blob: ae0d412a4deddb955d47ebfd66304223ed19a981 [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 */
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +0200509__LJMP static int hlua_arg2lua(lua_State *L, const struct arg *arg);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100510static 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);
Aurelien DARRAGON41217722023-05-17 10:44:47 +0200513__LJMP static int hlua_smp2lua(lua_State *L, struct sample *smp);
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +0200514__LJMP static 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 */
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +0200767__LJMP static int hlua_arg2lua(lua_State *L, const struct arg *arg)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100768{
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.
Aurelien DARRAGON0aaf6c42023-05-17 15:33:59 +0200801 *
802 * Note: although lua_tolstring() may raise a memory error according to
803 * lua documentation, in practise this could only happen when using to
804 * use lua_tolstring() on a number (lua will try to push the number as a
805 * string on the stack, and this may result in memory failure), so here we
806 * assume that hlua_lua2arg() will never raise an exception since it is
807 * exclusively used with lua string inputs.
808 *
809 * Note2: You should be extra careful when using <arg> argument, since
810 * string arguments rely on lua_tolstring() which returns a pointer to lua
811 * object that may be garbage collected at any time when removed from lua
812 * stack, thus you should make sure that <arg> is only used from a local
813 * scope within lua context (and not exported or stored in a lua-independent
814 * ctx) and that related lua object still exists when accessing arg data.
815 * See: https://www.lua.org/manual/5.4/manual.html#4.1.3
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100816 */
817static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
818{
819 switch (lua_type(L, ud)) {
820
821 case LUA_TNUMBER:
822 case LUA_TBOOLEAN:
823 arg->type = ARGT_SINT;
824 arg->data.sint = lua_tointeger(L, ud);
825 break;
826
827 case LUA_TSTRING:
828 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200829 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200830 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200831 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200832 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100833 break;
834
835 case LUA_TUSERDATA:
836 case LUA_TNIL:
837 case LUA_TTABLE:
838 case LUA_TFUNCTION:
839 case LUA_TTHREAD:
840 case LUA_TLIGHTUSERDATA:
841 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200842 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100843 break;
844 }
845 return 1;
846}
847
848/* the following functions are used to convert a struct sample
849 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500850 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100851 */
Aurelien DARRAGON41217722023-05-17 10:44:47 +0200852__LJMP static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100853{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200854 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100855 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100856 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200857 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100858 break;
859
860 case SMP_T_BIN:
861 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200862 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100863 break;
864
865 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200866 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100867 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
868 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
869 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
870 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
871 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
872 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
873 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
874 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
875 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200876 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100877 break;
878 default:
879 lua_pushnil(L);
880 break;
881 }
882 break;
883
884 case SMP_T_IPV4:
885 case SMP_T_IPV6:
886 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200887 if (sample_casts[smp->data.type][SMP_T_STR] &&
888 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200889 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100890 else
891 lua_pushnil(L);
892 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100893 default:
894 lua_pushnil(L);
895 break;
896 }
897 return 1;
898}
899
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100900/* the following functions are used to convert a struct sample
901 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500902 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100903 */
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +0200904__LJMP static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100905{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200906 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100907
908 case SMP_T_BIN:
909 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200910 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100911 break;
912
913 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200914 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100915 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
916 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
917 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
918 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
919 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
920 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
921 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
922 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
923 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200924 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100925 break;
926 default:
927 lua_pushstring(L, "");
928 break;
929 }
930 break;
931
932 case SMP_T_SINT:
933 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100934 case SMP_T_IPV4:
935 case SMP_T_IPV6:
936 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200937 if (sample_casts[smp->data.type][SMP_T_STR] &&
938 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200939 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100940 else
941 lua_pushstring(L, "");
942 break;
943 default:
944 lua_pushstring(L, "");
945 break;
946 }
947 return 1;
948}
949
Aurelien DARRAGONa3624cb2023-05-17 15:44:45 +0200950/* The following function is used to convert a Lua type to a
951 * struct sample. This is useful to provide data from LUA code to
952 * a converter.
953 *
954 * Note: although lua_tolstring() may raise a memory error according to
955 * lua documentation, in practise this could only happen when using to
956 * use lua_tolstring() on a number (lua will try to push the number as a
957 * string on the stack, and this may result in memory failure), so here we
958 * assume that hlua_lua2arg() will never raise an exception since it is
959 * exclusively used with lua string inputs.
960 *
961 * Note2: You should be extra careful when using <smp> argument, since
962 * string arguments rely on lua_tolstring() which returns a pointer to lua
963 * object that may be garbage collected at any time when removed from lua
964 * stack, thus you should make sure that <smp> is only used from a local
965 * scope within lua context (not exported or stored in a lua-independent
966 * ctx) and that related lua object still exists when accessing arg data.
967 * See: https://www.lua.org/manual/5.4/manual.html#4.1.3
968 *
969 * If you don't comply with this usage restriction, then you should consider
970 * duplicating the smp using smp_dup() to make it portable (little overhead),
971 * as this will ensure that the smp always points to valid memory block.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100972 */
973static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
974{
975 switch (lua_type(L, ud)) {
976
977 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200978 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200979 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100980 break;
981
982
983 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200984 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200985 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100986 break;
987
988 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200989 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100990 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200991 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200992 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200993 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200994 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100995 break;
996
997 case LUA_TUSERDATA:
998 case LUA_TNIL:
999 case LUA_TTABLE:
1000 case LUA_TFUNCTION:
1001 case LUA_TTHREAD:
1002 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +02001003 case LUA_TNONE:
1004 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001005 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001006 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001007 break;
1008 }
1009 return 1;
1010}
1011
Ilya Shipitsind4259502020-04-08 01:07:56 +05001012/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001013 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001014 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001015 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001016 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +02001017 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001018 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001019__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +01001020 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001021{
1022 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001023 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001024 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +02001025 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001026 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001027 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001028 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001029
1030 idx = 0;
1031 min_arg = ARGM(mask);
1032 mask >>= ARGM_BITS;
1033
1034 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001035 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001036
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001037 /* Check for mandatory arguments. */
1038 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001039 if (idx < min_arg) {
1040
1041 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001042 if (idx > 0) {
1043 msg = "Mandatory argument expected";
1044 goto error;
1045 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001046
1047 /* If first argument have a certain type, some default values
1048 * may be used. See the function smp_resolve_args().
1049 */
1050 switch (mask & ARGT_MASK) {
1051
1052 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001053 if (!(p->cap & PR_CAP_FE)) {
1054 msg = "Mandatory argument expected";
1055 goto error;
1056 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001057 argp[idx].data.prx = p;
1058 argp[idx].type = ARGT_FE;
1059 argp[idx+1].type = ARGT_STOP;
1060 break;
1061
1062 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001063 if (!(p->cap & PR_CAP_BE)) {
1064 msg = "Mandatory argument expected";
1065 goto error;
1066 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001067 argp[idx].data.prx = p;
1068 argp[idx].type = ARGT_BE;
1069 argp[idx+1].type = ARGT_STOP;
1070 break;
1071
1072 case ARGT_TAB:
Olivier Houchard14f62682022-09-13 00:35:53 +02001073 if (!p->table) {
1074 msg = "Mandatory argument expected";
1075 goto error;
1076 }
1077 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001078 argp[idx].type = ARGT_TAB;
1079 argp[idx+1].type = ARGT_STOP;
1080 break;
1081
1082 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001083 msg = "Mandatory argument expected";
1084 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001085 break;
1086 }
1087 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001088 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001089 }
1090
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001091 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001092 if ((mask & ARGT_MASK) == ARGT_STOP &&
1093 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001094 msg = "Last argument expected";
1095 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001096 }
1097
1098 if ((mask & ARGT_MASK) == ARGT_STOP &&
1099 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001100 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001101 }
1102
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001103 /* Convert some argument types. All string in argp[] are for not
1104 * duplicated yet.
1105 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001106 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001107 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001108 if (argp[idx].type != ARGT_SINT) {
1109 msg = "integer expected";
1110 goto error;
1111 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001112 argp[idx].type = ARGT_SINT;
1113 break;
1114
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001115 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001116 if (argp[idx].type != ARGT_SINT) {
1117 msg = "integer expected";
1118 goto error;
1119 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001120 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001121 break;
1122
1123 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001124 if (argp[idx].type != ARGT_SINT) {
1125 msg = "integer expected";
1126 goto error;
1127 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001128 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001129 break;
1130
1131 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001132 if (argp[idx].type != ARGT_STR) {
1133 msg = "string expected";
1134 goto error;
1135 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001136 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001137 if (!argp[idx].data.prx) {
1138 msg = "frontend doesn't exist";
1139 goto error;
1140 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001141 argp[idx].type = ARGT_FE;
1142 break;
1143
1144 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001145 if (argp[idx].type != ARGT_STR) {
1146 msg = "string expected";
1147 goto error;
1148 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001149 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001150 if (!argp[idx].data.prx) {
1151 msg = "backend doesn't exist";
1152 goto error;
1153 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001154 argp[idx].type = ARGT_BE;
1155 break;
1156
1157 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001158 if (argp[idx].type != ARGT_STR) {
1159 msg = "string expected";
1160 goto error;
1161 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001162 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001163 if (!argp[idx].data.t) {
1164 msg = "table doesn't exist";
1165 goto error;
1166 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001167 argp[idx].type = ARGT_TAB;
1168 break;
1169
1170 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001171 if (argp[idx].type != ARGT_STR) {
1172 msg = "string expected";
1173 goto error;
1174 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001175 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001176 if (sname) {
1177 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001178 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001179 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001180 if (!px) {
1181 msg = "backend doesn't exist";
1182 goto error;
1183 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001184 }
1185 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001186 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001187 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001188 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001189 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001190 if (!argp[idx].data.srv) {
1191 msg = "server doesn't exist";
1192 goto error;
1193 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001194 argp[idx].type = ARGT_SRV;
1195 break;
1196
1197 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001198 if (argp[idx].type != ARGT_STR) {
1199 msg = "string expected";
1200 goto error;
1201 }
1202 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1203 msg = "invalid IPv4 address";
1204 goto error;
1205 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001206 argp[idx].type = ARGT_IPV4;
1207 break;
1208
1209 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001210 if (argp[idx].type == ARGT_SINT)
1211 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1212 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001213 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1214 msg = "invalid IPv4 mask";
1215 goto error;
1216 }
1217 }
1218 else {
1219 msg = "integer or string expected";
1220 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001221 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001222 argp[idx].type = ARGT_MSK4;
1223 break;
1224
1225 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001226 if (argp[idx].type != ARGT_STR) {
1227 msg = "string expected";
1228 goto error;
1229 }
1230 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1231 msg = "invalid IPv6 address";
1232 goto error;
1233 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001234 argp[idx].type = ARGT_IPV6;
1235 break;
1236
1237 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001238 if (argp[idx].type == ARGT_SINT)
1239 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1240 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001241 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1242 msg = "invalid IPv6 mask";
1243 goto error;
1244 }
1245 }
1246 else {
1247 msg = "integer or string expected";
1248 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001249 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001250 argp[idx].type = ARGT_MSK6;
1251 break;
1252
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001253 case ARGT_REG:
1254 if (argp[idx].type != ARGT_STR) {
1255 msg = "string expected";
1256 goto error;
1257 }
1258 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1259 if (!reg) {
1260 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1261 argp[idx].data.str.area, err);
1262 free(err);
1263 goto error;
1264 }
1265 argp[idx].type = ARGT_REG;
1266 argp[idx].data.reg = reg;
1267 break;
1268
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001269 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001270 if (argp[idx].type != ARGT_STR) {
1271 msg = "string expected";
1272 goto error;
1273 }
1274 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001275 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001276 ul = p->uri_auth->userlist;
1277 else
1278 ul = auth_find_userlist(argp[idx].data.str.area);
1279
1280 if (!ul) {
1281 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1282 goto error;
1283 }
1284 argp[idx].type = ARGT_USR;
1285 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001286 break;
1287
1288 case ARGT_STR:
1289 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1290 msg = "unable to duplicate string arg";
1291 goto error;
1292 }
1293 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001294 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001295
Christopher Fauletd25d9262020-08-06 11:04:46 +02001296 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001297 msg = "type not yet supported";
1298 goto error;
1299 break;
1300
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001301 }
1302
1303 /* Check for type of argument. */
1304 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001305 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1306 arg_type_names[(mask & ARGT_MASK)],
1307 arg_type_names[argp[idx].type & ARGT_MASK]);
1308 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001309 }
1310
1311 /* Next argument. */
1312 mask >>= ARGT_BITS;
1313 idx++;
1314 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001315 return 0;
1316
1317 error:
Olivier Houchardca431612022-09-13 00:31:17 +02001318 argp[idx].type = ARGT_STOP;
Willy Tarreauee0d7272021-07-16 10:26:56 +02001319 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001320 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1321 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001322}
1323
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001324/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001325 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001326 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001327 *
1328 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001329 * - hlua_sethlua : create the association between hlua context and lua_state.
1330 */
Aurelien DARRAGON40cd44f2023-05-04 13:59:48 +02001331inline struct hlua *hlua_gethlua(lua_State *L)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001332{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001333 struct hlua **hlua = lua_getextraspace(L);
1334 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001335}
1336static inline void hlua_sethlua(struct hlua *hlua)
1337{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001338 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1339 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001340}
1341
Willy Tarreau0b7b6392022-06-19 17:39:33 +02001342/* Will return a non-NULL string indicating the Lua call trace if the caller
1343 * currently is executing from within a Lua function. One line per entry will
1344 * be emitted, and each extra line will be prefixed with <pfx>. If a current
1345 * Lua function is not detected, NULL is returned.
1346 */
1347const char *hlua_show_current_location(const char *pfx)
1348{
1349 lua_State *L;
1350 lua_Debug ar;
1351
1352 /* global or per-thread stack initializing ? */
1353 if (hlua_state_id != -1 && (L = hlua_states[hlua_state_id]) && lua_getstack(L, 0, &ar))
1354 return hlua_traceback(L, pfx);
1355
1356 /* per-thread stack running ? */
1357 if (hlua_states[tid + 1] && (L = hlua_states[tid + 1]) && lua_getstack(L, 0, &ar))
1358 return hlua_traceback(L, pfx);
1359
1360 /* global stack running ? */
1361 if (hlua_states[0] && (L = hlua_states[0]) && lua_getstack(L, 0, &ar))
1362 return hlua_traceback(L, pfx);
1363
1364 return NULL;
1365}
1366
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001367/* This function is used to send logs. It try to send on screen (stderr)
1368 * and on the default syslog server.
1369 */
1370static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1371{
1372 struct tm tm;
1373 char *p;
1374
1375 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001376 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001377 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001378 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001379 /* Break the message if exceed the buffer size. */
1380 *(p-4) = ' ';
1381 *(p-3) = '.';
1382 *(p-2) = '.';
1383 *(p-1) = '.';
1384 break;
1385 }
Willy Tarreau90807112020-02-25 08:16:33 +01001386 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001387 *p = *msg;
1388 else
1389 *p = '.';
1390 }
1391 *p = '\0';
1392
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001393 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001394 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001395 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1396 return;
1397
Willy Tarreaua678b432015-08-28 10:14:59 +02001398 get_localtime(date.tv_sec, &tm);
1399 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001400 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001401 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001402 fflush(stderr);
1403 }
1404}
1405
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001406/* This function just ensure that the yield will be always
1407 * returned with a timeout and permit to set some flags
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02001408 * <timeout> is a tick value
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001409 */
1410__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001411 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001412{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001413 struct hlua *hlua;
1414
1415 /* Get hlua struct, or NULL if we execute from main lua state */
1416 hlua = hlua_gethlua(L);
1417 if (!hlua) {
1418 return;
1419 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001420
1421 /* Set the wake timeout. If timeout is required, we set
1422 * the expiration time.
1423 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001424 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001425
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001426 hlua->flags |= flags;
1427
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001428 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001429 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001430}
1431
Willy Tarreau87b09662015-04-03 00:22:06 +02001432/* This function initialises the Lua environment stored in the stream.
1433 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001434 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001435 *
1436 * This function is particular. it initialises a new Lua thread. If the
1437 * initialisation fails (example: out of memory error), the lua function
1438 * throws an error (longjmp).
1439 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001440 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001441 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001442 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001443 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001444 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001445int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001446{
1447 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001448 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001449 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001450 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001451 lua->state_id = state_id;
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001452 hlua_timer_init(&lua->timer, 0); /* default value, no timeout */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001453 LIST_INIT(&lua->com);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001454 MT_LIST_INIT(&lua->hc_list);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001455 if (!SET_SAFE_LJMP_PARENT(lua)) {
1456 lua->Tref = LUA_REFNIL;
1457 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001458 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001459 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001460 if (!lua->T) {
1461 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001462 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001463 return 0;
1464 }
1465 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001466 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001467 lua->task = task;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01001468 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001469 return 1;
1470}
1471
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001472/* kill all associated httpclient to this hlua task
1473 * We must take extra precautions as we're manipulating lua-exposed
1474 * objects without the main lua lock.
1475 */
William Lallemandbb581422022-10-20 10:57:28 +02001476static void hlua_httpclient_destroy_all(struct hlua *hlua)
1477{
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001478 struct hlua_httpclient *hlua_hc;
William Lallemandbb581422022-10-20 10:57:28 +02001479
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01001480 /* use thread-safe accessors for hc_list since GC cycle initiated by
1481 * another thread sharing the same main lua stack (lua coroutine)
1482 * could execute hlua_httpclient_gc() on the hlua->hc_list items
1483 * in parallel: Lua GC applies on the main stack, it is not limited to
1484 * a single coroutine stack, see Github issue #2037 for reference.
1485 * Remember, coroutines created using lua_newthread() are not meant to
1486 * be thread safe in Lua. (From lua co-author:
1487 * http://lua-users.org/lists/lua-l/2011-07/msg00072.html)
1488 *
1489 * This security measure is superfluous when 'lua-load-per-thread' is used
1490 * since in this case coroutines exclusively run on the same thread
1491 * (main stack is not shared between OS threads).
1492 */
1493 while ((hlua_hc = MT_LIST_POP(&hlua->hc_list, typeof(hlua_hc), by_hlua))) {
1494 httpclient_stop_and_destroy(hlua_hc->hc);
William Lallemandbb581422022-10-20 10:57:28 +02001495 hlua_hc->hc = NULL;
William Lallemandbb581422022-10-20 10:57:28 +02001496 }
1497}
1498
1499
Willy Tarreau87b09662015-04-03 00:22:06 +02001500/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001501 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGON60ab0f72023-03-01 16:45:50 +01001502 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001503 */
1504void hlua_ctx_destroy(struct hlua *lua)
1505{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001506 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001507 return;
1508
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001509 if (!lua->T)
1510 goto end;
1511
William Lallemandbb581422022-10-20 10:57:28 +02001512 /* clean all running httpclient */
1513 hlua_httpclient_destroy_all(lua);
1514
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001515 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001516 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001517
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001518 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001519 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001520 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001521 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001522
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001523 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001524 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001525 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001526 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001527 /* Forces a garbage collecting process. If the Lua program is finished
1528 * without error, we run the GC on the thread pointer. Its freed all
1529 * the unused memory.
1530 * If the thread is finnish with an error or is currently yielded,
1531 * it seems that the GC applied on the thread doesn't clean anything,
1532 * so e run the GC on the main thread.
1533 * NOTE: maybe this action locks all the Lua threads untiml the en of
1534 * the garbage collection.
1535 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001536 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001537 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001538 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001539 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001540 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001541 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001542
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001543 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001544
1545end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001546 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001547}
1548
1549/* This function is used to restore the Lua context when a coroutine
1550 * fails. This function copy the common memory between old coroutine
1551 * and the new coroutine. The old coroutine is destroyed, and its
1552 * replaced by the new coroutine.
1553 * If the flag "keep_msg" is set, the last entry of the old is assumed
1554 * as string error message and it is copied in the new stack.
1555 */
1556static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1557{
1558 lua_State *T;
1559 int new_ref;
1560
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001561 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001562 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001563 if (!T)
1564 return 0;
1565
1566 /* Copy last error message. */
1567 if (keep_msg)
1568 lua_xmove(lua->T, T, 1);
1569
1570 /* Copy data between the coroutines. */
1571 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1572 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001573 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001574
1575 /* Destroy old data. */
1576 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1577
1578 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001579 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001580
1581 /* Fill the struct with the new coroutine values. */
1582 lua->Mref = new_ref;
1583 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001584 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001585
1586 /* Set context. */
1587 hlua_sethlua(lua);
1588
1589 return 1;
1590}
1591
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001592void hlua_hook(lua_State *L, lua_Debug *ar)
1593{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001594 struct hlua *hlua;
1595
1596 /* Get hlua struct, or NULL if we execute from main lua state */
1597 hlua = hlua_gethlua(L);
1598 if (!hlua)
1599 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001600
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001601 if (hlua->T != L) {
1602 /* We don't want to enforce a yield on a sub coroutine, since
1603 * we have no guarantees that the yield will be handled properly.
1604 * Indeed, only the hlua->T coroutine is being handled through
1605 * hlua_ctx_resume() function.
1606 *
1607 * Instead, we simply check for timeouts and wait for the sub
1608 * coroutine to finish..
1609 */
1610 goto check_timeout;
1611 }
1612
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001613 /* Lua cannot yield when its returning from a function,
1614 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001615 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001616 */
1617 if (lua_gethookmask(L) & LUA_MASKRET) {
1618 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1619 return;
1620 }
1621
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001622 /* If we interrupt the Lua processing in yieldable state, we yield.
1623 * If the state is not yieldable, trying yield causes an error.
1624 */
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001625 if (lua_isyieldable(L)) {
1626 /* note: for converters/fetches.. where yielding is not allowed
1627 * hlua_ctx_resume() will simply perform a goto resume_execution
1628 * instead of rescheduling hlua->task.
1629 * also: hlua_ctx_resume() will take care of checking execution
1630 * timeout and re-applying the hook as needed.
1631 */
Willy Tarreau9635e032018-10-16 17:52:55 +02001632 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Aurelien DARRAGON0ebd41f2022-11-24 09:51:40 +01001633 /* lua docs says that the hook should return immediately after lua_yieldk
1634 *
1635 * From: https://www.lua.org/manual/5.3/manual.html#lua_yieldk
1636 *
1637 * Moreover, it seems that we don't want to continue after the yield
1638 * because the end of the function is about handling unyieldable function,
1639 * which is not the case here.
1640 *
1641 * ->if we don't return lua_sethook gets incorrectly set with MASKRET later
1642 * in the function.
1643 */
1644 return;
1645 }
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001646
Aurelien DARRAGONcf0f7922023-04-07 16:34:20 +02001647 check_timeout:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001648 /* If we cannot yield, check the timeout. */
1649 if (!hlua_timer_check(&hlua->timer)) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001650 lua_pushfstring(L, "execution timeout");
1651 WILL_LJMP(lua_error(L));
1652 }
1653
1654 /* Try to interrupt the process at the end of the current
1655 * unyieldable function.
1656 */
1657 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001658}
1659
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001660/* This function start or resumes the Lua stack execution. If the flag
1661 * "yield_allowed" if no set and the LUA stack execution returns a yield
1662 * The function return an error.
1663 *
1664 * The function can returns 4 values:
1665 * - HLUA_E_OK : The execution is terminated without any errors.
1666 * - HLUA_E_AGAIN : The execution must continue at the next associated
1667 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001668 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001669 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001670 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001671 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001672 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001673 * LUA code.
1674 */
1675static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1676{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001677#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1678 int nres;
1679#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001680 int ret;
1681 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001682 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001683
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001684 /* Lock the whole Lua execution. This lock must be before the
1685 * label "resume_execution".
1686 */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001687 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001688
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001689 /* reset the timer as we might be re-entering the function to
1690 * resume the coroutine after a successful yield
1691 * (cumulative time will be updated)
1692 */
1693 hlua_timer_reset(&lua->timer);
1694
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001695resume_execution:
1696
1697 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1698 * instructions. it is used for preventing infinite loops.
1699 */
1700 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1701
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001702 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001703 HLUA_SET_RUN(lua);
1704 HLUA_CLR_CTRLYIELD(lua);
1705 HLUA_CLR_WAKERESWR(lua);
1706 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001707 HLUA_CLR_NOYIELD(lua);
1708 if (!yield_allowed)
1709 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001710
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001711 /* reset wake_time. */
Christopher Fauletbc275a92020-02-26 14:55:16 +01001712 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001713
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001714 /* start the timer as we're about to start lua processing */
1715 hlua_timer_start(&lua->timer);
1716
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001717 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001718#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001719 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001720#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001721 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001722#endif
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001723
1724 /* out of lua processing, stop the timer */
1725 hlua_timer_stop(&lua->timer);
1726
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001727 switch (ret) {
1728
1729 case LUA_OK:
1730 ret = HLUA_E_OK;
1731 break;
1732
1733 case LUA_YIELD:
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001734 /* Check if the execution timeout is expired. If it is the case, we
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001735 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001736 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01001737 if (!hlua_timer_check(&lua->timer)) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001738 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001739 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001740 break;
1741 }
1742 /* Process the forced yield. if the general yield is not allowed or
1743 * if no task were associated this the current Lua execution
1744 * coroutine, we resume the execution. Else we want to return in the
1745 * scheduler and we want to be waked up again, to continue the
1746 * current Lua execution. So we schedule our own task.
1747 */
1748 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001749 if (!yield_allowed || !lua->task)
1750 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001751 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001752 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001753 if (!yield_allowed) {
1754 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001755 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001756 break;
1757 }
1758 ret = HLUA_E_AGAIN;
1759 break;
1760
1761 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001762
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001763 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001764 * because the errors ares the only one mean to return immediately
1765 * from and lua execution.
1766 */
1767 if (lua->flags & HLUA_EXIT) {
1768 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001769 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001770 break;
1771 }
1772
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001773 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001774 if (!lua_checkstack(lua->T, 1)) {
1775 ret = HLUA_E_ERR;
1776 break;
1777 }
1778 msg = lua_tostring(lua->T, -1);
1779 lua_settop(lua->T, 0); /* Empty the stack. */
1780 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001781 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001782 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001783 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001784 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001785 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001786 ret = HLUA_E_ERRMSG;
1787 break;
1788
1789 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001790 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001791 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001792 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001793 break;
1794
1795 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001796 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001797 if (!lua_checkstack(lua->T, 1)) {
1798 ret = HLUA_E_ERR;
1799 break;
1800 }
1801 msg = lua_tostring(lua->T, -1);
1802 lua_settop(lua->T, 0); /* Empty the stack. */
1803 lua_pop(lua->T, 1);
1804 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001805 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001806 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001807 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001808 ret = HLUA_E_ERRMSG;
1809 break;
1810
1811 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001812 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001813 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001814 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001815 break;
1816 }
1817
1818 switch (ret) {
1819 case HLUA_E_AGAIN:
1820 break;
1821
1822 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001823 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001824 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001825 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001826 break;
1827
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001828 case HLUA_E_ETMOUT:
1829 case HLUA_E_NOMEM:
1830 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001831 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001832 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001833 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001834 hlua_ctx_renew(lua, 0);
1835 break;
1836
1837 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001838 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001839 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001840 break;
1841 }
1842
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001843 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe36f8032023-03-21 13:22:33 +01001844 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001845
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001846 return ret;
1847}
1848
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001849/* This function exit the current code. */
1850__LJMP static int hlua_done(lua_State *L)
1851{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001852 struct hlua *hlua;
1853
1854 /* Get hlua struct, or NULL if we execute from main lua state */
1855 hlua = hlua_gethlua(L);
1856 if (!hlua)
1857 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001858
1859 hlua->flags |= HLUA_EXIT;
1860 WILL_LJMP(lua_error(L));
1861
1862 return 0;
1863}
1864
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001865/* This function is an LUA binding. It provides a function
1866 * for deleting ACL from a referenced ACL file.
1867 */
1868__LJMP static int hlua_del_acl(lua_State *L)
1869{
1870 const char *name;
1871 const char *key;
1872 struct pat_ref *ref;
1873
1874 MAY_LJMP(check_args(L, 2, "del_acl"));
1875
1876 name = MAY_LJMP(luaL_checkstring(L, 1));
1877 key = MAY_LJMP(luaL_checkstring(L, 2));
1878
1879 ref = pat_ref_lookup(name);
1880 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001881 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001882
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001883 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001884 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001885 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001886 return 0;
1887}
1888
1889/* This function is an LUA binding. It provides a function
1890 * for deleting map entry from a referenced map file.
1891 */
1892static int hlua_del_map(lua_State *L)
1893{
1894 const char *name;
1895 const char *key;
1896 struct pat_ref *ref;
1897
1898 MAY_LJMP(check_args(L, 2, "del_map"));
1899
1900 name = MAY_LJMP(luaL_checkstring(L, 1));
1901 key = MAY_LJMP(luaL_checkstring(L, 2));
1902
1903 ref = pat_ref_lookup(name);
1904 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001905 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001906
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001907 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001908 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001909 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001910 return 0;
1911}
1912
1913/* This function is an LUA binding. It provides a function
1914 * for adding ACL pattern from a referenced ACL file.
1915 */
1916static int hlua_add_acl(lua_State *L)
1917{
1918 const char *name;
1919 const char *key;
1920 struct pat_ref *ref;
1921
1922 MAY_LJMP(check_args(L, 2, "add_acl"));
1923
1924 name = MAY_LJMP(luaL_checkstring(L, 1));
1925 key = MAY_LJMP(luaL_checkstring(L, 2));
1926
1927 ref = pat_ref_lookup(name);
1928 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001929 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001930
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001931 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001932 if (pat_ref_find_elt(ref, key) == NULL)
1933 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001934 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001935 return 0;
1936}
1937
1938/* This function is an LUA binding. It provides a function
1939 * for setting map pattern and sample from a referenced map
1940 * file.
1941 */
1942static int hlua_set_map(lua_State *L)
1943{
1944 const char *name;
1945 const char *key;
1946 const char *value;
1947 struct pat_ref *ref;
1948
1949 MAY_LJMP(check_args(L, 3, "set_map"));
1950
1951 name = MAY_LJMP(luaL_checkstring(L, 1));
1952 key = MAY_LJMP(luaL_checkstring(L, 2));
1953 value = MAY_LJMP(luaL_checkstring(L, 3));
1954
1955 ref = pat_ref_lookup(name);
1956 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001957 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001958
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001959 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001960 if (pat_ref_find_elt(ref, key) != NULL)
1961 pat_ref_set(ref, key, value, NULL);
1962 else
1963 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001964 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001965 return 0;
1966}
1967
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +02001968/* This function disables the sending of email through the
1969 * legacy email sending function which is implemented using
1970 * checks.
1971 *
1972 * It may not be used during runtime.
1973 */
1974__LJMP static int hlua_disable_legacy_mailers(lua_State *L)
1975{
1976 if (hlua_gethlua(L))
1977 WILL_LJMP(luaL_error(L, "disable_legacy_mailers: "
1978 "not available outside of init or body context"));
1979 send_email_disabled = 1;
1980 return 0;
1981}
1982
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001983/* A class is a lot of memory that contain data. This data can be a table,
1984 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001985 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001986 * the name of the object (_G[<name>] = <metable> ).
1987 *
1988 * A metable is a table that modify the standard behavior of a standard
1989 * access to the associated data. The entries of this new metatable are
1990 * defined as is:
1991 *
1992 * http://lua-users.org/wiki/MetatableEvents
1993 *
1994 * __index
1995 *
1996 * we access an absent field in a table, the result is nil. This is
1997 * true, but it is not the whole truth. Actually, such access triggers
1998 * the interpreter to look for an __index metamethod: If there is no
1999 * such method, as usually happens, then the access results in nil;
2000 * otherwise, the metamethod will provide the result.
2001 *
2002 * Control 'prototype' inheritance. When accessing "myTable[key]" and
2003 * the key does not appear in the table, but the metatable has an __index
2004 * property:
2005 *
2006 * - if the value is a function, the function is called, passing in the
2007 * table and the key; the return value of that function is returned as
2008 * the result.
2009 *
2010 * - if the value is another table, the value of the key in that table is
2011 * asked for and returned (and if it doesn't exist in that table, but that
2012 * table's metatable has an __index property, then it continues on up)
2013 *
2014 * - Use "rawget(myTable,key)" to skip this metamethod.
2015 *
2016 * http://www.lua.org/pil/13.4.1.html
2017 *
2018 * __newindex
2019 *
2020 * Like __index, but control property assignment.
2021 *
2022 * __mode - Control weak references. A string value with one or both
2023 * of the characters 'k' and 'v' which specifies that the the
2024 * keys and/or values in the table are weak references.
2025 *
2026 * __call - Treat a table like a function. When a table is followed by
2027 * parenthesis such as "myTable( 'foo' )" and the metatable has
2028 * a __call key pointing to a function, that function is invoked
2029 * (passing any specified arguments) and the return value is
2030 * returned.
2031 *
2032 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
2033 * called, if the metatable for myTable has a __metatable
2034 * key, the value of that key is returned instead of the
2035 * actual metatable.
2036 *
2037 * __tostring - Control string representation. When the builtin
2038 * "tostring( myTable )" function is called, if the metatable
2039 * for myTable has a __tostring property set to a function,
2040 * that function is invoked (passing myTable to it) and the
2041 * return value is used as the string representation.
2042 *
2043 * __len - Control table length. When the table length is requested using
2044 * the length operator ( '#' ), if the metatable for myTable has
2045 * a __len key pointing to a function, that function is invoked
2046 * (passing myTable to it) and the return value used as the value
2047 * of "#myTable".
2048 *
2049 * __gc - Userdata finalizer code. When userdata is set to be garbage
2050 * collected, if the metatable has a __gc field pointing to a
2051 * function, that function is first invoked, passing the userdata
2052 * to it. The __gc metamethod is not called for tables.
2053 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
2054 *
2055 * Special metamethods for redefining standard operators:
2056 * http://www.lua.org/pil/13.1.html
2057 *
2058 * __add "+"
2059 * __sub "-"
2060 * __mul "*"
2061 * __div "/"
2062 * __unm "!"
2063 * __pow "^"
2064 * __concat ".."
2065 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002066 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002067 * http://www.lua.org/pil/13.2.html
2068 *
2069 * __eq "=="
2070 * __lt "<"
2071 * __le "<="
2072 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002073
2074/*
2075 *
2076 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002077 * Class Map
2078 *
2079 *
2080 */
2081
2082/* Returns a struct hlua_map if the stack entry "ud" is
2083 * a class session, otherwise it throws an error.
2084 */
2085__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
2086{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002087 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002088}
2089
2090/* This function is the map constructor. It don't need
2091 * the class Map object. It creates and return a new Map
2092 * object. It must be called only during "body" or "init"
2093 * context because it process some filesystem accesses.
2094 */
2095__LJMP static int hlua_map_new(struct lua_State *L)
2096{
2097 const char *fn;
2098 int match = PAT_MATCH_STR;
2099 struct sample_conv conv;
2100 const char *file = "";
2101 int line = 0;
2102 lua_Debug ar;
2103 char *err = NULL;
2104 struct arg args[2];
2105
2106 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
2107 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
2108
2109 fn = MAY_LJMP(luaL_checkstring(L, 1));
2110
2111 if (lua_gettop(L) >= 2) {
2112 match = MAY_LJMP(luaL_checkinteger(L, 2));
2113 if (match < 0 || match >= PAT_MATCH_NUM)
2114 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
2115 }
2116
2117 /* Get Lua filename and line number. */
2118 if (lua_getstack(L, 1, &ar)) { /* check function at level */
2119 lua_getinfo(L, "Sl", &ar); /* get info about it */
2120 if (ar.currentline > 0) { /* is there info? */
2121 file = ar.short_src;
2122 line = ar.currentline;
2123 }
2124 }
2125
2126 /* fill fake sample_conv struct. */
2127 conv.kw = ""; /* unused. */
2128 conv.process = NULL; /* unused. */
2129 conv.arg_mask = 0; /* unused. */
2130 conv.val_args = NULL; /* unused. */
2131 conv.out_type = SMP_T_STR;
2132 conv.private = (void *)(long)match;
2133 switch (match) {
2134 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
2135 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
2136 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
2137 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
2138 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
2139 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
2140 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002141 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002142 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
2143 default:
2144 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
2145 }
2146
2147 /* fill fake args. */
2148 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02002149 args[0].data.str.area = strdup(fn);
2150 args[0].data.str.data = strlen(fn);
2151 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002152 args[1].type = ARGT_STOP;
2153
2154 /* load the map. */
2155 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002156 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002157 * free the err variable.
2158 */
2159 luaL_where(L, 1);
2160 lua_pushfstring(L, "'new': %s.", err);
2161 lua_concat(L, 2);
2162 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002163 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002164 WILL_LJMP(lua_error(L));
2165 }
2166
2167 /* create the lua object. */
2168 lua_newtable(L);
2169 lua_pushlightuserdata(L, args[0].data.map);
2170 lua_rawseti(L, -2, 0);
2171
2172 /* Pop a class Map metatable and affect it to the userdata. */
2173 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2174 lua_setmetatable(L, -2);
2175
2176
2177 return 1;
2178}
2179
2180__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2181{
2182 struct map_descriptor *desc;
2183 struct pattern *pat;
2184 struct sample smp;
2185
2186 MAY_LJMP(check_args(L, 2, "lookup"));
2187 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002188 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002189 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002190 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002191 }
2192 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002193 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002194 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002195 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 +01002196 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002197 }
2198
2199 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002200 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002201 if (str)
2202 lua_pushstring(L, "");
2203 else
2204 lua_pushnil(L);
2205 return 1;
2206 }
2207
2208 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002209 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002210 return 1;
2211}
2212
2213__LJMP static int hlua_map_lookup(struct lua_State *L)
2214{
2215 return _hlua_map_lookup(L, 0);
2216}
2217
2218__LJMP static int hlua_map_slookup(struct lua_State *L)
2219{
2220 return _hlua_map_lookup(L, 1);
2221}
2222
2223/*
2224 *
2225 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 * Class Socket
2227 *
2228 *
2229 */
2230
2231__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2232{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002233 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002234}
2235
2236/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002237 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 * received.
2239 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002240static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002241{
Willy Tarreau5321da92022-05-06 11:57:34 +02002242 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002243 struct stconn *sc = appctx_sc(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244
Christopher Faulet31572222023-03-31 11:13:48 +02002245 if (unlikely(se_fl_test(appctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW)))) {
Aurelien DARRAGONa2c53212023-05-02 19:10:24 +02002246 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
Christopher Faulet31572222023-03-31 11:13:48 +02002247 notification_wake(&ctx->wake_on_read);
2248 notification_wake(&ctx->wake_on_write);
2249 return;
2250 }
2251
Willy Tarreau5321da92022-05-06 11:57:34 +02002252 if (ctx->die) {
Christopher Faulet31572222023-03-31 11:13:48 +02002253 se_fl_set(appctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreau5321da92022-05-06 11:57:34 +02002254 notification_wake(&ctx->wake_on_read);
2255 notification_wake(&ctx->wake_on_write);
Christopher Faulet31572222023-03-31 11:13:48 +02002256 return;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002257 }
2258
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002259 /* If we can't write, wakeup the pending write signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002260 if (channel_output_closed(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002261 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002262
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002263 /* If we can't read, wakeup the pending read signals. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002264 if (channel_input_closed(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002265 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002266
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002267 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002268 * to be notified whenever the connection completes.
2269 */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002270 if (sc_opposite(sc)->state < SC_ST_EST) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02002271 applet_need_more_data(appctx);
Willy Tarreaub23edc82022-05-24 16:49:03 +02002272 se_need_remote_conn(appctx->sedesc);
Willy Tarreau4164eb92022-05-25 15:42:03 +02002273 applet_have_more_data(appctx);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002274 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002275 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276
2277 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002278 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002280 /* Wake the tasks which wants to write if the buffer have available space. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002281 if (channel_may_recv(sc_ic(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002282 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283
2284 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02002285 if (!channel_is_empty(sc_oc(sc)))
Willy Tarreau5321da92022-05-06 11:57:34 +02002286 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002287
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002288 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002289 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002290 */
Willy Tarreau5321da92022-05-06 11:57:34 +02002291 if (notification_registered(&ctx->wake_on_write))
Willy Tarreau4164eb92022-05-25 15:42:03 +02002292 applet_have_more_data(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293}
2294
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002295static int hlua_socket_init(struct appctx *appctx)
2296{
2297 struct hlua_csk_ctx *ctx = appctx->svcctx;
2298 struct stream *s;
2299
2300 if (appctx_finalize_startup(appctx, socket_proxy, &BUF_NULL) == -1)
2301 goto error;
2302
2303 s = appctx_strm(appctx);
2304
Willy Tarreau4596fe22022-05-17 19:07:51 +02002305 /* Configure "right" stream connector. This stconn is used to connect
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002306 * and retrieve data from the server. The connection is initialized
2307 * with the "struct server".
2308 */
Willy Tarreau74568cf2022-05-27 09:03:30 +02002309 sc_set_state(s->scb, SC_ST_ASS);
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002310
2311 /* Force destination server. */
2312 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2313 s->target = &socket_tcp->obj_type;
2314
2315 ctx->appctx = appctx;
2316 return 0;
2317
2318 error:
2319 return -1;
2320}
2321
Willy Tarreau87b09662015-04-03 00:22:06 +02002322/* This function is called when the "struct stream" is destroyed.
2323 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324 * Wake all the pending signals.
2325 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002326static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327{
Willy Tarreau5321da92022-05-06 11:57:34 +02002328 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002329 struct xref *peer;
2330
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02002331 /* Remove my link in the original objects. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002332 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002333 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002334 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002335
2336 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002337 notification_wake(&ctx->wake_on_read);
2338 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339}
2340
2341/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002342 * uses this object. If the stream does not exists, just quit.
2343 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002344 * pending signal can rest in the read and write lists. destroy
2345 * it.
2346 */
2347__LJMP static int hlua_socket_gc(lua_State *L)
2348{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002349 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002350 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002351 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002353 MAY_LJMP(check_args(L, 1, "__gc"));
2354
2355 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002356 peer = xref_get_peer_and_lock(&socket->xref);
2357 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002359
2360 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002362 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002363 ctx->die = 1;
2364 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002366 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002367 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002368 return 0;
2369}
2370
2371/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002372 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 */
sada05ed3302018-05-11 11:48:18 -07002374__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002376 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002377 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002378 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002379 struct hlua *hlua;
2380
2381 /* Get hlua struct, or NULL if we execute from main lua state */
2382 hlua = hlua_gethlua(L);
2383 if (!hlua)
2384 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002385
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002386 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002387
2388 /* Check if we run on the same thread than the xreator thread.
2389 * We cannot access to the socket if the thread is different.
2390 */
2391 if (socket->tid != tid)
2392 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2393
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002394 peer = xref_get_peer_and_lock(&socket->xref);
2395 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002397
2398 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002399 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002401 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002402 ctx->die = 1;
2403 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002404
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002405 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002406 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407 return 0;
2408}
2409
sada05ed3302018-05-11 11:48:18 -07002410/* The close function calls close_helper.
2411 */
2412__LJMP static int hlua_socket_close(lua_State *L)
2413{
2414 MAY_LJMP(check_args(L, 1, "close"));
2415 return hlua_socket_close_helper(L);
2416}
2417
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002418/* This Lua function assumes that the stack contain three parameters.
2419 * 1 - USERDATA containing a struct socket
2420 * 2 - INTEGER with values of the macro defined below
2421 * If the integer is -1, we must read at most one line.
2422 * If the integer is -2, we ust read all the data until the
2423 * end of the stream.
2424 * If the integer is positive value, we must read a number of
2425 * bytes corresponding to this value.
2426 */
2427#define HLSR_READ_LINE (-1)
2428#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002429__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002430{
2431 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2432 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002433 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002434 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002436 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002437 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002438 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002439 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002440 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002441 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002442 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002443 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002444 struct stream *s;
2445 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002446 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002448 /* Get hlua struct, or NULL if we execute from main lua state */
2449 hlua = hlua_gethlua(L);
2450
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002451 /* Check if this lua stack is schedulable. */
2452 if (!hlua || !hlua->task)
2453 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2454 "'frontend', 'backend' or 'task'"));
2455
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002456 /* Check if we run on the same thread than the xreator thread.
2457 * We cannot access to the socket if the thread is different.
2458 */
2459 if (socket->tid != tid)
2460 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2461
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002462 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002463 peer = xref_get_peer_and_lock(&socket->xref);
2464 if (!peer)
2465 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002466
2467 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2468 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002469 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002471 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002472 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002473 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002474 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002475 if (nblk < 0) /* Connection close. */
2476 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002477 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002478 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002479
2480 /* remove final \r\n. */
2481 if (nblk == 1) {
2482 if (blk1[len1-1] == '\n') {
2483 len1--;
2484 skip_at_end++;
2485 if (blk1[len1-1] == '\r') {
2486 len1--;
2487 skip_at_end++;
2488 }
2489 }
2490 }
2491 else {
2492 if (blk2[len2-1] == '\n') {
2493 len2--;
2494 skip_at_end++;
2495 if (blk2[len2-1] == '\r') {
2496 len2--;
2497 skip_at_end++;
2498 }
2499 }
2500 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002501 }
2502
2503 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002504 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002505 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506 if (nblk < 0) /* Connection close. */
2507 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002508 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509 goto connection_empty;
2510 }
2511
2512 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002513 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002514 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515 if (nblk < 0) /* Connection close. */
2516 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002517 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002518 goto connection_empty;
2519
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002520 missing_bytes = wanted - socket->b.n;
2521 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002522 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002523 len1 = missing_bytes;
2524 } if (nblk == 2 && len1 + len2 > missing_bytes)
2525 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002526 }
2527
2528 len = len1;
2529
2530 luaL_addlstring(&socket->b, blk1, len1);
2531 if (nblk == 2) {
2532 len += len2;
2533 luaL_addlstring(&socket->b, blk2, len2);
2534 }
2535
2536 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002537 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002538
2539 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002540 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002541
2542 /* If the pattern reclaim to read all the data
2543 * in the connection, got out.
2544 */
2545 if (wanted == HLSR_READ_ALL)
2546 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002547 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002548 goto connection_empty;
2549
2550 /* Return result. */
2551 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002552 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002553 return 1;
2554
2555connection_closed:
2556
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002557 xref_unlock(&socket->xref, peer);
2558
2559no_peer:
2560
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002561 /* If the buffer containds data. */
2562 if (socket->b.n > 0) {
2563 luaL_pushresult(&socket->b);
2564 return 1;
2565 }
2566 lua_pushnil(L);
2567 lua_pushstring(L, "connection closed.");
2568 return 2;
2569
2570connection_empty:
2571
Willy Tarreau5321da92022-05-06 11:57:34 +02002572 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002573 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002574 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002575 }
2576 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002577 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002578 return 0;
2579}
2580
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002581/* This Lua function gets two parameters. The first one can be string
2582 * or a number. If the string is "*l", the user requires one line. If
2583 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002584 * If the value is a number, the user require a number of bytes equal
2585 * to the value. The default value is "*l" (a line).
2586 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002587 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002588 * integer takes this values:
2589 * -1 : read a line
2590 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002591 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002592 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002593 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594 * concatenated with the read data.
2595 */
2596__LJMP static int hlua_socket_receive(struct lua_State *L)
2597{
2598 int wanted = HLSR_READ_LINE;
2599 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002600 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002601 char *error;
2602 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002603 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002604
2605 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2606 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2607
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002608 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002609
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002610 /* Check if we run on the same thread than the xreator thread.
2611 * We cannot access to the socket if the thread is different.
2612 */
2613 if (socket->tid != tid)
2614 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2615
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002616 /* check for pattern. */
2617 if (lua_gettop(L) >= 2) {
2618 type = lua_type(L, 2);
2619 if (type == LUA_TSTRING) {
2620 pattern = lua_tostring(L, 2);
2621 if (strcmp(pattern, "*a") == 0)
2622 wanted = HLSR_READ_ALL;
2623 else if (strcmp(pattern, "*l") == 0)
2624 wanted = HLSR_READ_LINE;
2625 else {
2626 wanted = strtoll(pattern, &error, 10);
2627 if (*error != '\0')
2628 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2629 }
2630 }
2631 else if (type == LUA_TNUMBER) {
2632 wanted = lua_tointeger(L, 2);
2633 if (wanted < 0)
2634 WILL_LJMP(luaL_error(L, "Unsupported size."));
2635 }
2636 }
2637
2638 /* Set pattern. */
2639 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002640
2641 /* Check if we would replace the top by itself. */
2642 if (lua_gettop(L) != 2)
2643 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644
Christopher Fauletc31b2002021-05-03 10:11:13 +02002645 /* Save index of the top of the stack because since buffers are used, it
2646 * may change
2647 */
2648 lastarg = lua_gettop(L);
2649
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002650 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002651 luaL_buffinit(L, &socket->b);
2652
2653 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002654 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002655 if (lua_type(L, 3) != LUA_TSTRING)
2656 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2657 pattern = lua_tolstring(L, 3, &len);
2658 luaL_addlstring(&socket->b, pattern, len);
2659 }
2660
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002661 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002662}
2663
2664/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002665 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002666 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002667static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002668{
2669 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002670 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002671 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002672 struct appctx *appctx;
2673 size_t buf_len;
2674 const char *buf;
2675 int len;
2676 int send_len;
2677 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002678 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002679 struct stream *s;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002680 struct stconn *sc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002681
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002682 /* Get hlua struct, or NULL if we execute from main lua state */
2683 hlua = hlua_gethlua(L);
2684
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002685 /* Check if this lua stack is schedulable. */
2686 if (!hlua || !hlua->task)
2687 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2688 "'frontend', 'backend' or 'task'"));
2689
2690 /* Get object */
2691 socket = MAY_LJMP(hlua_checksocket(L, 1));
2692 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002693 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002694
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002695 /* Check if we run on the same thread than the xreator thread.
2696 * We cannot access to the socket if the thread is different.
2697 */
2698 if (socket->tid != tid)
2699 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2700
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002701 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002702 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002703 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002704 lua_pushinteger(L, -1);
2705 return 1;
2706 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002707
2708 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2709 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002710 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002711 s = __sc_strm(sc);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002712
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002713 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002714 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002715 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002716 lua_pushinteger(L, -1);
2717 return 1;
2718 }
2719
2720 /* Update the input buffer data. */
2721 buf += sent;
2722 send_len = buf_len - sent;
2723
2724 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002725 if (sent >= buf_len) {
2726 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002727 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002728 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002729
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002730 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002731 * the request buffer if its not required.
2732 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002733 if (s->req.buf.size == 0) {
Willy Tarreau3e7be362022-05-27 10:35:27 +02002734 if (!sc_alloc_ibuf(sc, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002735 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002736 }
2737
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002738 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002739 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002740 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002741 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002742 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002743
2744 /* send data */
2745 if (len < send_len)
2746 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002747 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002748
2749 /* "Not enough space" (-1), "Buffer too little to contain
2750 * the data" (-2) are not expected because the available length
2751 * is tested.
2752 * Other unknown error are also not expected.
2753 */
2754 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002755 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002756 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002757
sada05ed3302018-05-11 11:48:18 -07002758 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002759 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002760 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002761 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002762 return 1;
2763 }
2764
2765 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002766 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002767
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002768 /* Update length sent. */
2769 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002770 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002771
2772 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002773 if (sent + len >= buf_len) {
2774 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002775 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002776 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002777
2778hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002779 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002780 xref_unlock(&socket->xref, peer);
2781 WILL_LJMP(luaL_error(L, "out of memory"));
2782 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002783 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002784 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002785 return 0;
2786}
2787
2788/* This function initiate the send of data. It just check the input
2789 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002790 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002791 * "hlua_socket_write_yield" that can yield.
2792 *
2793 * The Lua function gets between 3 and 4 parameters. The first one is
2794 * the associated object. The second is a string buffer. The third is
2795 * a facultative integer that represents where is the buffer position
2796 * of the start of the data that can send. The first byte is the
2797 * position "1". The default value is "1". The fourth argument is a
2798 * facultative integer that represents where is the buffer position
2799 * of the end of the data that can send. The default is the last byte.
2800 */
2801static int hlua_socket_send(struct lua_State *L)
2802{
2803 int i;
2804 int j;
2805 const char *buf;
2806 size_t buf_len;
2807
2808 /* Check number of arguments. */
2809 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2810 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2811
2812 /* Get the string. */
2813 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2814
2815 /* Get and check j. */
2816 if (lua_gettop(L) == 4) {
2817 j = MAY_LJMP(luaL_checkinteger(L, 4));
2818 if (j < 0)
2819 j = buf_len + j + 1;
2820 if (j > buf_len)
2821 j = buf_len + 1;
2822 lua_pop(L, 1);
2823 }
2824 else
2825 j = buf_len;
2826
2827 /* Get and check i. */
2828 if (lua_gettop(L) == 3) {
2829 i = MAY_LJMP(luaL_checkinteger(L, 3));
2830 if (i < 0)
2831 i = buf_len + i + 1;
2832 if (i > buf_len)
2833 i = buf_len + 1;
2834 lua_pop(L, 1);
2835 } else
2836 i = 1;
2837
2838 /* Check bth i and j. */
2839 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002840 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002841 return 1;
2842 }
2843 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002844 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002845 return 1;
2846 }
2847 if (i == 0)
2848 i = 1;
2849 if (j == 0)
2850 j = 1;
2851
2852 /* Pop the string. */
2853 lua_pop(L, 1);
2854
2855 /* Update the buffer length. */
2856 buf += i - 1;
2857 buf_len = j - i + 1;
2858 lua_pushlstring(L, buf, buf_len);
2859
2860 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002861 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002862
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002863 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002864}
2865
Willy Tarreau22b0a682015-06-17 19:43:49 +02002866#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002867__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002868{
2869 static char buffer[SOCKET_INFO_MAX_LEN];
2870 int ret;
2871 int len;
2872 char *p;
2873
2874 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2875 if (ret <= 0) {
2876 lua_pushnil(L);
2877 return 1;
2878 }
2879
2880 if (ret == AF_UNIX) {
2881 lua_pushstring(L, buffer+1);
2882 return 1;
2883 }
2884 else if (ret == AF_INET6) {
2885 buffer[0] = '[';
2886 len = strlen(buffer);
2887 buffer[len] = ']';
2888 len++;
2889 buffer[len] = ':';
2890 len++;
2891 p = buffer;
2892 }
2893 else if (ret == AF_INET) {
2894 p = buffer + 1;
2895 len = strlen(p);
2896 p[len] = ':';
2897 len++;
2898 }
2899 else {
2900 lua_pushnil(L);
2901 return 1;
2902 }
2903
2904 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2905 lua_pushnil(L);
2906 return 1;
2907 }
2908
2909 lua_pushstring(L, p);
2910 return 1;
2911}
2912
2913/* Returns information about the peer of the connection. */
2914__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2915{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002916 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002917 struct xref *peer;
2918 struct appctx *appctx;
Willy Tarreau3e7be362022-05-27 10:35:27 +02002919 struct stconn *sc;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002920 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002921 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002922
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002923 MAY_LJMP(check_args(L, 1, "getpeername"));
2924
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002925 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002926
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002927 /* Check if we run on the same thread than the xreator thread.
2928 * We cannot access to the socket if the thread is different.
2929 */
2930 if (socket->tid != tid)
2931 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2932
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002933 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002934 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002935 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002936 lua_pushnil(L);
2937 return 1;
2938 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002939
2940 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02002941 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02002942 dst = sc_dst(sc_opposite(sc));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002943 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002944 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002945 lua_pushnil(L);
2946 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002947 }
2948
Christopher Faulet16f16af2021-10-27 09:34:56 +02002949 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002950 xref_unlock(&socket->xref, peer);
2951 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002952}
2953
2954/* Returns information about my connection side. */
2955static int hlua_socket_getsockname(struct lua_State *L)
2956{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002957 struct hlua_socket *socket;
2958 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002959 struct appctx *appctx;
2960 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002961 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002962 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002963
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002964 MAY_LJMP(check_args(L, 1, "getsockname"));
2965
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002966 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002967
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002968 /* Check if we run on the same thread than the xreator thread.
2969 * We cannot access to the socket if the thread is different.
2970 */
2971 if (socket->tid != tid)
2972 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2973
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002974 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002975 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002976 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002977 lua_pushnil(L);
2978 return 1;
2979 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002980
2981 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002982 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002983
Willy Tarreaufd9417b2022-05-18 16:23:22 +02002984 conn = sc_conn(s->scb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002985 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002986 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002987 lua_pushnil(L);
2988 return 1;
2989 }
2990
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002991 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002992 xref_unlock(&socket->xref, peer);
2993 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002994}
2995
2996/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002997static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998 .obj_type = OBJ_TYPE_APPLET,
2999 .name = "<LUA_TCP>",
3000 .fct = hlua_socket_handler,
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003001 .init = hlua_socket_init,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003002 .release = hlua_socket_release,
3003};
3004
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003005__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003006{
3007 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003008 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003009 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02003010 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003011 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003012 struct stream *s;
3013
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003014 /* Get hlua struct, or NULL if we execute from main lua state */
3015 hlua = hlua_gethlua(L);
3016 if (!hlua)
3017 return 0;
3018
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003019 /* Check if we run on the same thread than the xreator thread.
3020 * We cannot access to the socket if the thread is different.
3021 */
3022 if (socket->tid != tid)
3023 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3024
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003025 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003026 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003027 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003028 lua_pushnil(L);
3029 lua_pushstring(L, "Can't connect");
3030 return 2;
3031 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003032
3033 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3034 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02003035 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003036
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003037 /* Check if we run on the same thread than the xreator thread.
3038 * We cannot access to the socket if the thread is different.
3039 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003040 if (socket->tid != tid) {
3041 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003042 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003043 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003044
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003045 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003046 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003047 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003048 lua_pushnil(L);
3049 lua_pushstring(L, "Can't connect");
3050 return 2;
3051 }
3052
Willy Tarreau8e7c6e62022-05-18 17:58:02 +02003053 appctx = __sc_appctx(s->scf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003054
3055 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003056 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003057 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003058 lua_pushinteger(L, 1);
3059 return 1;
3060 }
3061
Willy Tarreau5321da92022-05-06 11:57:34 +02003062 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003063 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003064 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003065 }
3066 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02003067 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003068 return 0;
3069}
3070
3071/* This function fail or initite the connection. */
3072__LJMP static int hlua_socket_connect(struct lua_State *L)
3073{
3074 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003075 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003076 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003077 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02003078 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003079 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003080 int low, high;
3081 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003082 struct xref *peer;
Willy Tarreau3e7be362022-05-27 10:35:27 +02003083 struct stconn *sc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003084 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003085
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003086 if (lua_gettop(L) < 2)
3087 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003088
3089 /* Get args. */
3090 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003091
3092 /* Check if we run on the same thread than the xreator thread.
3093 * We cannot access to the socket if the thread is different.
3094 */
3095 if (socket->tid != tid)
3096 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3097
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003098 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01003099 if (lua_gettop(L) >= 3) {
3100 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003101 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003102
Tim Duesterhus6edab862018-01-06 19:04:45 +01003103 /* Force the ip to end with a colon, to support IPv6 addresses
3104 * that are not enclosed within square brackets.
3105 */
3106 if (port > 0) {
3107 luaL_buffinit(L, &b);
3108 luaL_addstring(&b, ip);
3109 luaL_addchar(&b, ':');
3110 luaL_pushresult(&b);
3111 ip = lua_tolstring(L, lua_gettop(L), NULL);
3112 }
3113 }
3114
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003115 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003116 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003117 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003118 lua_pushnil(L);
3119 return 1;
3120 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003121
3122 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02003123 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 +02003124 if (!addr) {
3125 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003126 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003127 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02003128
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003129 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003130 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003131 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003132 if (port == -1) {
3133 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003134 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003135 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003136 ((struct sockaddr_in *)addr)->sin_port = htons(port);
3137 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003138 if (port == -1) {
3139 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003140 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003141 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003142 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02003143 }
3144 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003145
Willy Tarreau5321da92022-05-06 11:57:34 +02003146 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
3147 appctx = csk_ctx->appctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02003148 sc = appctx_sc(appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02003149 s = __sc_strm(sc);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003150
Willy Tarreau3e7be362022-05-27 10:35:27 +02003151 if (!sockaddr_alloc(&sc_opposite(sc)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02003152 xref_unlock(&socket->xref, peer);
3153 WILL_LJMP(luaL_error(L, "connect: internal error"));
3154 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003155
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003156 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003157 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003158 if (!hlua)
3159 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003160
3161 /* inform the stream that we want to be notified whenever the
3162 * connection completes.
3163 */
Willy Tarreau90e8b452022-05-25 18:21:43 +02003164 applet_need_more_data(appctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +02003165 applet_have_more_data(appctx);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003166 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003167
Willy Tarreauf31af932020-01-14 09:59:38 +01003168 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02003169
Willy Tarreau5321da92022-05-06 11:57:34 +02003170 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003171 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003172 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003173 }
3174 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003175
3176 task_wakeup(s->task, TASK_WOKEN_INIT);
3177 /* Return yield waiting for connection. */
3178
Willy Tarreau9635e032018-10-16 17:52:55 +02003179 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003180
3181 return 0;
3182}
3183
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003184#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003185__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3186{
3187 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003188 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003189 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003190
3191 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3192 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003193
3194 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003195 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003196 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003197 lua_pushnil(L);
3198 return 1;
3199 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003200
Willy Tarreau0698c802022-05-11 14:09:57 +02003201 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003202
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003203 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003204 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003205 return MAY_LJMP(hlua_socket_connect(L));
3206}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003207#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003208
3209__LJMP static int hlua_socket_setoption(struct lua_State *L)
3210{
3211 return 0;
3212}
3213
3214__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3215{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003216 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003217 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003218 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003219 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003220 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003221
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003222 MAY_LJMP(check_args(L, 2, "settimeout"));
3223
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003224 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003225
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003226 /* convert the timeout to millis */
3227 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003228
Thierry Fournier17a921b2018-03-08 09:59:02 +01003229 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003230 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003231 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3232
Mark Lakes56cc1252018-03-27 09:48:06 +02003233 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003234 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003235
3236 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003237 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003238 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003239
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003240 /* Check if we run on the same thread than the xreator thread.
3241 * We cannot access to the socket if the thread is different.
3242 */
3243 if (socket->tid != tid)
3244 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3245
Mark Lakes56cc1252018-03-27 09:48:06 +02003246 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003247 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003248 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003249 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3250 WILL_LJMP(lua_error(L));
3251 return 0;
3252 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003253
Willy Tarreau0698c802022-05-11 14:09:57 +02003254 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003255
Cyril Bonté7bb63452018-08-17 23:51:02 +02003256 s->sess->fe->timeout.connect = tmout;
Christopher Faulet5aaacfb2023-02-15 08:13:33 +01003257 s->scf->ioto = tmout;
3258 s->scb->ioto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003259
3260 s->task->expire = tick_add_ifset(now_ms, tmout);
3261 task_queue(s->task);
3262
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003263 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003264
Thierry Fourniere9636f12018-03-08 09:54:32 +01003265 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003266 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003267}
3268
3269__LJMP static int hlua_socket_new(lua_State *L)
3270{
3271 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02003272 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003273 struct appctx *appctx;
3274
3275 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003276 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003277 hlua_pusherror(L, "socket: full stack");
3278 goto out_fail_conf;
3279 }
3280
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003281 /* Create the object: obj[0] = userdata. */
3282 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003283 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003284 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003285 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003286 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003287
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003288 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003289 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003290 hlua_pusherror(L, "socket: uninitialized pools.");
3291 goto out_fail_conf;
3292 }
3293
Willy Tarreau87b09662015-04-03 00:22:06 +02003294 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003295 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3296 lua_setmetatable(L, -2);
3297
Willy Tarreaud420a972015-04-06 00:39:18 +02003298 /* Create the applet context */
Christopher Faulet6095d572022-05-16 17:09:48 +02003299 appctx = appctx_new_here(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003300 if (!appctx) {
3301 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003302 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003303 }
Willy Tarreau5321da92022-05-06 11:57:34 +02003304 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
3305 ctx->connected = 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02003306 ctx->die = 0;
3307 LIST_INIT(&ctx->wake_on_write);
3308 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003309
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003310 if (appctx_init(appctx) == -1) {
3311 hlua_pusherror(L, "socket: fail to init applet.");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003312 goto out_fail_appctx;
3313 }
3314
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003315 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003316 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003317 return 1;
3318
Christopher Faulet13a35e52021-12-20 15:34:16 +01003319 out_fail_appctx:
Christopher Faulet5f35a3e2022-05-12 15:31:05 +02003320 appctx_free_on_early_error(appctx);
Willy Tarreaud420a972015-04-06 00:39:18 +02003321 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003322 WILL_LJMP(lua_error(L));
3323 return 0;
3324}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003325
3326/*
3327 *
3328 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003329 * Class Channel
3330 *
3331 *
3332 */
3333
3334/* Returns the struct hlua_channel join to the class channel in the
3335 * stack entry "ud" or throws an argument error.
3336 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003337__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003338{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003339 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003340}
3341
Willy Tarreau47860ed2015-03-10 14:07:50 +01003342/* Pushes the channel onto the top of the stack. If the stask does not have a
3343 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003344 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003345static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003346{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003347 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003348 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003349 return 0;
3350
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003351 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003352 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003353 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003354
3355 /* Pop a class sesison metatable and affect it to the userdata. */
3356 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3357 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003358 return 1;
3359}
3360
Christopher Faulet9f55a502020-02-25 15:21:02 +01003361/* Helper function returning a filter attached to a channel at the position <ud>
3362 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003363 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003364 * initialized.
3365 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003366static 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 +01003367{
3368 struct filter *filter = NULL;
3369
3370 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3371 struct hlua_flt_ctx *flt_ctx;
3372
3373 filter = lua_touserdata (L, -1);
3374 flt_ctx = filter->ctx;
3375 if (hlua_filter_from_payload(filter)) {
3376 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3377 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3378 }
3379 }
3380
3381 lua_pop(L, 1);
3382 return filter;
3383}
3384
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003385/* Copies <len> bytes of data present in the channel's buffer, starting at the
3386* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003387* responsibility to ensure <len> and <offset> are valid. It always return the
3388* length of the built string. <len> may be 0, in this case, an empty string is
3389* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003390*/
3391static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003392{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003393 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003394 luaL_Buffer b;
3395
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003396 block1 = len;
3397 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3398 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3399 block2 = len - block1;
3400
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003401 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003402 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3403 if (block2)
3404 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003405 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003406 return len;
3407}
3408
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003409/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3410 * function returns -1 if data cannot be copied. Otherwise, it returns the
3411 * number of bytes copied.
3412 */
3413static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3414{
3415 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003416
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003417 /* Nothing to do, just return */
3418 if (unlikely(istlen(str) == 0))
3419 goto end;
3420
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003421 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003422 ret = -1;
3423 goto end;
3424 }
3425 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3426
3427 end:
3428 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003429}
3430
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003431/* Removes <len> bytes of data at the absolute position <offset>.
3432 */
3433static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3434{
3435 size_t end = offset + len;
3436
3437 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3438 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3439 b_data(&chn->buf) - end, -len);
3440 b_sub(&chn->buf, len);
3441}
3442
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003443/* Copies input data in the channel's buffer. It is possible to set a specific
3444 * offset (0 by default) and a length (all remaining input data starting for the
3445 * offset by default). If there is not enough input data and more data can be
3446 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003447 *
3448 * From an action, All input data are considered. For a filter, the offset and
3449 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003450 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003451__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003452{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003453 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003454 struct filter *filter;
3455 size_t input, output;
3456 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003457
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003458 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003459
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003460 output = co_data(chn);
3461 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003462
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003463 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3464 if (filter && !hlua_filter_from_payload(filter))
3465 WILL_LJMP(lua_error(L));
3466
3467 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003468 if (lua_gettop(L) > 1) {
3469 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3470 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003471 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003472 offset += output;
3473 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003474 lua_pushfstring(L, "offset out of range.");
3475 WILL_LJMP(lua_error(L));
3476 }
3477 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003478 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003479 if (lua_gettop(L) == 3) {
3480 len = MAY_LJMP(luaL_checkinteger(L, 3));
3481 if (!len)
3482 goto dup;
3483 if (len == -1)
3484 len = global.tune.bufsize;
3485 if (len < 0) {
3486 lua_pushfstring(L, "length out of range.");
3487 WILL_LJMP(lua_error(L));
3488 }
3489 }
3490
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003491 /* Wait for more data if possible if no length was specified and there
3492 * is no data or not enough data was received.
3493 */
3494 if (!len || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003495 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3496 /* Yield waiting for more data, as requested */
3497 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3498 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003499
3500 /* Return 'nil' if there is no data and the channel can't receive more data */
3501 if (!len) {
3502 lua_pushnil(L);
3503 return -1;
3504 }
3505
3506 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003507 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003508 }
3509
3510 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003511 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003512 return 1;
3513}
3514
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003515/* Copies the first line (including the trailing LF) of input data in the
3516 * channel's buffer. It is possible to set a specific offset (0 by default) and
3517 * a length (all remaining input data starting for the offset by default). If
3518 * there is not enough input data and more data can be received, the function
3519 * yields. If a length is explicitly specified, no more data are
3520 * copied. Otherwise, if no LF is found and more data can be received, this
3521 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003522 *
3523 * From an action, All input data are considered. For a filter, the offset and
3524 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003525 */
3526__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003527{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003528 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003529 struct filter *filter;
3530 size_t l, input, output;
3531 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003532
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003533 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003534 output = co_data(chn);
3535 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003536
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003537 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3538 if (filter && !hlua_filter_from_payload(filter))
3539 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003540
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003541 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003542 if (lua_gettop(L) > 1) {
3543 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3544 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003545 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003546 offset += output;
3547 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003548 lua_pushfstring(L, "offset out of range.");
3549 WILL_LJMP(lua_error(L));
3550 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003551 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003552
3553 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003554 if (lua_gettop(L) == 3) {
3555 len = MAY_LJMP(luaL_checkinteger(L, 3));
3556 if (!len)
3557 goto dup;
3558 if (len == -1)
3559 len = global.tune.bufsize;
3560 if (len < 0) {
3561 lua_pushfstring(L, "length out of range.");
3562 WILL_LJMP(lua_error(L));
3563 }
3564 }
3565
3566 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003567 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003568 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003569 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003570 len = l+1;
3571 goto dup;
3572 }
3573 }
3574
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003575 /* Wait for more data if possible if no line is found and no length was
3576 * specified or not enough data was received.
3577 */
3578 if (lua_gettop(L) != 3 || offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003579 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3580 /* Yield waiting for more data */
3581 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3582 }
Christopher Faulet0ae2e632023-01-10 15:29:54 +01003583
3584 /* Return 'nil' if there is no data and the channel can't receive more data */
3585 if (!len) {
3586 lua_pushnil(L);
3587 return -1;
3588 }
3589
3590 /* Otherwise, return all data */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003591 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003592 }
3593
3594 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003595 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003596 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003597}
3598
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599/* [ DEPRECATED ]
3600 *
3601 * Duplicate all input data foud in the channel's buffer. The data are not
3602 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 *
3604 * From an action, All input data are considered. For a filter, the offset and
3605 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003606 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003607__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003608{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003609 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003610 struct filter *filter;
3611 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003612
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003613 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003614 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003615 if (IS_HTX_STRM(chn_strm(chn))) {
3616 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3617 WILL_LJMP(lua_error(L));
3618 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003619
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003620 offset = co_data(chn);
3621 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003622
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3624 if (filter && !hlua_filter_from_payload(filter))
3625 WILL_LJMP(lua_error(L));
3626
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003627 if (!ci_data(chn) && channel_input_closed(chn)) {
3628 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003629 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003630 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003631
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003632 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003633 return 1;
3634}
3635
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003636/* [ DEPRECATED ]
3637 *
3638 * Get all input data foud in the channel's buffer. The data are removed from
3639 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3640 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003641 *
3642 * From an action, All input data are considered. For a filter, the offset and
3643 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003644 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003645__LJMP static int hlua_channel_get(lua_State *L)
3646{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003647 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003648 struct filter *filter;
3649 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003650 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003651
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003652 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003653 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3654 if (IS_HTX_STRM(chn_strm(chn))) {
3655 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3656 WILL_LJMP(lua_error(L));
3657 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003658
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003659 offset = co_data(chn);
3660 len = ci_data(chn);
3661
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003662 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3663 if (filter && !hlua_filter_from_payload(filter))
3664 WILL_LJMP(lua_error(L));
3665
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003666 if (!ci_data(chn) && channel_input_closed(chn)) {
3667 lua_pushnil(L);
3668 return 1;
3669 }
3670
3671 ret = _hlua_channel_dup(chn, L, offset, len);
3672 _hlua_channel_delete(chn, offset, ret);
3673 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003674}
3675
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003676/* This functions consumes and returns one line. If the channel is closed,
3677 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003678 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003679 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003680 *
3681 * From an action, All input data are considered. For a filter, the offset and
3682 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003683 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003684__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003685{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003686 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003687 struct filter *filter;
3688 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003689 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003690
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003691 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003692
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003693 offset = co_data(chn);
3694 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003695
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003696 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3697 if (filter && !hlua_filter_from_payload(filter))
3698 WILL_LJMP(lua_error(L));
3699
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003700 if (!ci_data(chn) && channel_input_closed(chn)) {
3701 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003702 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003703 }
3704
3705 for (l = 0; l < len; l++) {
3706 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3707 len = l+1;
3708 goto dup;
3709 }
3710 }
3711
3712 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3713 /* Yield waiting for more data */
3714 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3715 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003716
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003717 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003718 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003719 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003720 return 1;
3721}
3722
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003723/* [ DEPRECATED ]
3724 *
3725 * Check arguments for the function "hlua_channel_getline_yield".
3726 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003727__LJMP static int hlua_channel_getline(lua_State *L)
3728{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003729 struct channel *chn;
3730
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003731 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003732 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3733 if (IS_HTX_STRM(chn_strm(chn))) {
3734 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3735 WILL_LJMP(lua_error(L));
3736 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003737 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3738}
3739
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003740/* Retrieves a given amount of input data at the given offset. By default all
3741 * available input data are returned. The offset may be negactive to start from
3742 * the end of input data. The length may be -1 to set it to the maximum buffer
3743 * size.
3744 */
3745__LJMP static int hlua_channel_get_data(lua_State *L)
3746{
3747 struct channel *chn;
3748
3749 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3750 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3751 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3752 if (IS_HTX_STRM(chn_strm(chn))) {
3753 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3754 WILL_LJMP(lua_error(L));
3755 }
3756 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3757}
3758
3759/* Retrieves a given amount of input data at the given offset. By default all
3760 * available input data are returned. The offset may be negactive to start from
3761 * the end of input data. The length may be -1 to set it to the maximum buffer
3762 * size.
3763 */
3764__LJMP static int hlua_channel_get_line(lua_State *L)
3765{
3766 struct channel *chn;
3767
3768 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3769 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3770 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3771 if (IS_HTX_STRM(chn_strm(chn))) {
3772 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3773 WILL_LJMP(lua_error(L));
3774 }
3775 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3776}
3777
3778/* Appends a string into the input side of channel. It returns the length of the
3779 * written string, or -1 if the channel is closed or if the buffer size is too
3780 * little for the data. 0 may be returned if nothing is copied. This function
3781 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003782 *
3783 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003784 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003785__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003786{
Christopher Faulet23976d92021-08-06 09:59:49 +02003787 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003788 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003789 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003790 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003791 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003792
3793 MAY_LJMP(check_args(L, 2, "append"));
3794 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003795 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003796 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003797 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003798 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003799 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003800
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003801 offset = co_data(chn);
3802 len = ci_data(chn);
3803
3804 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3805 if (filter && !hlua_filter_from_payload(filter))
3806 WILL_LJMP(lua_error(L));
3807
3808 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3809 if (ret > 0 && filter) {
3810 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3811
3812 flt_update_offsets(filter, chn, ret);
3813 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3814 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003815 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003816 return 1;
3817}
3818
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003819/* Prepends a string into the input side of channel. It returns the length of the
3820 * written string, or -1 if the channel is closed or if the buffer size is too
3821 * little for the data. 0 may be returned if nothing is copied. This function
3822 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003823 *
3824 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003825 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003826__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003827{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003828 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003829 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003830 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003831 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003832 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003833
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003834 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003835 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003836 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3837 if (IS_HTX_STRM(chn_strm(chn))) {
3838 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3839 WILL_LJMP(lua_error(L));
3840 }
3841
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003842 offset = co_data(chn);
3843 len = ci_data(chn);
3844
3845 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3846 if (filter && !hlua_filter_from_payload(filter))
3847 WILL_LJMP(lua_error(L));
3848
3849 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3850 if (ret > 0 && filter) {
3851 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3852
3853 flt_update_offsets(filter, chn, ret);
3854 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3855 }
3856
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003857 lua_pushinteger(L, ret);
3858 return 1;
3859}
3860
3861/* Inserts a given amount of input data at the given offset by a string
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003862 * content. By default the string is appended in front of input data. It
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003863 * returns the length of the written string, or -1 if the channel is closed or
3864 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003865 *
3866 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003867 */
3868__LJMP static int hlua_channel_insert_data(lua_State *L)
3869{
3870 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003871 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003872 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003873 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003874 int ret, offset;
3875
3876 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3877 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3878 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3879 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003880
3881 output = co_data(chn);
3882 input = ci_data(chn);
3883
3884 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3885 if (filter && !hlua_filter_from_payload(filter))
3886 WILL_LJMP(lua_error(L));
3887
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003888 offset = output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003889 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003890 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003891 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003892 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003893 offset += output;
Aurelien DARRAGONafb7daf2022-10-04 12:16:05 +02003894 if (offset > output + input) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003895 lua_pushfstring(L, "offset out of range.");
3896 WILL_LJMP(lua_error(L));
3897 }
3898 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003899 if (IS_HTX_STRM(chn_strm(chn))) {
3900 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3901 WILL_LJMP(lua_error(L));
3902 }
3903
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003904 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3905 if (ret > 0 && filter) {
3906 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003907
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003908 flt_update_offsets(filter, chn, ret);
3909 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003910 }
3911
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003912 lua_pushinteger(L, ret);
3913 return 1;
3914}
3915/* Replaces a given amount of input data at the given offset by a string
3916 * content. By default all remaining data are removed (offset = 0 and len =
3917 * -1). It returns the length of the written string, or -1 if the channel is
3918 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003919 *
3920 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003921 */
3922__LJMP static int hlua_channel_set_data(lua_State *L)
3923{
3924 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003925 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003926 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003927 size_t sz, input, output;
3928 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003929
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003930 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3931 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3932 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3933 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003934
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003935 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003936 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003937 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003938 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003939
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003940 output = co_data(chn);
3941 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003942
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003943 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3944 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003945 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003946
3947 offset = output;
3948 if (lua_gettop(L) > 2) {
3949 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3950 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003951 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003952 offset += output;
3953 if (offset < output || offset > input + output) {
3954 lua_pushfstring(L, "offset out of range.");
3955 WILL_LJMP(lua_error(L));
3956 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003957 }
3958
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003959 len = output + input - offset;
3960 if (lua_gettop(L) == 4) {
3961 len = MAY_LJMP(luaL_checkinteger(L, 4));
3962 if (!len)
3963 goto set;
3964 if (len == -1)
3965 len = output + input - offset;
3966 if (len < 0 || offset + len > output + input) {
3967 lua_pushfstring(L, "length out of range.");
3968 WILL_LJMP(lua_error(L));
3969 }
3970 }
3971
3972 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003973 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003974 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003975 lua_pushinteger(L, -1);
3976 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003977 _hlua_channel_delete(chn, offset, len);
3978 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3979 if (filter) {
3980 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3981
3982 len -= (ret > 0 ? ret : 0);
3983 flt_update_offsets(filter, chn, -len);
3984 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3985 }
3986
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003987 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003988 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003989 return 1;
3990}
3991
3992/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003993 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003994 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003995 *
3996 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003997 */
3998__LJMP static int hlua_channel_del_data(lua_State *L)
3999{
4000 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004001 struct filter *filter;
4002 size_t input, output;
4003 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004004
4005 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
4006 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
4007 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004008
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004009 if (IS_HTX_STRM(chn_strm(chn))) {
4010 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4011 WILL_LJMP(lua_error(L));
4012 }
4013
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004014 output = co_data(chn);
4015 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004016
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004017 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4018 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004019 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004020
4021 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00004022 if (lua_gettop(L) > 1) {
4023 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004024 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02004025 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004026 offset += output;
4027 if (offset < output || offset > input + output) {
4028 lua_pushfstring(L, "offset out of range.");
4029 WILL_LJMP(lua_error(L));
4030 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004031 }
4032
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004033 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00004034 if (lua_gettop(L) == 3) {
4035 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004036 if (!len)
4037 goto end;
4038 if (len == -1)
4039 len = output + input - offset;
4040 if (len < 0 || offset + len > output + input) {
4041 lua_pushfstring(L, "length out of range.");
4042 WILL_LJMP(lua_error(L));
4043 }
4044 }
4045
4046 _hlua_channel_delete(chn, offset, len);
4047 if (filter) {
4048 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4049
4050 flt_update_offsets(filter, chn, -len);
4051 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
4052 }
4053
4054 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004055 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02004056 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004057}
4058
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004059/* Append data in the output side of the buffer. This data is immediately
4060 * sent. The function returns the amount of data written. If the buffer
4061 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004062 * if the channel is closed.
4063 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004064__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004065{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004066 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004067 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004068 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004069 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004070 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004071 struct hlua *hlua;
4072
4073 /* Get hlua struct, or NULL if we execute from main lua state */
4074 hlua = hlua_gethlua(L);
4075 if (!hlua) {
4076 lua_pushnil(L);
4077 return 1;
4078 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004079
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004080 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4081 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
4082 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01004083
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004084 offset = co_data(chn);
4085 len = ci_data(chn);
4086
4087 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4088 if (filter && !hlua_filter_from_payload(filter))
4089 WILL_LJMP(lua_error(L));
4090
4091
Willy Tarreau47860ed2015-03-10 14:07:50 +01004092 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004093 lua_pushinteger(L, -1);
4094 return 1;
4095 }
4096
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004097 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004098 if (len > sz -l) {
4099 if (filter) {
4100 lua_pushinteger(L, -1);
4101 return 1;
4102 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004103 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004104 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004105
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004106 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004107 if (ret == -1) {
4108 lua_pop(L, 1);
4109 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01004110 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004111 }
4112 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004113 if (filter) {
4114 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4115
4116
4117 flt_update_offsets(filter, chn, ret);
4118 FLT_OFF(filter, chn) += ret;
4119 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
4120 }
4121 else
4122 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004123
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004124 l += ret;
4125 lua_pop(L, 1);
4126 lua_pushinteger(L, l);
4127 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004128
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004129 if (l < sz) {
4130 /* Yield only if the channel's output is not empty.
4131 * Otherwise it means we cannot add more data. */
4132 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004133 return 1;
4134
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004135 /* If we are waiting for space in the response buffer, we
4136 * must set the flag WAKERESWR. This flag required the task
4137 * wake up if any activity is detected on the response buffer.
4138 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004139 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004140 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004141 else
4142 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02004143 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004144 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004145
4146 return 1;
4147}
4148
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004149/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004150 * yield the LUA process, and resume it without checking the
4151 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004152 *
4153 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004154 */
4155__LJMP static int hlua_channel_send(lua_State *L)
4156{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004157 struct channel *chn;
4158
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004159 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004160 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4161 if (IS_HTX_STRM(chn_strm(chn))) {
4162 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4163 WILL_LJMP(lua_error(L));
4164 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004165 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004166 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004167}
4168
4169/* This function forward and amount of butes. The data pass from
4170 * the input side of the buffer to the output side, and can be
4171 * forwarded. This function never fails.
4172 *
4173 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004174 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004175 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004176__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004177{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004178 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004179 struct filter *filter;
4180 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004181 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004182 struct hlua *hlua;
4183
4184 /* Get hlua struct, or NULL if we execute from main lua state */
4185 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004186 if (!hlua) {
4187 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01004188 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02004189 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01004190
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004191 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004192 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004193 l = MAY_LJMP(luaL_checkinteger(L, -1));
4194
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004195 offset = co_data(chn);
4196 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004197
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004198 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
4199 if (filter && !hlua_filter_from_payload(filter))
4200 WILL_LJMP(lua_error(L));
4201
4202 max = fwd - l;
4203 if (max > len)
4204 max = len;
4205
4206 if (filter) {
4207 struct hlua_flt_ctx *flt_ctx = filter->ctx;
4208
4209 FLT_OFF(filter, chn) += max;
4210 flt_ctx->cur_off[CHN_IDX(chn)] += max;
4211 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
4212 }
4213 else
4214 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004215
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004216 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004217 lua_pop(L, 1);
4218 lua_pushinteger(L, l);
4219
4220 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004221 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004222 /* The the input channel or the output channel are closed, we
4223 * must return the amount of data forwarded.
4224 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02004225 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004226 return 1;
4227
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004228 /* If we are waiting for space data in the response buffer, we
4229 * must set the flag WAKERESWR. This flag required the task
4230 * wake up if any activity is detected on the response buffer.
4231 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01004232 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004233 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004234 else
4235 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004236
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004237 /* Otherwise, we can yield waiting for new data in the input side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02004238 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004239 }
4240
4241 return 1;
4242}
4243
4244/* Just check the input and prepare the stack for the previous
4245 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004246 *
4247 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004248 */
4249__LJMP static int hlua_channel_forward(lua_State *L)
4250{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004251 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004252
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02004253 MAY_LJMP(check_args(L, 2, "forward"));
4254 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4255 if (IS_HTX_STRM(chn_strm(chn))) {
4256 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
4257 WILL_LJMP(lua_error(L));
4258 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004259 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004260 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004261}
4262
4263/* Just returns the number of bytes available in the input
4264 * side of the buffer. This function never fails.
4265 */
4266__LJMP static int hlua_channel_get_in_len(lua_State *L)
4267{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004268 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004269 struct filter *filter;
4270 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004271
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004272 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004273 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004274
4275 output = co_data(chn);
4276 input = ci_data(chn);
4277 filter = hlua_channel_filter(L, 1, chn, &output, &input);
4278 if (filter || !IS_HTX_STRM(chn_strm(chn)))
4279 lua_pushinteger(L, input);
4280 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004281 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004282
Christopher Fauleta3ceac12018-12-14 13:39:09 +01004283 lua_pushinteger(L, htx->data - co_data(chn));
4284 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004285 return 1;
4286}
4287
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004288/* Returns true if the channel is full. */
4289__LJMP static int hlua_channel_is_full(lua_State *L)
4290{
4291 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004292
4293 MAY_LJMP(check_args(L, 1, "is_full"));
4294 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01004295 /* ignore the reserve, we are not on a producer side (ie in an
4296 * applet).
4297 */
4298 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01004299 return 1;
4300}
4301
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004302/* Returns true if the channel may still receive data. */
4303__LJMP static int hlua_channel_may_recv(lua_State *L)
4304{
4305 struct channel *chn;
4306
4307 MAY_LJMP(check_args(L, 1, "may_recv"));
4308 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4309 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4310 return 1;
4311}
4312
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004313/* Returns true if the channel is the response channel. */
4314__LJMP static int hlua_channel_is_resp(lua_State *L)
4315{
4316 struct channel *chn;
4317
4318 MAY_LJMP(check_args(L, 1, "is_resp"));
4319 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4320
4321 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4322 return 1;
4323}
4324
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004325/* Just returns the number of bytes available in the output
4326 * side of the buffer. This function never fails.
4327 */
4328__LJMP static int hlua_channel_get_out_len(lua_State *L)
4329{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004330 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004331 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004332
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004333 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004334 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004335
4336 output = co_data(chn);
4337 input = ci_data(chn);
4338 hlua_channel_filter(L, 1, chn, &output, &input);
4339
4340 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004341 return 1;
4342}
4343
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004344/*
4345 *
4346 *
4347 * Class Fetches
4348 *
4349 *
4350 */
4351
4352/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004353 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004354 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004355__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004356{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004357 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004358}
4359
4360/* This function creates and push in the stack a fetch object according
4361 * with a current TXN.
4362 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004363static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004364{
Willy Tarreau7073c472015-04-06 11:15:40 +02004365 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004366
4367 /* Check stack size. */
4368 if (!lua_checkstack(L, 3))
4369 return 0;
4370
4371 /* Create the object: obj[0] = userdata.
4372 * Note that the base of the Fetches object is the
4373 * transaction object.
4374 */
4375 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004376 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004377 lua_rawseti(L, -2, 0);
4378
Willy Tarreau7073c472015-04-06 11:15:40 +02004379 hsmp->s = txn->s;
4380 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004381 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004382 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004383
4384 /* Pop a class sesison metatable and affect it to the userdata. */
4385 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4386 lua_setmetatable(L, -2);
4387
4388 return 1;
4389}
4390
4391/* This function is an LUA binding. It is called with each sample-fetch.
4392 * It uses closure argument to store the associated sample-fetch. It
4393 * returns only one argument or throws an error. An error is thrown
4394 * only if an error is encountered during the argument parsing. If
4395 * the "sample-fetch" function fails, nil is returned.
4396 */
4397__LJMP static int hlua_run_sample_fetch(lua_State *L)
4398{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004399 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004400 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004401 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004402 int i;
4403 struct sample smp;
4404
4405 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004406 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004407
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004408 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004409 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004410
Thierry FOURNIERca988662015-12-20 18:43:03 +01004411 /* Check execution authorization. */
4412 if (f->use & SMP_USE_HTTP_ANY &&
4413 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4414 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4415 "is not available in Lua services", f->kw);
4416 WILL_LJMP(lua_error(L));
4417 }
4418
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004419 /* Get extra arguments. */
4420 for (i = 0; i < lua_gettop(L) - 1; i++) {
4421 if (i >= ARGM_NBARGS)
4422 break;
4423 hlua_lua2arg(L, i + 2, &args[i]);
4424 }
4425 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004426 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004427
4428 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004429 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004430
4431 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004432 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004433 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004434 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004435 }
4436
4437 /* Initialise the sample. */
4438 memset(&smp, 0, sizeof(smp));
4439
4440 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004441 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004442 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004443 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004444 lua_pushstring(L, "");
4445 else
4446 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004447 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004448 }
4449
4450 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004451 if (hsmp->flags & HLUA_F_AS_STRING)
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +02004452 MAY_LJMP(hlua_smp2lua_str(L, &smp));
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004453 else
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004454 MAY_LJMP(hlua_smp2lua(L, &smp));
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004455
4456 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004457 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004458 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004459
4460 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004461 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004462 WILL_LJMP(lua_error(L));
4463 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004464}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004465
4466/*
4467 *
4468 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004469 * Class Converters
4470 *
4471 *
4472 */
4473
4474/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004475 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004476 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004477__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004478{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004479 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004480}
4481
4482/* This function creates and push in the stack a Converters object
4483 * according with a current TXN.
4484 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004485static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004486{
Willy Tarreau7073c472015-04-06 11:15:40 +02004487 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004488
4489 /* Check stack size. */
4490 if (!lua_checkstack(L, 3))
4491 return 0;
4492
4493 /* Create the object: obj[0] = userdata.
4494 * Note that the base of the Converters object is the
4495 * same than the TXN object.
4496 */
4497 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004498 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004499 lua_rawseti(L, -2, 0);
4500
Willy Tarreau7073c472015-04-06 11:15:40 +02004501 hsmp->s = txn->s;
4502 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004503 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004504 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004505
Willy Tarreau87b09662015-04-03 00:22:06 +02004506 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004507 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4508 lua_setmetatable(L, -2);
4509
4510 return 1;
4511}
4512
4513/* This function is an LUA binding. It is called with each converter.
4514 * It uses closure argument to store the associated converter. It
4515 * returns only one argument or throws an error. An error is thrown
4516 * only if an error is encountered during the argument parsing. If
4517 * the converter function function fails, nil is returned.
4518 */
4519__LJMP static int hlua_run_sample_conv(lua_State *L)
4520{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004521 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004522 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004523 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004524 int i;
4525 struct sample smp;
4526
4527 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004528 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004529
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004530 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004531 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004532
4533 /* Get extra arguments. */
4534 for (i = 0; i < lua_gettop(L) - 2; i++) {
4535 if (i >= ARGM_NBARGS)
4536 break;
4537 hlua_lua2arg(L, i + 3, &args[i]);
4538 }
4539 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004540 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004541
4542 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004543 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004544
4545 /* Run the special args checker. */
4546 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4547 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004548 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004549 }
4550
4551 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004552 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004553 if (!hlua_lua2smp(L, 2, &smp)) {
4554 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004555 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004556 }
4557
Willy Tarreau1777ea62016-03-10 16:15:46 +01004558 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4559
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004560 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004561 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004562 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004563 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004564 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004565 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004566 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4567 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004568 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004569 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004570 }
4571
4572 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004573 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004574 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004575 lua_pushstring(L, "");
4576 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004577 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004578 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004579 }
4580
4581 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004582 if (hsmp->flags & HLUA_F_AS_STRING)
Aurelien DARRAGON742b1a82023-05-17 10:38:50 +02004583 MAY_LJMP(hlua_smp2lua_str(L, &smp));
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004584 else
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004585 MAY_LJMP(hlua_smp2lua(L, &smp));
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004586 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004587 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004588 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004589
4590 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004591 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004592 WILL_LJMP(lua_error(L));
4593 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004594}
4595
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004596/*
4597 *
4598 *
4599 * Class AppletTCP
4600 *
4601 *
4602 */
4603
4604/* Returns a struct hlua_txn if the stack entry "ud" is
4605 * a class stream, otherwise it throws an error.
4606 */
4607__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4608{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004609 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004610}
4611
4612/* This function creates and push in the stack an Applet object
4613 * according with a current TXN.
4614 */
4615static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4616{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004617 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004618 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004619 struct proxy *p;
4620
4621 ALREADY_CHECKED(s);
4622 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004623
4624 /* Check stack size. */
4625 if (!lua_checkstack(L, 3))
4626 return 0;
4627
4628 /* Create the object: obj[0] = userdata.
4629 * Note that the base of the Converters object is the
4630 * same than the TXN object.
4631 */
4632 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004633 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004634 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004635 luactx->appctx = ctx;
4636 luactx->htxn.s = s;
4637 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004638
4639 /* Create the "f" field that contains a list of fetches. */
4640 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004641 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004642 return 0;
4643 lua_settable(L, -3);
4644
4645 /* Create the "sf" field that contains a list of stringsafe fetches. */
4646 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004647 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004648 return 0;
4649 lua_settable(L, -3);
4650
4651 /* Create the "c" field that contains a list of converters. */
4652 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004653 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004654 return 0;
4655 lua_settable(L, -3);
4656
4657 /* Create the "sc" field that contains a list of stringsafe converters. */
4658 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004659 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004660 return 0;
4661 lua_settable(L, -3);
4662
4663 /* Pop a class stream metatable and affect it to the table. */
4664 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4665 lua_setmetatable(L, -2);
4666
4667 return 1;
4668}
4669
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004670__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4671{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004672 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004673 struct stream *s;
4674 const char *name;
4675 size_t len;
4676 struct sample smp;
4677
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004678 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4679 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004680
4681 /* It is useles to retrieve the stream, but this function
4682 * runs only in a stream context.
4683 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004684 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004685 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004686 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004687
4688 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004689 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004690 hlua_lua2smp(L, 3, &smp);
4691
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02004692 /* Store the sample in a variable. We don't need to dup the smp, vars API
4693 * already takes care of duplicating dynamic var data.
4694 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004695 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004696
4697 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4698 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4699 else
4700 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4701
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004702 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004703}
4704
4705__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4706{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004707 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004708 struct stream *s;
4709 const char *name;
4710 size_t len;
4711 struct sample smp;
4712
4713 MAY_LJMP(check_args(L, 2, "unset_var"));
4714
4715 /* It is useles to retrieve the stream, but this function
4716 * runs only in a stream context.
4717 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004718 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004719 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004720 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004721
4722 /* Unset the variable. */
4723 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004724 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4725 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004726}
4727
4728__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4729{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004730 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004731 struct stream *s;
4732 const char *name;
4733 size_t len;
4734 struct sample smp;
4735
4736 MAY_LJMP(check_args(L, 2, "get_var"));
4737
4738 /* It is useles to retrieve the stream, but this function
4739 * runs only in a stream context.
4740 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004741 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004742 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004743 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004744
4745 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004746 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004747 lua_pushnil(L);
4748 return 1;
4749 }
4750
Aurelien DARRAGON41217722023-05-17 10:44:47 +02004751 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004752}
4753
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004754__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4755{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004756 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4757 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004758 struct hlua *hlua;
4759
4760 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004761 if (!s->hlua)
4762 return 0;
4763 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004764
4765 MAY_LJMP(check_args(L, 2, "set_priv"));
4766
4767 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004768 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004769
4770 /* Get and store new value. */
4771 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4772 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4773
4774 return 0;
4775}
4776
4777__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4778{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004779 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4780 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004781 struct hlua *hlua;
4782
4783 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004784 if (!s->hlua) {
4785 lua_pushnil(L);
4786 return 1;
4787 }
4788 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004789
4790 /* Push configuration index in the stack. */
4791 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4792
4793 return 1;
4794}
4795
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004796/* If expected data not yet available, it returns a yield. This function
4797 * consumes the data in the buffer. It returns a string containing the
4798 * data. This string can be empty.
4799 */
4800__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4801{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004802 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004803 struct stconn *sc = appctx_sc(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004804 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004805 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004806 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004807 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004808 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004809
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004810 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004811 ret = co_getline_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004812
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004813 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004814 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004815 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004816 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004817 }
4818
4819 /* End of data: commit the total strings and return. */
4820 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004821 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004822 return 1;
4823 }
4824
4825 /* Ensure that the block 2 length is usable. */
4826 if (ret == 1)
4827 len2 = 0;
4828
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004829 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004830 luaL_addlstring(&luactx->b, blk1, len1);
4831 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004832
4833 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004834 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004835 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004836 return 1;
4837}
4838
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004839/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004840__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4841{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004842 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004843
4844 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004845 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004846
4847 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4848}
4849
4850/* If expected data not yet available, it returns a yield. This function
4851 * consumes the data in the buffer. It returns a string containing the
4852 * data. This string can be empty.
4853 */
4854__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4855{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004856 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004857 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004858 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004859 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004860 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004861 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004862 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004863 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004864
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004865 /* Read the maximum amount of data available. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004866 ret = co_getblk_nc(sc_oc(sc), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004867
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004868 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004869 if (ret == 0) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02004870 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004871 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004872 }
4873
4874 /* End of data: commit the total strings and return. */
4875 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004876 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004877 return 1;
4878 }
4879
4880 /* Ensure that the block 2 length is usable. */
4881 if (ret == 1)
4882 len2 = 0;
4883
4884 if (len == -1) {
4885
4886 /* If len == -1, catenate all the data avalaile and
4887 * yield because we want to get all the data until
4888 * the end of data stream.
4889 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004890 luaL_addlstring(&luactx->b, blk1, len1);
4891 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004892 co_skip(sc_oc(sc), len1 + len2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004893 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004894 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004895
4896 } else {
4897
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004898 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004899 if (len1 > len)
4900 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004901 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004902 len -= len1;
4903
4904 /* Copy the second block. */
4905 if (len2 > len)
4906 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004907 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004908 len -= len2;
4909
4910 /* Consume input channel output buffer data. */
Willy Tarreau3e7be362022-05-27 10:35:27 +02004911 co_skip(sc_oc(sc), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004912
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004913 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004914 if (len > 0) {
4915 lua_pushinteger(L, len);
4916 lua_replace(L, 2);
Willy Tarreau90e8b452022-05-25 18:21:43 +02004917 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02004918 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004919 }
4920
4921 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004922 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004923 return 1;
4924 }
4925
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004926 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004927 hlua_pusherror(L, "Lua: internal error");
4928 WILL_LJMP(lua_error(L));
4929 return 0;
4930}
4931
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004932/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004933__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4934{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004935 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004936 int len = -1;
4937
4938 if (lua_gettop(L) > 2)
4939 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4940 if (lua_gettop(L) >= 2) {
4941 len = MAY_LJMP(luaL_checkinteger(L, 2));
4942 lua_pop(L, 1);
4943 }
4944
4945 /* Confirm or set the required length */
4946 lua_pushinteger(L, len);
4947
4948 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004949 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004950
4951 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4952}
4953
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004954/* Append data in the output side of the buffer. This data is immediately
4955 * sent. The function returns the amount of data written. If the buffer
4956 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004957 * if the channel is closed.
4958 */
4959__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4960{
4961 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004962 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004963 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4964 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreauc12b3212022-05-27 11:08:15 +02004965 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02004966 struct channel *chn = sc_ic(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004967 int max;
4968
4969 /* Get the max amount of data which can write as input in the channel. */
4970 max = channel_recv_max(chn);
4971 if (max > (len - l))
4972 max = len - l;
4973
4974 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004975 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004976
4977 /* update counters. */
4978 l += max;
4979 lua_pop(L, 1);
4980 lua_pushinteger(L, l);
4981
4982 /* If some data is not send, declares the situation to the
4983 * applet, and returns a yield.
4984 */
4985 if (l < len) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02004986 sc_need_room(sc, channel_recv_max(chn) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02004987 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004988 }
4989
4990 return 1;
4991}
4992
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004993/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004994 * yield the LUA process, and resume it without checking the
4995 * input arguments.
4996 */
4997__LJMP static int hlua_applet_tcp_send(lua_State *L)
4998{
4999 MAY_LJMP(check_args(L, 2, "send"));
5000 lua_pushinteger(L, 0);
5001
5002 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
5003}
5004
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005005/*
5006 *
5007 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005008 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005009 *
5010 *
5011 */
5012
5013/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005014 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005015 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005016__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005017{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005018 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005019}
5020
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005021/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005022 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005023 * It relies on the caller to have already reserved the room in ctx->svcctx
5024 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005025 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005026static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005027{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005028 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02005029 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01005030 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02005031 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005032 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02005033 struct htx *htx;
5034 struct htx_blk *blk;
5035 struct htx_sl *sl;
5036 struct ist path;
5037 unsigned long long len = 0;
5038 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02005039 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005040
5041 /* Check stack size. */
5042 if (!lua_checkstack(L, 3))
5043 return 0;
5044
5045 /* Create the object: obj[0] = userdata.
5046 * Note that the base of the Converters object is the
5047 * same than the TXN object.
5048 */
5049 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005050 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005051 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005052 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005053 http_ctx->status = 200; /* Default status code returned. */
5054 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005055 luactx->htxn.s = s;
5056 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005057
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005058 /* Create the "f" field that contains a list of fetches. */
5059 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005060 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005061 return 0;
5062 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005063
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005064 /* Create the "sf" field that contains a list of stringsafe fetches. */
5065 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005066 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005067 return 0;
5068 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005069
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005070 /* Create the "c" field that contains a list of converters. */
5071 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005072 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005073 return 0;
5074 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005075
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005076 /* Create the "sc" field that contains a list of stringsafe converters. */
5077 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02005078 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005079 return 0;
5080 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02005081
Christopher Fauleta2097962019-07-15 16:25:33 +02005082 htx = htxbuf(&s->req.buf);
5083 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01005084 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02005085 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005086
Christopher Fauleta2097962019-07-15 16:25:33 +02005087 /* Stores the request method. */
5088 lua_pushstring(L, "method");
5089 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5090 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005091
Christopher Fauleta2097962019-07-15 16:25:33 +02005092 /* Stores the http version. */
5093 lua_pushstring(L, "version");
5094 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5095 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005096
Christopher Fauleta2097962019-07-15 16:25:33 +02005097 /* creates an array of headers. hlua_http_get_headers() crates and push
5098 * the array on the top of the stack.
5099 */
5100 lua_pushstring(L, "headers");
5101 htxn.s = s;
5102 htxn.p = px;
5103 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005104 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02005105 return 0;
5106 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005107
Amaury Denoyellec453f952021-07-06 11:40:12 +02005108 parser = http_uri_parser_init(htx_sl_req_uri(sl));
5109 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01005110 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02005111 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005112
Christopher Fauleta2097962019-07-15 16:25:33 +02005113 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01005114 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02005115 q = p;
5116 while (q < end && *q != '?')
5117 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005118
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005119 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005120 lua_pushstring(L, "path");
5121 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01005122 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005123
Christopher Fauleta2097962019-07-15 16:25:33 +02005124 /* Stores the query string. */
5125 lua_pushstring(L, "qs");
5126 if (*q == '?')
5127 q++;
5128 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005129 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02005130 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005131
Christopher Fauleta2097962019-07-15 16:25:33 +02005132 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5133 struct htx_blk *blk = htx_get_blk(htx, pos);
5134 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005135
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005136 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02005137 break;
5138 if (type == HTX_BLK_DATA)
5139 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005140 }
Christopher Faulet2e47e3a2023-01-13 11:40:24 +01005141 if (htx->extra != HTX_UNKOWN_PAYLOAD_LENGTH)
Christopher Fauleta2097962019-07-15 16:25:33 +02005142 len += htx->extra;
5143
5144 /* Stores the request path. */
5145 lua_pushstring(L, "length");
5146 lua_pushinteger(L, len);
5147 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005148
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005149 /* Create an empty array of HTTP request headers. */
5150 lua_pushstring(L, "response");
5151 lua_newtable(L);
5152 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01005153
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005154 /* Pop a class stream metatable and affect it to the table. */
5155 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
5156 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005157
5158 return 1;
5159}
5160
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005161__LJMP static int hlua_applet_http_set_var(lua_State *L)
5162{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005163 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005164 struct stream *s;
5165 const char *name;
5166 size_t len;
5167 struct sample smp;
5168
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005169 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5170 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005171
5172 /* It is useles to retrieve the stream, but this function
5173 * runs only in a stream context.
5174 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005175 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005176 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005177 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005178
5179 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005180 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005181 hlua_lua2smp(L, 3, &smp);
5182
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02005183 /* Store the sample in a variable. We don't need to dup the smp, vars API
5184 * already takes care of duplicating dynamic var data.
5185 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005186 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005187
5188 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5189 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5190 else
5191 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5192
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005193 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005194}
5195
5196__LJMP static int hlua_applet_http_unset_var(lua_State *L)
5197{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005198 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005199 struct stream *s;
5200 const char *name;
5201 size_t len;
5202 struct sample smp;
5203
5204 MAY_LJMP(check_args(L, 2, "unset_var"));
5205
5206 /* It is useles to retrieve the stream, but this function
5207 * runs only in a stream context.
5208 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005209 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005210 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005211 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005212
5213 /* Unset the variable. */
5214 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005215 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5216 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005217}
5218
5219__LJMP static int hlua_applet_http_get_var(lua_State *L)
5220{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005221 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005222 struct stream *s;
5223 const char *name;
5224 size_t len;
5225 struct sample smp;
5226
5227 MAY_LJMP(check_args(L, 2, "get_var"));
5228
5229 /* It is useles to retrieve the stream, but this function
5230 * runs only in a stream context.
5231 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005232 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005233 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02005234 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005235
5236 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02005237 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005238 lua_pushnil(L);
5239 return 1;
5240 }
5241
Aurelien DARRAGON41217722023-05-17 10:44:47 +02005242 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01005243}
5244
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005245__LJMP static int hlua_applet_http_set_priv(lua_State *L)
5246{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005247 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5248 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005249 struct hlua *hlua;
5250
5251 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005252 if (!s->hlua)
5253 return 0;
5254 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005255
5256 MAY_LJMP(check_args(L, 2, "set_priv"));
5257
5258 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005259 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005260
5261 /* Get and store new value. */
5262 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5263 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5264
5265 return 0;
5266}
5267
5268__LJMP static int hlua_applet_http_get_priv(lua_State *L)
5269{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005270 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5271 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01005272 struct hlua *hlua;
5273
5274 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005275 if (!s->hlua) {
5276 lua_pushnil(L);
5277 return 1;
5278 }
5279 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01005280
5281 /* Push configuration index in the stack. */
5282 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5283
5284 return 1;
5285}
5286
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005287/* If expected data not yet available, it returns a yield. This function
5288 * consumes the data in the buffer. It returns a string containing the
5289 * data. This string can be empty.
5290 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005291__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005292{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005293 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005294 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005295 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005296 struct htx *htx;
5297 struct htx_blk *blk;
5298 size_t count;
5299 int stop = 0;
5300
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005301 htx = htx_from_buf(&req->buf);
5302 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02005303 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01005304
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005305 while (count && !stop && blk) {
5306 enum htx_blk_type type = htx_get_blk_type(blk);
5307 uint32_t sz = htx_get_blksz(blk);
5308 struct ist v;
5309 uint32_t vlen;
5310 char *nl;
5311
5312 vlen = sz;
5313 if (vlen > count) {
5314 if (type != HTX_BLK_DATA)
5315 break;
5316 vlen = count;
5317 }
5318
5319 switch (type) {
5320 case HTX_BLK_UNUSED:
5321 break;
5322
5323 case HTX_BLK_DATA:
5324 v = htx_get_blk_value(htx, blk);
5325 v.len = vlen;
5326 nl = istchr(v, '\n');
5327 if (nl != NULL) {
5328 stop = 1;
5329 vlen = nl - v.ptr + 1;
5330 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005331 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005332 break;
5333
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005334 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005335 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005336 stop = 1;
5337 break;
5338
5339 default:
5340 break;
5341 }
5342
Willy Tarreau84240042022-02-28 16:51:23 +01005343 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005344 count -= vlen;
5345 if (sz == vlen)
5346 blk = htx_remove_blk(htx, blk);
5347 else {
5348 htx_cut_data_blk(htx, blk, vlen);
5349 break;
5350 }
5351 }
5352
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005353 /* The message was fully consumed and no more data are expected
5354 * (EOM flag set).
5355 */
Christopher Fauletc9e8a322023-06-12 09:16:27 +02005356 if (htx_is_empty(htx) && (sc_opposite(sc)->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005357 stop = 1;
5358
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005359 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005360 if (!stop) {
Willy Tarreau90e8b452022-05-25 18:21:43 +02005361 applet_need_more_data(luactx->appctx);
Christopher Fauleta2097962019-07-15 16:25:33 +02005362 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005363 }
5364
5365 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005366 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005367 return 1;
5368}
5369
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005370
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005371/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005372__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005373{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005374 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005375
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005376 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005377 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005378
Christopher Fauleta2097962019-07-15 16:25:33 +02005379 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005380}
5381
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005382/* If expected data not yet available, it returns a yield. This function
5383 * consumes the data in the buffer. It returns a string containing the
5384 * data. This string can be empty.
5385 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005386__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005387{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005388 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005389 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005390 struct channel *req = sc_oc(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005391 struct htx *htx;
5392 struct htx_blk *blk;
5393 size_t count;
5394 int len;
5395
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005396 htx = htx_from_buf(&req->buf);
5397 len = MAY_LJMP(luaL_checkinteger(L, 2));
5398 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005399 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005400 while (count && len && blk) {
5401 enum htx_blk_type type = htx_get_blk_type(blk);
5402 uint32_t sz = htx_get_blksz(blk);
5403 struct ist v;
5404 uint32_t vlen;
5405
5406 vlen = sz;
5407 if (len > 0 && vlen > len)
5408 vlen = len;
5409 if (vlen > count) {
5410 if (type != HTX_BLK_DATA)
5411 break;
5412 vlen = count;
5413 }
5414
5415 switch (type) {
5416 case HTX_BLK_UNUSED:
5417 break;
5418
5419 case HTX_BLK_DATA:
5420 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005421 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005422 break;
5423
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005424 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005425 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005426 len = 0;
5427 break;
5428
5429 default:
5430 break;
5431 }
5432
Willy Tarreau84240042022-02-28 16:51:23 +01005433 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005434 count -= vlen;
5435 if (len > 0)
5436 len -= vlen;
5437 if (sz == vlen)
5438 blk = htx_remove_blk(htx, blk);
5439 else {
5440 htx_cut_data_blk(htx, blk, vlen);
5441 break;
5442 }
5443 }
5444
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005445 /* The message was fully consumed and no more data are expected
5446 * (EOM flag set).
5447 */
Christopher Fauletc9e8a322023-06-12 09:16:27 +02005448 if (htx_is_empty(htx) && (sc_opposite(sc)->flags & SC_FL_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005449 len = 0;
5450
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005451 htx_to_buf(htx, &req->buf);
5452
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005453 /* If we are no other data available, yield waiting for new data. */
5454 if (len) {
5455 if (len > 0) {
5456 lua_pushinteger(L, len);
5457 lua_replace(L, 2);
5458 }
Willy Tarreau90e8b452022-05-25 18:21:43 +02005459 applet_need_more_data(luactx->appctx);
Willy Tarreau9635e032018-10-16 17:52:55 +02005460 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005461 }
5462
5463 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005464 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005465 return 1;
5466}
5467
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005468/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005469__LJMP static int hlua_applet_http_recv(lua_State *L)
5470{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005471 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005472 int len = -1;
5473
5474 /* Check arguments. */
5475 if (lua_gettop(L) > 2)
5476 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5477 if (lua_gettop(L) >= 2) {
5478 len = MAY_LJMP(luaL_checkinteger(L, 2));
5479 lua_pop(L, 1);
5480 }
5481
Christopher Fauleta2097962019-07-15 16:25:33 +02005482 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005483
Christopher Fauleta2097962019-07-15 16:25:33 +02005484 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005485 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005486
Christopher Fauleta2097962019-07-15 16:25:33 +02005487 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005488}
5489
5490/* Append data in the output side of the buffer. This data is immediately
5491 * sent. The function returns the amount of data written. If the buffer
5492 * cannot contain the data, the function yields. The function returns -1
5493 * if the channel is closed.
5494 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005495__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005496{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005497 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005498 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005499 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005500 struct htx *htx = htx_from_buf(&res->buf);
5501 const char *data;
5502 size_t len;
5503 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5504 int max;
5505
Christopher Faulet9060fc02019-07-03 11:39:30 +02005506 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005507 if (!max)
5508 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005509
5510 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5511
5512 /* Get the max amount of data which can write as input in the channel. */
5513 if (max > (len - l))
5514 max = len - l;
5515
5516 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005517 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005518 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005519
5520 /* update counters. */
5521 l += max;
5522 lua_pop(L, 1);
5523 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005524
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005525 /* If some data is not send, declares the situation to the
5526 * applet, and returns a yield.
5527 */
5528 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005529 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005530 htx_to_buf(htx, &res->buf);
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005531 sc_need_room(sc, channel_recv_max(res) + 1);
Willy Tarreau9635e032018-10-16 17:52:55 +02005532 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005533 }
5534
Christopher Fauleta2097962019-07-15 16:25:33 +02005535 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005536 return 1;
5537}
5538
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005539/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005540 * yield the LUA process, and resume it without checking the
5541 * input arguments.
5542 */
5543__LJMP static int hlua_applet_http_send(lua_State *L)
5544{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005545 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005546 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005547
5548 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005549 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005550 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5551 WILL_LJMP(lua_error(L));
5552 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005553
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005554 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005555 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005556
Christopher Fauleta2097962019-07-15 16:25:33 +02005557 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005558}
5559
5560__LJMP static int hlua_applet_http_addheader(lua_State *L)
5561{
5562 const char *name;
5563 int ret;
5564
5565 MAY_LJMP(hlua_checkapplet_http(L, 1));
5566 name = MAY_LJMP(luaL_checkstring(L, 2));
5567 MAY_LJMP(luaL_checkstring(L, 3));
5568
5569 /* Push in the stack the "response" entry. */
5570 ret = lua_getfield(L, 1, "response");
5571 if (ret != LUA_TTABLE) {
5572 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5573 "is expected as an array. %s found", lua_typename(L, ret));
5574 WILL_LJMP(lua_error(L));
5575 }
5576
5577 /* check if the header is already registered if it is not
5578 * the case, register it.
5579 */
5580 ret = lua_getfield(L, -1, name);
5581 if (ret == LUA_TNIL) {
5582
5583 /* Entry not found. */
5584 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5585
5586 /* Insert the new header name in the array in the top of the stack.
5587 * It left the new array in the top of the stack.
5588 */
5589 lua_newtable(L);
5590 lua_pushvalue(L, 2);
5591 lua_pushvalue(L, -2);
5592 lua_settable(L, -4);
5593
5594 } else if (ret != LUA_TTABLE) {
5595
5596 /* corruption error. */
5597 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5598 "is expected as an array. %s found", name, lua_typename(L, ret));
5599 WILL_LJMP(lua_error(L));
5600 }
5601
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005602 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005603 * the header value as new entry.
5604 */
5605 lua_pushvalue(L, 3);
5606 ret = lua_rawlen(L, -2);
5607 lua_rawseti(L, -2, ret + 1);
5608 lua_pushboolean(L, 1);
5609 return 1;
5610}
5611
5612__LJMP static int hlua_applet_http_status(lua_State *L)
5613{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005614 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005615 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005616 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005617 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005618
5619 if (status < 100 || status > 599) {
5620 lua_pushboolean(L, 0);
5621 return 1;
5622 }
5623
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005624 http_ctx->status = status;
5625 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005626 lua_pushboolean(L, 1);
5627 return 1;
5628}
5629
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005630
Christopher Fauleta2097962019-07-15 16:25:33 +02005631__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005632{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005633 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005634 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +02005635 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005636 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005637 struct htx *htx;
5638 struct htx_sl *sl;
5639 struct h1m h1m;
5640 const char *status, *reason;
5641 const char *name, *value;
5642 size_t nlen, vlen;
5643 unsigned int flags;
5644
5645 /* Send the message at once. */
5646 htx = htx_from_buf(&res->buf);
5647 h1m_init_res(&h1m);
5648
5649 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005650 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5651 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005652 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005653 reason = http_get_reason(http_ctx->status);
5654 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005655 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5656 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5657 }
5658 else {
5659 flags = HTX_SL_F_IS_RESP;
5660 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5661 }
5662 if (!sl) {
5663 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005664 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005665 WILL_LJMP(lua_error(L));
5666 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005667 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005668
5669 /* Get the array associated to the field "response" in the object AppletHTTP. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005670 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5671 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005672 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005673 WILL_LJMP(lua_error(L));
5674 }
5675
5676 /* Browse the list of headers. */
5677 lua_pushnil(L);
5678 while(lua_next(L, -2) != 0) {
5679 /* We expect a string as -2. */
5680 if (lua_type(L, -2) != LUA_TSTRING) {
5681 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005682 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005683 lua_typename(L, lua_type(L, -2)));
5684 WILL_LJMP(lua_error(L));
5685 }
5686 name = lua_tolstring(L, -2, &nlen);
5687
5688 /* We expect an array as -1. */
5689 if (lua_type(L, -1) != LUA_TTABLE) {
5690 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 +02005691 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005692 name,
5693 lua_typename(L, lua_type(L, -1)));
5694 WILL_LJMP(lua_error(L));
5695 }
5696
5697 /* Browse the table who is on the top of the stack. */
5698 lua_pushnil(L);
5699 while(lua_next(L, -2) != 0) {
5700 int id;
5701
5702 /* We expect a number as -2. */
5703 if (lua_type(L, -2) != LUA_TNUMBER) {
5704 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 +02005705 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005706 name,
5707 lua_typename(L, lua_type(L, -2)));
5708 WILL_LJMP(lua_error(L));
5709 }
5710 id = lua_tointeger(L, -2);
5711
5712 /* We expect a string as -2. */
5713 if (lua_type(L, -1) != LUA_TSTRING) {
5714 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 +02005715 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005716 name, id,
5717 lua_typename(L, lua_type(L, -1)));
5718 WILL_LJMP(lua_error(L));
5719 }
5720 value = lua_tolstring(L, -1, &vlen);
5721
5722 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005723 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5724 int ret;
5725
5726 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5727 if (ret < 0) {
5728 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5729 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5730 name);
5731 WILL_LJMP(lua_error(L));
5732 }
5733 else if (ret == 0)
5734 goto next; /* Skip it */
5735 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005736 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5737 struct ist v = ist2(value, vlen);
5738 int ret;
5739
5740 ret = h1_parse_cont_len_header(&h1m, &v);
5741 if (ret < 0) {
5742 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005743 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005744 name);
5745 WILL_LJMP(lua_error(L));
5746 }
5747 else if (ret == 0)
5748 goto next; /* Skip it */
5749 }
5750
5751 /* Add a new header */
5752 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5753 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005754 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005755 name);
5756 WILL_LJMP(lua_error(L));
5757 }
5758 next:
5759 /* Remove the array from the stack, and get next element with a remaining string. */
5760 lua_pop(L, 1);
5761 }
5762
5763 /* Remove the array from the stack, and get next element with a remaining string. */
5764 lua_pop(L, 1);
5765 }
5766
5767 if (h1m.flags & H1_MF_CHNK)
5768 h1m.flags &= ~H1_MF_CLEN;
5769 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5770 h1m.flags |= H1_MF_XFER_LEN;
5771
5772 /* Uset HTX start-line flags */
5773 if (h1m.flags & H1_MF_XFER_ENC)
5774 flags |= HTX_SL_F_XFER_ENC;
5775 if (h1m.flags & H1_MF_XFER_LEN) {
5776 flags |= HTX_SL_F_XFER_LEN;
5777 if (h1m.flags & H1_MF_CHNK)
5778 flags |= HTX_SL_F_CHNK;
5779 else if (h1m.flags & H1_MF_CLEN)
5780 flags |= HTX_SL_F_CLEN;
5781 if (h1m.body_len == 0)
5782 flags |= HTX_SL_F_BODYLESS;
5783 }
5784 sl->flags |= flags;
5785
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005786 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005787 * and the status code implies the presence of a message body, we must
5788 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005789 * for the keepalive compliance. If the applet announces a transfer-encoding
5790 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005791 */
5792 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005793 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005794 /* Add a new header */
5795 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5796 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5797 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005798 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005799 WILL_LJMP(lua_error(L));
5800 }
5801 }
5802
5803 /* Finalize headers. */
5804 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5805 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005806 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005807 WILL_LJMP(lua_error(L));
5808 }
5809
5810 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5811 b_reset(&res->buf);
5812 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5813 WILL_LJMP(lua_error(L));
5814 }
5815
5816 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005817 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005818
5819 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005820 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005821 return 0;
5822
5823}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005824/* We will build the status line and the headers of the HTTP response.
5825 * We will try send at once if its not possible, we give back the hand
5826 * waiting for more room.
5827 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005828__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005829{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005830 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauc12b3212022-05-27 11:08:15 +02005831 struct stconn *sc = appctx_sc(luactx->appctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +02005832 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005833
5834 if (co_data(res)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +02005835 sc_need_room(sc, -1);
Christopher Fauleta2097962019-07-15 16:25:33 +02005836 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005837 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005838 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005839}
5840
5841
Christopher Fauleta2097962019-07-15 16:25:33 +02005842__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005843{
Christopher Fauleta2097962019-07-15 16:25:33 +02005844 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005845}
5846
Christopher Fauleta2097962019-07-15 16:25:33 +02005847/*
5848 *
5849 *
5850 * Class HTTP
5851 *
5852 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005853 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005854
5855/* Returns a struct hlua_txn if the stack entry "ud" is
5856 * a class stream, otherwise it throws an error.
5857 */
5858__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005859{
Christopher Fauleta2097962019-07-15 16:25:33 +02005860 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5861}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005862
Christopher Fauleta2097962019-07-15 16:25:33 +02005863/* This function creates and push in the stack a HTTP object
5864 * according with a current TXN.
5865 */
5866static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5867{
5868 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005869
Christopher Fauleta2097962019-07-15 16:25:33 +02005870 /* Check stack size. */
5871 if (!lua_checkstack(L, 3))
5872 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005873
Christopher Fauleta2097962019-07-15 16:25:33 +02005874 /* Create the object: obj[0] = userdata.
5875 * Note that the base of the Converters object is the
5876 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005877 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005878 lua_newtable(L);
5879 htxn = lua_newuserdata(L, sizeof(*htxn));
5880 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005881
5882 htxn->s = txn->s;
5883 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005884 htxn->dir = txn->dir;
5885 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005886
5887 /* Pop a class stream metatable and affect it to the table. */
5888 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5889 lua_setmetatable(L, -2);
5890
5891 return 1;
5892}
5893
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005894/* This function creates and returns an array containing the status-line
5895 * elements. This function does not fails.
5896 */
5897__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5898{
5899 /* Create the table. */
5900 lua_newtable(L);
5901
5902 if (sl->flags & HTX_SL_F_IS_RESP) {
5903 lua_pushstring(L, "version");
5904 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5905 lua_settable(L, -3);
5906 lua_pushstring(L, "code");
5907 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5908 lua_settable(L, -3);
5909 lua_pushstring(L, "reason");
5910 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5911 lua_settable(L, -3);
5912 }
5913 else {
5914 lua_pushstring(L, "method");
5915 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5916 lua_settable(L, -3);
5917 lua_pushstring(L, "uri");
5918 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5919 lua_settable(L, -3);
5920 lua_pushstring(L, "version");
5921 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5922 lua_settable(L, -3);
5923 }
5924 return 1;
5925}
5926
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005927/* This function creates ans returns an array of HTTP headers.
5928 * This function does not fails. It is used as wrapper with the
5929 * 2 following functions.
5930 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005931__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005932{
Christopher Fauleta2097962019-07-15 16:25:33 +02005933 struct htx *htx;
5934 int32_t pos;
5935
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005936 /* Create the table. */
5937 lua_newtable(L);
5938
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005939
Christopher Fauleta2097962019-07-15 16:25:33 +02005940 htx = htxbuf(&msg->chn->buf);
5941 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5942 struct htx_blk *blk = htx_get_blk(htx, pos);
5943 enum htx_blk_type type = htx_get_blk_type(blk);
5944 struct ist n, v;
5945 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005946
Christopher Fauleta2097962019-07-15 16:25:33 +02005947 if (type == HTX_BLK_HDR) {
5948 n = htx_get_blk_name(htx,blk);
5949 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005950 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005951 else if (type == HTX_BLK_EOH)
5952 break;
5953 else
5954 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005955
Christopher Fauleta2097962019-07-15 16:25:33 +02005956 /* Check for existing entry:
5957 * assume that the table is on the top of the stack, and
5958 * push the key in the stack, the function lua_gettable()
5959 * perform the lookup.
5960 */
5961 lua_pushlstring(L, n.ptr, n.len);
5962 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005963
Christopher Fauleta2097962019-07-15 16:25:33 +02005964 switch (lua_type(L, -1)) {
5965 case LUA_TNIL:
5966 /* Table not found, create it. */
5967 lua_pop(L, 1); /* remove the nil value. */
5968 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5969 lua_newtable(L); /* create and push empty table. */
5970 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5971 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5972 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005973 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005974
Christopher Fauleta2097962019-07-15 16:25:33 +02005975 case LUA_TTABLE:
5976 /* Entry found: push the value in the table. */
5977 len = lua_rawlen(L, -1);
5978 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5979 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5980 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5981 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005982
Christopher Fauleta2097962019-07-15 16:25:33 +02005983 default:
5984 /* Other cases are errors. */
5985 hlua_pusherror(L, "internal error during the parsing of headers.");
5986 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005987 }
5988 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005989 return 1;
5990}
5991
5992__LJMP static int hlua_http_req_get_headers(lua_State *L)
5993{
5994 struct hlua_txn *htxn;
5995
5996 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5997 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5998
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005999 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006000 WILL_LJMP(lua_error(L));
6001
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006002 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006003}
6004
6005__LJMP static int hlua_http_res_get_headers(lua_State *L)
6006{
6007 struct hlua_txn *htxn;
6008
6009 MAY_LJMP(check_args(L, 1, "res_get_headers"));
6010 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6011
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006012 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006013 WILL_LJMP(lua_error(L));
6014
Christopher Faulet9d1332b2020-02-24 16:46:16 +01006015 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006016}
6017
6018/* This function replace full header, or just a value in
6019 * the request or in the response. It is a wrapper fir the
6020 * 4 following functions.
6021 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006022__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006023{
6024 size_t name_len;
6025 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6026 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
6027 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02006028 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02006029 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006030
Dragan Dosen26743032019-04-30 15:54:36 +02006031 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006032 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
6033
Christopher Fauleta2097962019-07-15 16:25:33 +02006034 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006035 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02006036 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006037 return 0;
6038}
6039
6040__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
6041{
6042 struct hlua_txn *htxn;
6043
6044 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6045 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6046
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006047 if (htxn->dir != SMP_OPT_DIR_REQ || !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->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006051}
6052
6053__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
6054{
6055 struct hlua_txn *htxn;
6056
6057 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
6058 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6059
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006060 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006061 WILL_LJMP(lua_error(L));
6062
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006063 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006064}
6065
6066__LJMP static int hlua_http_req_rep_val(lua_State *L)
6067{
6068 struct hlua_txn *htxn;
6069
6070 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
6071 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6072
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006073 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006074 WILL_LJMP(lua_error(L));
6075
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006076 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006077}
6078
6079__LJMP static int hlua_http_res_rep_val(lua_State *L)
6080{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006081 struct hlua_txn *htxn;
6082
6083 MAY_LJMP(check_args(L, 4, "res_rep_val"));
6084 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6085
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006086 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006087 WILL_LJMP(lua_error(L));
6088
Christopher Fauletd1914aa2020-02-24 16:52:46 +01006089 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006090}
6091
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006092/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006093 * It is a wrapper for the 2 following functions.
6094 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006095__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006096{
6097 size_t len;
6098 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006099 struct htx *htx = htxbuf(&msg->chn->buf);
6100 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006101
Christopher Fauleta2097962019-07-15 16:25:33 +02006102 ctx.blk = NULL;
6103 while (http_find_header(htx, ist2(name, len), &ctx, 1))
6104 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006105 return 0;
6106}
6107
6108__LJMP static int hlua_http_req_del_hdr(lua_State *L)
6109{
6110 struct hlua_txn *htxn;
6111
6112 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
6113 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6114
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006115 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006116 WILL_LJMP(lua_error(L));
6117
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006118 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006119}
6120
6121__LJMP static int hlua_http_res_del_hdr(lua_State *L)
6122{
6123 struct hlua_txn *htxn;
6124
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006125 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006126 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6127
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006128 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006129 WILL_LJMP(lua_error(L));
6130
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006131 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006132}
6133
6134/* This function adds an header. It is a wrapper used by
6135 * the 2 following functions.
6136 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01006137__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006138{
6139 size_t name_len;
6140 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6141 size_t value_len;
6142 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02006143 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006144
Christopher Fauleta2097962019-07-15 16:25:33 +02006145 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
6146 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006147 return 0;
6148}
6149
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006150__LJMP static int hlua_http_req_add_hdr(lua_State *L)
6151{
6152 struct hlua_txn *htxn;
6153
6154 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
6155 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6156
6157 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6158 WILL_LJMP(lua_error(L));
6159
6160 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6161}
6162
6163__LJMP static int hlua_http_res_add_hdr(lua_State *L)
6164{
6165 struct hlua_txn *htxn;
6166
6167 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
6168 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6169
6170 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6171 WILL_LJMP(lua_error(L));
6172
6173 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6174}
6175
6176static int hlua_http_req_set_hdr(lua_State *L)
6177{
6178 struct hlua_txn *htxn;
6179
6180 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
6181 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6182
6183 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6184 WILL_LJMP(lua_error(L));
6185
6186 hlua_http_del_hdr(L, &htxn->s->txn->req);
6187 return hlua_http_add_hdr(L, &htxn->s->txn->req);
6188}
6189
6190static int hlua_http_res_set_hdr(lua_State *L)
6191{
6192 struct hlua_txn *htxn;
6193
6194 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
6195 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6196
6197 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6198 WILL_LJMP(lua_error(L));
6199
6200 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
6201 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
6202}
6203
6204/* This function set the method. */
6205static int hlua_http_req_set_meth(lua_State *L)
6206{
6207 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6208 size_t name_len;
6209 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6210
6211 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6212 WILL_LJMP(lua_error(L));
6213
6214 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
6215 return 1;
6216}
6217
6218/* This function set the method. */
6219static int hlua_http_req_set_path(lua_State *L)
6220{
6221 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6222 size_t name_len;
6223 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6224
6225 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6226 WILL_LJMP(lua_error(L));
6227
6228 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
6229 return 1;
6230}
6231
6232/* This function set the query-string. */
6233static int hlua_http_req_set_query(lua_State *L)
6234{
6235 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6236 size_t name_len;
6237 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6238
6239 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6240 WILL_LJMP(lua_error(L));
6241
6242 /* Check length. */
6243 if (name_len > trash.size - 1) {
6244 lua_pushboolean(L, 0);
6245 return 1;
6246 }
6247
6248 /* Add the mark question as prefix. */
6249 chunk_reset(&trash);
6250 trash.area[trash.data++] = '?';
6251 memcpy(trash.area + trash.data, name, name_len);
6252 trash.data += name_len;
6253
6254 lua_pushboolean(L,
6255 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
6256 return 1;
6257}
6258
6259/* This function set the uri. */
6260static int hlua_http_req_set_uri(lua_State *L)
6261{
6262 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6263 size_t name_len;
6264 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6265
6266 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
6267 WILL_LJMP(lua_error(L));
6268
6269 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
6270 return 1;
6271}
6272
6273/* This function set the response code & optionally reason. */
6274static int hlua_http_res_set_status(lua_State *L)
6275{
6276 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
6277 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
6278 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6279 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
6280
6281 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
6282 WILL_LJMP(lua_error(L));
6283
6284 http_res_set_status(code, reason, htxn->s);
6285 return 0;
6286}
6287
6288/*
6289 *
6290 *
6291 * Class HTTPMessage
6292 *
6293 *
6294 */
6295
6296/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
6297 * otherwise it throws an error.
6298 */
6299__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
6300{
6301 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
6302}
6303
6304/* Creates and pushes on the stack a HTTP object according with a current TXN.
6305 */
Christopher Faulet78c35472020-02-26 17:14:08 +01006306static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006307{
6308 /* Check stack size. */
6309 if (!lua_checkstack(L, 3))
6310 return 0;
6311
6312 lua_newtable(L);
6313 lua_pushlightuserdata(L, msg);
6314 lua_rawseti(L, -2, 0);
6315
6316 /* Create the "channel" field that contains the request channel object. */
6317 lua_pushstring(L, "channel");
6318 if (!hlua_channel_new(L, msg->chn))
6319 return 0;
6320 lua_rawset(L, -3);
6321
6322 /* Pop a class stream metatable and affect it to the table. */
6323 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6324 lua_setmetatable(L, -2);
6325
6326 return 1;
6327}
6328
6329/* Helper function returning a filter attached to the HTTP message at the
6330 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006331 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006332 * filled with output and input length respectively.
6333 */
6334static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6335{
6336 struct channel *chn = msg->chn;
6337 struct htx *htx = htxbuf(&chn->buf);
6338 struct filter *filter = NULL;
6339
6340 *offset = co_data(msg->chn);
6341 *len = htx->data - co_data(msg->chn);
6342
6343 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6344 filter = lua_touserdata (L, -1);
6345 if (msg->msg_state >= HTTP_MSG_DATA) {
6346 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6347
6348 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6349 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6350 }
6351 }
6352
6353 lua_pop(L, 1);
6354 return filter;
6355}
6356
6357/* Returns true if the channel attached to the HTTP message is the response
6358 * channel.
6359 */
6360__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6361{
6362 struct http_msg *msg;
6363
6364 MAY_LJMP(check_args(L, 1, "is_resp"));
6365 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6366
6367 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6368 return 1;
6369}
6370
6371/* Returns an array containing the elements status-line of the HTTP message. It relies
6372 * on hlua_http_get_stline().
6373 */
6374__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6375{
6376 struct http_msg *msg;
6377 struct htx *htx;
6378 struct htx_sl *sl;
6379
6380 MAY_LJMP(check_args(L, 1, "get_stline"));
6381 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6382
6383 if (msg->msg_state > HTTP_MSG_BODY)
6384 WILL_LJMP(lua_error(L));
6385
6386 htx = htxbuf(&msg->chn->buf);
6387 sl = http_get_stline(htx);
6388 if (!sl)
6389 return 0;
6390 return hlua_http_get_stline(L, sl);
6391}
6392
6393/* Returns an array containing all headers of the HTTP message. it relies on
6394 * hlua_http_get_headers().
6395 */
6396__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6397{
6398 struct http_msg *msg;
6399
6400 MAY_LJMP(check_args(L, 1, "get_headers"));
6401 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6402
6403 if (msg->msg_state > HTTP_MSG_BODY)
6404 WILL_LJMP(lua_error(L));
6405
6406 return hlua_http_get_headers(L, msg);
6407}
6408
6409/* Deletes all occurrences of an header in the HTTP message matching on its
6410 * name. It relies on hlua_http_del_hdr().
6411 */
6412__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6413{
6414 struct http_msg *msg;
6415
6416 MAY_LJMP(check_args(L, 2, "del_header"));
6417 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6418
6419 if (msg->msg_state > HTTP_MSG_BODY)
6420 WILL_LJMP(lua_error(L));
6421
6422 return hlua_http_del_hdr(L, msg);
6423}
6424
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006425/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006426 * message given its name against a regex and replaces it if it matches. It
6427 * relies on hlua_http_rep_hdr().
6428 */
6429__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6430{
6431 struct http_msg *msg;
6432
6433 MAY_LJMP(check_args(L, 4, "rep_header"));
6434 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6435
6436 if (msg->msg_state > HTTP_MSG_BODY)
6437 WILL_LJMP(lua_error(L));
6438
6439 return hlua_http_rep_hdr(L, msg, 1);
6440}
6441
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006442/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006443 * message given its name against a regex and replaces it if it matches. It
6444 * relies on hlua_http_rep_hdr().
6445 */
6446__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6447{
6448 struct http_msg *msg;
6449
6450 MAY_LJMP(check_args(L, 4, "rep_value"));
6451 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6452
6453 if (msg->msg_state > HTTP_MSG_BODY)
6454 WILL_LJMP(lua_error(L));
6455
6456 return hlua_http_rep_hdr(L, msg, 0);
6457}
6458
6459/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6460__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6461{
6462 struct http_msg *msg;
6463
6464 MAY_LJMP(check_args(L, 3, "add_header"));
6465 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6466
6467 if (msg->msg_state > HTTP_MSG_BODY)
6468 WILL_LJMP(lua_error(L));
6469
6470 return hlua_http_add_hdr(L, msg);
6471}
6472
6473/* Add an header in the HTTP message removing existing headers with the same
6474 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6475 */
6476__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6477{
6478 struct http_msg *msg;
6479
6480 MAY_LJMP(check_args(L, 3, "set_header"));
6481 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6482
6483 if (msg->msg_state > HTTP_MSG_BODY)
6484 WILL_LJMP(lua_error(L));
6485
6486 hlua_http_del_hdr(L, msg);
6487 return hlua_http_add_hdr(L, msg);
6488}
6489
6490/* Rewrites the request method. It relies on http_req_replace_stline(). */
6491__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6492{
6493 struct stream *s;
6494 struct http_msg *msg;
6495 const char *name;
6496 size_t name_len;
6497
6498 MAY_LJMP(check_args(L, 2, "set_method"));
6499 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6500 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6501
6502 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6503 WILL_LJMP(lua_error(L));
6504
6505 s = chn_strm(msg->chn);
6506 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6507 return 1;
6508}
6509
6510/* Rewrites the request path. It relies on http_req_replace_stline(). */
6511__LJMP static int hlua_http_msg_set_path(lua_State *L)
6512{
6513 struct stream *s;
6514 struct http_msg *msg;
6515 const char *name;
6516 size_t name_len;
6517
6518 MAY_LJMP(check_args(L, 2, "set_path"));
6519 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6520 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6521
6522 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6523 WILL_LJMP(lua_error(L));
6524
6525 s = chn_strm(msg->chn);
6526 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6527 return 1;
6528}
6529
6530/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6531__LJMP static int hlua_http_msg_set_query(lua_State *L)
6532{
6533 struct stream *s;
6534 struct http_msg *msg;
6535 const char *name;
6536 size_t name_len;
6537
6538 MAY_LJMP(check_args(L, 2, "set_query"));
6539 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6540 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6541
6542 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6543 WILL_LJMP(lua_error(L));
6544
6545 /* Check length. */
6546 if (name_len > trash.size - 1) {
6547 lua_pushboolean(L, 0);
6548 return 1;
6549 }
6550
6551 /* Add the mark question as prefix. */
6552 chunk_reset(&trash);
6553 trash.area[trash.data++] = '?';
6554 memcpy(trash.area + trash.data, name, name_len);
6555 trash.data += name_len;
6556
6557 s = chn_strm(msg->chn);
6558 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6559 return 1;
6560}
6561
6562/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6563__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6564{
6565 struct stream *s;
6566 struct http_msg *msg;
6567 const char *name;
6568 size_t name_len;
6569
6570 MAY_LJMP(check_args(L, 2, "set_uri"));
6571 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6572 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6573
6574 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6575 WILL_LJMP(lua_error(L));
6576
6577 s = chn_strm(msg->chn);
6578 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6579 return 1;
6580}
6581
6582/* Rewrites the response status code. It relies on http_res_set_status(). */
6583__LJMP static int hlua_http_msg_set_status(lua_State *L)
6584{
6585 struct http_msg *msg;
6586 unsigned int code;
6587 const char *reason;
6588 size_t reason_len;
6589
6590 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6591 code = MAY_LJMP(luaL_checkinteger(L, 2));
6592 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6593
6594 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6595 WILL_LJMP(lua_error(L));
6596
6597 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6598 return 1;
6599}
6600
6601/* Returns true if the HTTP message is full. */
6602__LJMP static int hlua_http_msg_is_full(lua_State *L)
6603{
6604 struct http_msg *msg;
6605
6606 MAY_LJMP(check_args(L, 1, "is_full"));
6607 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6608 lua_pushboolean(L, channel_full(msg->chn, 0));
6609 return 1;
6610}
6611
6612/* Returns true if the HTTP message may still receive data. */
6613__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6614{
6615 struct http_msg *msg;
6616 struct htx *htx;
6617
6618 MAY_LJMP(check_args(L, 1, "may_recv"));
6619 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6620 htx = htxbuf(&msg->chn->buf);
6621 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6622 return 1;
6623}
6624
6625/* Returns true if the HTTP message EOM was received */
6626__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6627{
6628 struct http_msg *msg;
6629 struct htx *htx;
6630
6631 MAY_LJMP(check_args(L, 1, "may_recv"));
6632 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6633 htx = htxbuf(&msg->chn->buf);
6634 lua_pushboolean(L, !htx_expect_more(htx));
6635 return 1;
6636}
6637
6638/* Returns the number of bytes available in the input side of the HTTP
6639 * message. This function never fails.
6640 */
6641__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6642{
6643 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006644 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006645
6646 MAY_LJMP(check_args(L, 1, "input"));
6647 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006648 hlua_http_msg_filter(L, 1, msg, &output, &input);
6649 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006650 return 1;
6651}
6652
6653/* Returns the number of bytes available in the output side of the HTTP
6654 * message. This function never fails.
6655 */
6656__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6657{
6658 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006659 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006660
6661 MAY_LJMP(check_args(L, 1, "output"));
6662 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006663 hlua_http_msg_filter(L, 1, msg, &output, &input);
6664 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006665 return 1;
6666}
6667
6668/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6669 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006670 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006671 * block. This function is called during the payload filtering, so the headers
6672 * are already scheduled for output (from the filter point of view).
6673 */
6674static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6675{
6676 struct htx *htx = htxbuf(&msg->chn->buf);
6677 struct htx_blk *blk;
6678 struct htx_ret htxret;
6679 luaL_Buffer b;
6680 int ret = 0;
6681
6682 luaL_buffinit(L, &b);
6683 htxret = htx_find_offset(htx, offset);
6684 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6685 enum htx_blk_type type = htx_get_blk_type(blk);
6686 struct ist v;
6687
6688 switch (type) {
6689 case HTX_BLK_UNUSED:
6690 break;
6691
6692 case HTX_BLK_DATA:
6693 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006694 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006695 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006696
6697 luaL_addlstring(&b, v.ptr, v.len);
6698 ret += v.len;
6699 break;
6700
6701 default:
vishnu0af4bd72021-10-24 06:46:24 +05306702 if (!ret)
6703 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006704 goto end;
6705 }
6706 offset = 0;
6707 }
6708
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006709end:
vishnu0af4bd72021-10-24 06:46:24 +05306710 if (!ret && (htx->flags & HTX_FL_EOM))
6711 goto no_data;
6712 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006713 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306714
6715 no_data:
6716 /* Remove the empty string and push nil on the stack */
6717 lua_pop(L, 1);
6718 lua_pushnil(L);
6719 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006720}
6721
6722/* Copies the string <str> to the HTTP message <msg> at the offset
6723 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006724 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006725 * the filter context.
6726 */
6727static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6728{
6729 struct htx *htx = htx_from_buf(&msg->chn->buf);
6730 struct htx_ret htxret;
6731 int /*max, */ret = 0;
6732
6733 /* Nothing to do, just return */
6734 if (unlikely(istlen(str) == 0))
6735 goto end;
6736
6737 if (istlen(str) > htx_free_data_space(htx)) {
6738 ret = -1;
6739 goto end;
6740 }
6741
6742 htxret = htx_find_offset(htx, offset);
6743 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6744 if (!htx_add_last_data(htx, str))
6745 goto end;
6746 }
6747 else {
6748 struct ist v = htx_get_blk_value(htx, htxret.blk);
6749 v.ptr += htxret.ret;
6750 v.len = 0;
6751 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6752 goto end;
6753 }
6754 ret = str.len;
6755 if (ret) {
6756 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6757 flt_update_offsets(filter, msg->chn, ret);
6758 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6759 }
6760
6761 end:
6762 htx_to_buf(htx, &msg->chn->buf);
6763 return ret;
6764}
6765
6766/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6767 * position <offset>. It stops on the first non-DATA HTX block. This function is
6768 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006769 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006770 * update the filter context.
6771 */
6772static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6773{
6774 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6775 struct htx *htx = htx_from_buf(&msg->chn->buf);
6776 struct htx_blk *blk;
6777 struct htx_ret htxret;
6778 size_t ret = 0;
6779
6780 /* Be sure <len> is always the amount of DATA to remove */
6781 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006782 /* When htx tail type == HTX_BLK_DATA, no need to take care
6783 * of special blocks like HTX_BLK_EOT.
6784 * We simply truncate after offset
6785 * (truncate targeted blk and discard the following ones)
6786 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006787 htx_truncate(htx, offset);
6788 ret = len;
6789 goto end;
6790 }
6791
6792 htxret = htx_find_offset(htx, offset);
6793 blk = htxret.blk;
6794 if (htxret.ret) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006795 /* dealing with offset: we need to trim targeted blk */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006796 struct ist v;
6797
6798 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6799 goto end;
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006800
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006801 v = htx_get_blk_value(htx, blk);
Tim Duesterhusa029d782022-10-08 12:33:18 +02006802 v = istadv(v, htxret.ret);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006803
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006804 v = isttrim(v, len);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006805 /* trimming data in blk: discard everything after the offset
6806 * (replace 'v' with 'IST_NULL')
6807 */
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006808 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006809 if (blk && v.len < len) {
6810 /* In this case, caller wants to keep removing data,
6811 * but we need to spare current blk
6812 * because it was already trimmed
6813 */
6814 blk = htx_get_next_blk(htx, blk);
6815 }
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006816 len -= v.len;
6817 ret += v.len;
6818 }
6819
6820
6821 while (blk && len) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006822 /* there is more data that needs to be discarded */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006823 enum htx_blk_type type = htx_get_blk_type(blk);
6824 uint32_t sz = htx_get_blksz(blk);
6825
6826 switch (type) {
6827 case HTX_BLK_UNUSED:
6828 break;
6829
6830 case HTX_BLK_DATA:
6831 if (len < sz) {
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006832 /* don't discard whole blk, only part of it
6833 * (from the beginning)
6834 */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006835 htx_cut_data_blk(htx, blk, len);
6836 ret += len;
6837 goto end;
6838 }
6839 break;
6840
6841 default:
Aurelien DARRAGONbcbcf982022-09-28 19:08:15 +02006842 /* HTX_BLK_EOT blk won't be removed */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006843 goto end;
6844 }
6845
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006846 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006847 len -= sz;
6848 ret += sz;
6849 blk = htx_remove_blk(htx, blk);
6850 }
6851
6852end:
6853 flt_update_offsets(filter, msg->chn, -ret);
6854 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6855 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6856 * to loose the EOM flag if the message is empty.
6857 */
6858}
6859
6860/* Copies input data found in an HTTP message. Unlike the channel function used
6861 * to duplicate raw data, this one can only be called inside a filter, from
6862 * http_payload callback. So it cannot yield. An exception is returned if it is
6863 * called from another callback. If nothing was copied, a nil value is pushed on
6864 * the stack.
6865 */
6866__LJMP static int hlua_http_msg_get_body(lua_State *L)
6867{
6868 struct http_msg *msg;
6869 struct filter *filter;
6870 size_t output, input;
6871 int offset, len;
6872
6873 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6874 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6875 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6876
6877 if (msg->msg_state < HTTP_MSG_DATA)
6878 WILL_LJMP(lua_error(L));
6879
6880 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6881 if (!filter || !hlua_filter_from_payload(filter))
6882 WILL_LJMP(lua_error(L));
6883
6884 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6885 lua_pushnil(L);
6886 return 1;
6887 }
6888
6889 offset = output;
6890 if (lua_gettop(L) > 1) {
6891 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6892 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006893 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006894 offset += output;
6895 if (offset < output || offset > input + output) {
6896 lua_pushfstring(L, "offset out of range.");
6897 WILL_LJMP(lua_error(L));
6898 }
6899 }
6900 len = output + input - offset;
6901 if (lua_gettop(L) == 3) {
6902 len = MAY_LJMP(luaL_checkinteger(L, 3));
6903 if (!len)
6904 goto dup;
6905 if (len == -1)
6906 len = global.tune.bufsize;
6907 if (len < 0) {
6908 lua_pushfstring(L, "length out of range.");
6909 WILL_LJMP(lua_error(L));
6910 }
6911 }
6912
6913 dup:
6914 _hlua_http_msg_dup(msg, L, offset, len);
6915 return 1;
6916}
6917
6918/* Appends a string to the HTTP message, after all existing DATA blocks but
6919 * before the trailers, if any. It returns the amount of data written or -1 if
6920 * nothing was copied. Unlike the channel function used to append data, this one
6921 * can only be called inside a filter, from http_payload callback. So it cannot
6922 * yield. An exception is returned if it is called from another callback.
6923 */
6924__LJMP static int hlua_http_msg_append(lua_State *L)
6925{
6926 struct http_msg *msg;
6927 struct filter *filter;
6928 const char *str;
6929 size_t offset, len, sz;
6930 int ret;
6931
6932 MAY_LJMP(check_args(L, 2, "append"));
6933 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6934
6935 if (msg->msg_state < HTTP_MSG_DATA)
6936 WILL_LJMP(lua_error(L));
6937
6938 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6939 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6940 if (!filter || !hlua_filter_from_payload(filter))
6941 WILL_LJMP(lua_error(L));
6942
6943 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6944 lua_pushinteger(L, ret);
6945 return 1;
6946}
6947
6948/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6949 * returns the amount of data written or -1 if nothing was copied. Unlike the
6950 * channel function used to prepend data, this one can only be called inside a
6951 * filter, from http_payload callback. So it cannot yield. An exception is
6952 * returned if it is called from another callback.
6953 */
6954__LJMP static int hlua_http_msg_prepend(lua_State *L)
6955{
6956 struct http_msg *msg;
6957 struct filter *filter;
6958 const char *str;
6959 size_t offset, len, sz;
6960 int ret;
6961
6962 MAY_LJMP(check_args(L, 2, "prepend"));
6963 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006964
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006965 if (msg->msg_state < HTTP_MSG_DATA)
6966 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006967
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006968 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6969 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6970 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006971 WILL_LJMP(lua_error(L));
6972
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006973 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6974 lua_pushinteger(L, ret);
6975 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006976}
6977
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006978/* Inserts a string to the HTTP message at a given offset. By default the string
6979 * is appended at the end of DATA blocks. It returns the amount of data written
6980 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6981 * this one can only be called inside a filter, from http_payload callback. So
6982 * it cannot yield. An exception is returned if it is called from another
6983 * callback.
6984 */
6985__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006986{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006987 struct http_msg *msg;
6988 struct filter *filter;
6989 const char *str;
6990 size_t input, output, sz;
6991 int offset;
6992 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006993
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006994 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6995 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006996 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006997
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006998 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006999 WILL_LJMP(lua_error(L));
7000
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007001 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007002 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007003 if (!filter || !hlua_filter_from_payload(filter))
7004 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007005
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007006 offset = output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007007 if (lua_gettop(L) > 2) {
7008 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7009 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007010 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007011 offset += output;
Aurelien DARRAGON7fdba0a2022-09-28 16:03:45 +02007012 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007013 lua_pushfstring(L, "offset out of range.");
7014 WILL_LJMP(lua_error(L));
7015 }
7016 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007017
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007018 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7019 lua_pushinteger(L, ret);
7020 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007021}
7022
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007023/* Removes a given amount of data from the HTTP message at a given offset. By
7024 * default all DATA blocks are removed. It returns the amount of data
7025 * removed. Unlike the channel function used to remove data, this one can only
7026 * be called inside a filter, from http_payload callback. So it cannot yield. An
7027 * exception is returned if it is called from another callback.
7028 */
7029__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007030{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007031 struct http_msg *msg;
7032 struct filter *filter;
7033 size_t input, output;
7034 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007035
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007036 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00007037 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007038 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007039
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007040 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007041 WILL_LJMP(lua_error(L));
7042
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007043 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007044 if (!filter || !hlua_filter_from_payload(filter))
7045 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007046
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007047 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00007048 if (lua_gettop(L) > 1) {
7049 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007050 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007051 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007052 offset += output;
Aurelien DARRAGONd7c71b02022-09-28 15:52:18 +02007053 if (offset > output + input) {
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007054 lua_pushfstring(L, "offset out of range.");
7055 WILL_LJMP(lua_error(L));
7056 }
7057 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007058
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007059 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00007060 if (lua_gettop(L) == 3) {
7061 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007062 if (!len)
7063 goto end;
7064 if (len == -1)
7065 len = output + input - offset;
7066 if (len < 0 || offset + len > output + input) {
7067 lua_pushfstring(L, "length out of range.");
7068 WILL_LJMP(lua_error(L));
7069 }
7070 }
7071
7072 _hlua_http_msg_delete(msg, filter, offset, len);
7073
7074 end:
7075 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007076 return 1;
7077}
7078
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05007079/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007080 * all remaining data are removed, accordingly to the filter context. It returns
7081 * the amount of data written or -1 if nothing was copied. Unlike the channel
7082 * function used to replace data, this one can only be called inside a filter,
7083 * from http_payload callback. So it cannot yield. An exception is returned if
7084 * it is called from another callback.
7085 */
7086__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007087{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007088 struct http_msg *msg;
7089 struct filter *filter;
7090 struct htx *htx;
7091 const char *str;
7092 size_t input, output, sz;
7093 int offset, len;
7094 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02007095
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007096 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
7097 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
7098 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7099
7100 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007101 WILL_LJMP(lua_error(L));
7102
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007103 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7104 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
7105 if (!filter || !hlua_filter_from_payload(filter))
7106 WILL_LJMP(lua_error(L));
7107
7108 offset = output;
7109 if (lua_gettop(L) > 2) {
7110 offset = MAY_LJMP(luaL_checkinteger(L, 3));
7111 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02007112 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007113 offset += output;
7114 if (offset < output || offset > input + output) {
7115 lua_pushfstring(L, "offset out of range.");
7116 WILL_LJMP(lua_error(L));
7117 }
7118 }
7119
7120 len = output + input - offset;
7121 if (lua_gettop(L) == 4) {
7122 len = MAY_LJMP(luaL_checkinteger(L, 4));
7123 if (!len)
7124 goto set;
7125 if (len == -1)
7126 len = output + input - offset;
7127 if (len < 0 || offset + len > output + input) {
7128 lua_pushfstring(L, "length out of range.");
7129 WILL_LJMP(lua_error(L));
7130 }
7131 }
7132
7133 set:
7134 /* Be sure we can copied the string once input data will be removed. */
7135 htx = htx_from_buf(&msg->chn->buf);
7136 if (sz > htx_free_data_space(htx) + len)
7137 lua_pushinteger(L, -1);
7138 else {
7139 _hlua_http_msg_delete(msg, filter, offset, len);
7140 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7141 lua_pushinteger(L, ret);
7142 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007143 return 1;
7144}
7145
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007146/* Prepends data into an HTTP message and forward it, from the filter point of
7147 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
7148 * the channel function used to send data, this one can only be called inside a
7149 * filter, from http_payload callback. So it cannot yield. An exception is
7150 * returned if it is called from another callback.
7151 */
7152__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007153{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007154 struct http_msg *msg;
7155 struct filter *filter;
7156 struct htx *htx;
7157 const char *str;
7158 size_t offset, len, sz;
7159 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007160
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007161 MAY_LJMP(check_args(L, 2, "send"));
7162 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7163
7164 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007165 WILL_LJMP(lua_error(L));
7166
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007167 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
7168 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7169 if (!filter || !hlua_filter_from_payload(filter))
7170 WILL_LJMP(lua_error(L));
7171
7172 /* Return an error if the channel's output is closed */
7173 if (unlikely(channel_output_closed(msg->chn))) {
7174 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007175 return 1;
7176 }
7177
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007178 htx = htx_from_buf(&msg->chn->buf);
7179 if (sz > htx_free_data_space(htx)) {
7180 lua_pushinteger(L, -1);
7181 return 1;
7182 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007183
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007184 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
7185 if (ret > 0) {
7186 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7187
7188 FLT_OFF(filter, msg->chn) += ret;
7189 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7190 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7191 }
7192
7193 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007194 return 1;
7195}
7196
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007197/* Forwards a given amount of bytes. It return -1 if the channel's output is
7198 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
7199 * channel function used to forward data, this one can only be called inside a
7200 * filter, from http_payload callback. So it cannot yield. An exception is
7201 * returned if it is called from another callback. All other functions deal with
7202 * DATA block, this one not.
7203*/
7204__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007205{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007206 struct http_msg *msg;
7207 struct filter *filter;
7208 size_t offset, len;
7209 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007210
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007211 MAY_LJMP(check_args(L, 2, "forward"));
7212 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7213
7214 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007215 WILL_LJMP(lua_error(L));
7216
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007217 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
7218 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
7219 if (!filter || !hlua_filter_from_payload(filter))
7220 WILL_LJMP(lua_error(L));
7221
7222 /* Nothing to do, just return */
7223 if (!fwd)
7224 goto end;
7225
7226 /* Return an error if the channel's output is closed */
7227 if (unlikely(channel_output_closed(msg->chn))) {
7228 ret = -1;
7229 goto end;
7230 }
7231
7232 ret = fwd;
7233 if (ret > len)
7234 ret = len;
7235
7236 if (ret) {
7237 struct hlua_flt_ctx *flt_ctx = filter->ctx;
7238
7239 FLT_OFF(filter, msg->chn) += ret;
7240 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
7241 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
7242 }
7243
7244 end:
7245 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007246 return 1;
7247}
7248
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007249/* Set EOM flag on the HTX message.
7250 *
7251 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7252 * really know how to do without this feature.
7253 */
7254__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007255{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007256 struct http_msg *msg;
7257 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007258
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007259 MAY_LJMP(check_args(L, 1, "set_eom"));
7260 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7261 htx = htxbuf(&msg->chn->buf);
7262 htx->flags |= HTX_FL_EOM;
7263 return 0;
7264}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02007265
Christopher Fauletdf97ac42020-02-26 16:57:19 +01007266/* Unset EOM flag on the HTX message.
7267 *
7268 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
7269 * really know how to do without this feature.
7270 */
7271__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
7272{
7273 struct http_msg *msg;
7274 struct htx *htx;
7275
7276 MAY_LJMP(check_args(L, 1, "set_eom"));
7277 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
7278 htx = htxbuf(&msg->chn->buf);
7279 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007280 return 0;
7281}
7282
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007283/*
7284 *
7285 *
William Lallemand3956c4e2021-09-21 16:25:15 +02007286 * Class HTTPClient
7287 *
7288 *
7289 */
7290__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
7291{
7292 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
7293}
7294
William Lallemandf77f1de2021-09-28 19:10:38 +02007295
7296/* stops the httpclient and ask it to kill itself */
7297__LJMP static int hlua_httpclient_gc(lua_State *L)
7298{
7299 struct hlua_httpclient *hlua_hc;
7300
7301 MAY_LJMP(check_args(L, 1, "__gc"));
7302
7303 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
7304
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007305 if (MT_LIST_DELETE(&hlua_hc->by_hlua)) {
7306 /* we won the race against hlua_httpclient_destroy_all() */
William Lallemandbb581422022-10-20 10:57:28 +02007307 httpclient_stop_and_destroy(hlua_hc->hc);
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007308 hlua_hc->hc = NULL;
7309 }
William Lallemandf77f1de2021-09-28 19:10:38 +02007310
7311 return 0;
7312}
7313
7314
William Lallemand3956c4e2021-09-21 16:25:15 +02007315__LJMP static int hlua_httpclient_new(lua_State *L)
7316{
7317 struct hlua_httpclient *hlua_hc;
7318 struct hlua *hlua;
7319
7320 /* Get hlua struct, or NULL if we execute from main lua state */
7321 hlua = hlua_gethlua(L);
7322 if (!hlua)
7323 return 0;
7324
7325 /* Check stack size. */
7326 if (!lua_checkstack(L, 3)) {
7327 hlua_pusherror(L, "httpclient: full stack");
7328 goto err;
7329 }
7330 /* Create the object: obj[0] = userdata. */
7331 lua_newtable(L);
7332 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
7333 lua_rawseti(L, -2, 0);
7334 memset(hlua_hc, 0, sizeof(*hlua_hc));
7335
7336 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7337 if (!hlua_hc->hc)
7338 goto err;
7339
Aurelien DARRAGON3ffbf382023-02-09 17:02:57 +01007340 MT_LIST_APPEND(&hlua->hc_list, &hlua_hc->by_hlua);
William Lallemandbb581422022-10-20 10:57:28 +02007341
William Lallemand3956c4e2021-09-21 16:25:15 +02007342 /* Pop a class stream metatable and affect it to the userdata. */
7343 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7344 lua_setmetatable(L, -2);
7345
7346 return 1;
7347
7348 err:
7349 WILL_LJMP(lua_error(L));
7350 return 0;
7351}
7352
7353
7354/*
7355 * Callback of the httpclient, this callback wakes the lua task up, once the
7356 * httpclient receives some data
7357 *
7358 */
7359
William Lallemandbd5739e2021-10-28 15:41:38 +02007360static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007361{
7362 struct hlua *hlua = hc->caller;
7363
7364 if (!hlua || !hlua->task)
7365 return;
7366
7367 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7368}
7369
7370/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007371 * Fill the lua stack with headers from the httpclient response
7372 * This works the same way as the hlua_http_get_headers() function
7373 */
7374__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7375{
7376 struct http_hdr *hdr;
7377
7378 lua_newtable(L);
7379
William Lallemandef574b22021-10-05 16:19:31 +02007380 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007381 struct ist n, v;
7382 int len;
7383
7384 n = hdr->n;
7385 v = hdr->v;
7386
7387 /* Check for existing entry:
7388 * assume that the table is on the top of the stack, and
7389 * push the key in the stack, the function lua_gettable()
7390 * perform the lookup.
7391 */
7392
7393 lua_pushlstring(L, n.ptr, n.len);
7394 lua_gettable(L, -2);
7395
7396 switch (lua_type(L, -1)) {
7397 case LUA_TNIL:
7398 /* Table not found, create it. */
7399 lua_pop(L, 1); /* remove the nil value. */
7400 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7401 lua_newtable(L); /* create and push empty table. */
7402 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7403 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7404 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7405 break;
7406
7407 case LUA_TTABLE:
7408 /* Entry found: push the value in the table. */
7409 len = lua_rawlen(L, -1);
7410 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7411 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7412 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7413 break;
7414
7415 default:
7416 /* Other cases are errors. */
7417 hlua_pusherror(L, "internal error during the parsing of headers.");
7418 WILL_LJMP(lua_error(L));
7419 }
7420 }
7421 return 1;
7422}
7423
7424/*
William Lallemand746e6f32021-10-06 10:57:44 +02007425 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7426 *
7427 * Caller must free the result
7428 */
7429struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7430{
7431 struct http_hdr hdrs[global.tune.max_http_hdr];
7432 struct http_hdr *result = NULL;
7433 uint32_t hdr_num = 0;
7434
7435 lua_pushnil(L);
7436 while (lua_next(L, -2) != 0) {
7437 struct ist name, value;
7438 const char *n, *v;
7439 size_t nlen, vlen;
7440
7441 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7442 /* Skip element if the key is not a string or if the value is not a table */
7443 goto next_hdr;
7444 }
7445
7446 n = lua_tolstring(L, -2, &nlen);
7447 name = ist2(n, nlen);
7448
7449 /* Loop on header's values */
7450 lua_pushnil(L);
7451 while (lua_next(L, -2)) {
7452 if (!lua_isstring(L, -1)) {
7453 /* Skip the value if it is not a string */
7454 goto next_value;
7455 }
7456
7457 v = lua_tolstring(L, -1, &vlen);
7458 value = ist2(v, vlen);
7459 name = ist2(n, nlen);
7460
7461 hdrs[hdr_num].n = istdup(name);
7462 hdrs[hdr_num].v = istdup(value);
7463
7464 hdr_num++;
7465
7466 next_value:
7467 lua_pop(L, 1);
7468 }
7469
7470 next_hdr:
7471 lua_pop(L, 1);
7472
7473 }
7474
7475 if (hdr_num) {
7476 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007477 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007478 if (!result)
7479 goto skip_headers;
7480 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7481
7482 result[hdr_num].n = IST_NULL;
7483 result[hdr_num].v = IST_NULL;
7484 }
7485
7486skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007487
7488 return result;
7489}
7490
7491
William Lallemandbd5739e2021-10-28 15:41:38 +02007492/*
7493 * For each yield, checks if there is some data in the httpclient and push them
7494 * in the lua buffer, once the httpclient finished its job, push the result on
7495 * the stack
7496 */
7497__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7498{
7499 struct buffer *tr;
7500 int res;
7501 struct hlua *hlua = hlua_gethlua(L);
7502 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7503
7504
7505 tr = get_trash_chunk();
7506
7507 res = httpclient_res_xfer(hlua_hc->hc, tr);
7508 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7509
7510 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7511
7512 luaL_pushresult(&hlua_hc->b);
7513 lua_settable(L, -3);
7514
7515 lua_pushstring(L, "status");
7516 lua_pushinteger(L, hlua_hc->hc->res.status);
7517 lua_settable(L, -3);
7518
7519
7520 lua_pushstring(L, "reason");
7521 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7522 lua_settable(L, -3);
7523
7524 lua_pushstring(L, "headers");
7525 hlua_httpclient_get_headers(L, hlua_hc);
7526 lua_settable(L, -3);
7527
7528 return 1;
7529 }
7530
7531 if (httpclient_data(hlua_hc->hc))
7532 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7533
7534 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7535
7536 return 0;
7537}
7538
7539/*
7540 * Call this when trying to stream a body during a request
7541 */
7542__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7543{
7544 struct hlua *hlua;
7545 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7546 const char *body_str = NULL;
7547 int ret;
7548 int end = 0;
7549 size_t buf_len;
7550 size_t to_send = 0;
7551
7552 hlua = hlua_gethlua(L);
7553
7554 if (!hlua || !hlua->task)
7555 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7556 "'frontend', 'backend' or 'task'"));
7557
7558 ret = lua_getfield(L, -1, "body");
7559 if (ret != LUA_TSTRING)
7560 goto rcv;
7561
7562 body_str = lua_tolstring(L, -1, &buf_len);
7563 lua_pop(L, 1);
7564
Christopher Fauletfc591292022-01-12 14:46:03 +01007565 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007566
7567 if ((hlua_hc->sent + to_send) >= buf_len)
7568 end = 1;
7569
7570 /* the end flag is always set since we are using the whole remaining size */
7571 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7572
7573 if (buf_len > hlua_hc->sent) {
7574 /* still need to process the buffer */
7575 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7576 } else {
7577 goto rcv;
7578 /* we sent the whole request buffer we can recv */
7579 }
7580 return 0;
7581
7582rcv:
7583
7584 /* we return a "res" object */
7585 lua_newtable(L);
7586
William Lallemandbd5739e2021-10-28 15:41:38 +02007587 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007588 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007589
William Lallemand933fe392021-11-04 09:45:58 +01007590 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007591 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7592
7593 return 1;
7594}
William Lallemand746e6f32021-10-06 10:57:44 +02007595
William Lallemand3956c4e2021-09-21 16:25:15 +02007596/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007597 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007598 */
7599
William Lallemanddc2cc902021-10-26 11:43:26 +02007600__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007601{
7602 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007603 struct http_hdr *hdrs = NULL;
7604 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007605 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007606 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007607 const char *body_str = NULL;
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007608 size_t buf_len = 0;
William Lallemand746e6f32021-10-06 10:57:44 +02007609 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007610
7611 hlua = hlua_gethlua(L);
7612
7613 if (!hlua || !hlua->task)
7614 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7615 "'frontend', 'backend' or 'task'"));
7616
William Lallemand746e6f32021-10-06 10:57:44 +02007617 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7618 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7619
William Lallemand4f4f2b72022-02-17 20:00:23 +01007620 hlua_hc = hlua_checkhttpclient(L, 1);
7621
William Lallemand7177a952022-03-03 15:33:12 +01007622 lua_pushnil(L); /* first key */
7623 while (lua_next(L, 2)) {
7624 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7625 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7626 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007627
William Lallemand7177a952022-03-03 15:33:12 +01007628 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7629 if (lua_type(L, -1) != LUA_TSTRING)
7630 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7631 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007632
William Lallemand7177a952022-03-03 15:33:12 +01007633 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7634 if (lua_type(L, -1) != LUA_TNUMBER)
7635 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7636 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007637
William Lallemand7177a952022-03-03 15:33:12 +01007638 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7639 if (lua_type(L, -1) != LUA_TTABLE)
7640 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7641 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007642
William Lallemand7177a952022-03-03 15:33:12 +01007643 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7644 if (lua_type(L, -1) != LUA_TSTRING)
7645 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7646 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007647
William Lallemand7177a952022-03-03 15:33:12 +01007648 } else {
7649 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7650 }
7651 /* removes 'value'; keeps 'key' for next iteration */
7652 lua_pop(L, 1);
7653 }
William Lallemanddec25c32021-10-25 19:48:37 +02007654
William Lallemand746e6f32021-10-06 10:57:44 +02007655 if (!url_str) {
7656 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7657 return 0;
7658 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007659
William Lallemand10a37362022-03-02 16:18:26 +01007660 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007661
Aurelien DARRAGON03564072023-02-09 15:26:25 +01007662 istfree(&hlua_hc->hc->req.url);
William Lallemand3956c4e2021-09-21 16:25:15 +02007663 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007664 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007665
7666 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007667 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7668 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7669 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007670 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007671
William Lallemandbd5739e2021-10-28 15:41:38 +02007672 /* a body is available, it will use the request callback */
Christopher Faulet380ae9c2022-10-14 14:57:04 +02007673 if (body_str && buf_len) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007674 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7675 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007676
William Lallemandbd5739e2021-10-28 15:41:38 +02007677 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007678
William Lallemand746e6f32021-10-06 10:57:44 +02007679 /* free the temporary headers array */
7680 hdrs_i = hdrs;
7681 while (hdrs_i && isttest(hdrs_i->n)) {
7682 istfree(&hdrs_i->n);
7683 istfree(&hdrs_i->v);
7684 hdrs_i++;
7685 }
7686 ha_free(&hdrs);
7687
7688
William Lallemand6137a9e2021-10-26 15:01:53 +02007689 if (ret != ERR_NONE) {
7690 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7691 return 0;
7692 }
7693
William Lallemandc2d3db42022-04-26 11:46:13 +02007694 if (!httpclient_start(hlua_hc->hc))
7695 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007696
William Lallemandbd5739e2021-10-28 15:41:38 +02007697 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007698
William Lallemand3956c4e2021-09-21 16:25:15 +02007699 return 0;
7700}
7701
7702/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007703 * Sends an HTTP HEAD request and wait for a response
7704 *
7705 * httpclient:head(url, headers, payload)
7706 */
7707__LJMP static int hlua_httpclient_head(lua_State *L)
7708{
7709 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7710}
7711
7712/*
7713 * Send an HTTP GET request and wait for a response
7714 *
7715 * httpclient:get(url, headers, payload)
7716 */
7717__LJMP static int hlua_httpclient_get(lua_State *L)
7718{
7719 return hlua_httpclient_send(L, HTTP_METH_GET);
7720
7721}
7722
7723/*
7724 * Sends an HTTP PUT request and wait for a response
7725 *
7726 * httpclient:put(url, headers, payload)
7727 */
7728__LJMP static int hlua_httpclient_put(lua_State *L)
7729{
7730 return hlua_httpclient_send(L, HTTP_METH_PUT);
7731}
7732
7733/*
7734 * Send an HTTP POST request and wait for a response
7735 *
7736 * httpclient:post(url, headers, payload)
7737 */
7738__LJMP static int hlua_httpclient_post(lua_State *L)
7739{
7740 return hlua_httpclient_send(L, HTTP_METH_POST);
7741}
7742
7743
7744/*
7745 * Sends an HTTP DELETE request and wait for a response
7746 *
7747 * httpclient:delete(url, headers, payload)
7748 */
7749__LJMP static int hlua_httpclient_delete(lua_State *L)
7750{
7751 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7752}
7753
7754/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007755 *
7756 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007757 * Class TXN
7758 *
7759 *
7760 */
7761
7762/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007763 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007764 */
7765__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7766{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007767 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007768}
7769
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007770__LJMP static int hlua_set_var(lua_State *L)
7771{
7772 struct hlua_txn *htxn;
7773 const char *name;
7774 size_t len;
7775 struct sample smp;
7776
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007777 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7778 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007779
7780 /* It is useles to retrieve the stream, but this function
7781 * runs only in a stream context.
7782 */
7783 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7784 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7785
7786 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007787 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007788 hlua_lua2smp(L, 3, &smp);
7789
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02007790 /* Store the sample in a variable. We don't need to dup the smp, vars API
7791 * already takes care of duplicating dynamic var data.
7792 */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007793 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007794
7795 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7796 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7797 else
7798 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7799
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007800 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007801}
7802
Christopher Faulet85d79c92016-11-09 16:54:56 +01007803__LJMP static int hlua_unset_var(lua_State *L)
7804{
7805 struct hlua_txn *htxn;
7806 const char *name;
7807 size_t len;
7808 struct sample smp;
7809
7810 MAY_LJMP(check_args(L, 2, "unset_var"));
7811
7812 /* It is useles to retrieve the stream, but this function
7813 * runs only in a stream context.
7814 */
7815 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7816 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7817
7818 /* Unset the variable. */
7819 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007820 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7821 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007822}
7823
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007824__LJMP static int hlua_get_var(lua_State *L)
7825{
7826 struct hlua_txn *htxn;
7827 const char *name;
7828 size_t len;
7829 struct sample smp;
7830
7831 MAY_LJMP(check_args(L, 2, "get_var"));
7832
7833 /* It is useles to retrieve the stream, but this function
7834 * runs only in a stream context.
7835 */
7836 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7837 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7838
Willy Tarreau7560dd42016-03-10 16:28:58 +01007839 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007840 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007841 lua_pushnil(L);
7842 return 1;
7843 }
7844
Aurelien DARRAGON41217722023-05-17 10:44:47 +02007845 return MAY_LJMP(hlua_smp2lua(L, &smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007846}
7847
Willy Tarreau59551662015-03-10 14:23:13 +01007848__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007849{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007850 struct hlua *hlua;
7851
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007852 MAY_LJMP(check_args(L, 2, "set_priv"));
7853
Willy Tarreau87b09662015-04-03 00:22:06 +02007854 /* It is useles to retrieve the stream, but this function
7855 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007856 */
7857 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007858
7859 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007860 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007861 if (!hlua)
7862 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007863
7864 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007865 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007866
7867 /* Get and store new value. */
7868 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7869 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7870
7871 return 0;
7872}
7873
Willy Tarreau59551662015-03-10 14:23:13 +01007874__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007875{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007876 struct hlua *hlua;
7877
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007878 MAY_LJMP(check_args(L, 1, "get_priv"));
7879
Willy Tarreau87b09662015-04-03 00:22:06 +02007880 /* It is useles to retrieve the stream, but this function
7881 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007882 */
7883 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007884
7885 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007886 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007887 if (!hlua) {
7888 lua_pushnil(L);
7889 return 1;
7890 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007891
7892 /* Push configuration index in the stack. */
7893 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7894
7895 return 1;
7896}
7897
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007898/* Create stack entry containing a class TXN. This function
7899 * return 0 if the stack does not contains free slots,
7900 * otherwise it returns 1.
7901 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007902static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007903{
Willy Tarreaude491382015-04-06 11:04:28 +02007904 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007905
7906 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007907 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007908 return 0;
7909
7910 /* NOTE: The allocation never fails. The failure
7911 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007912 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007913 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007914 /* Create the object: obj[0] = userdata. */
7915 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007916 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007917 lua_rawseti(L, -2, 0);
7918
Willy Tarreaude491382015-04-06 11:04:28 +02007919 htxn->s = s;
7920 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007921 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007922 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007923
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007924 /* Create the "f" field that contains a list of fetches. */
7925 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007926 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007927 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007928 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007929
7930 /* Create the "sf" field that contains a list of stringsafe fetches. */
7931 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007932 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007933 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007934 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007935
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007936 /* Create the "c" field that contains a list of converters. */
7937 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007938 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007939 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007940 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007941
7942 /* Create the "sc" field that contains a list of stringsafe converters. */
7943 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007944 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007945 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007946 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007947
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007948 /* Create the "req" field that contains the request channel object. */
7949 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007950 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007951 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007952 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007953
7954 /* Create the "res" field that contains the response channel object. */
7955 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007956 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007957 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007958 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007959
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007960 /* Creates the HTTP object is the current proxy allows http. */
7961 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007962 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007963 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007964 return 0;
7965 }
7966 else
7967 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007968 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007969
Christopher Faulet78c35472020-02-26 17:14:08 +01007970 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7971 /* HTTPMessage object are created when a lua TXN is created from
7972 * a filter context only
7973 */
7974
7975 /* Creates the HTTP-Request object is the current proxy allows http. */
7976 lua_pushstring(L, "http_req");
7977 if (p->mode == PR_MODE_HTTP) {
7978 if (!hlua_http_msg_new(L, &s->txn->req))
7979 return 0;
7980 }
7981 else
7982 lua_pushnil(L);
7983 lua_rawset(L, -3);
7984
7985 /* Creates the HTTP-Response object is the current proxy allows http. */
7986 lua_pushstring(L, "http_res");
7987 if (p->mode == PR_MODE_HTTP) {
7988 if (!hlua_http_msg_new(L, &s->txn->rsp))
7989 return 0;
7990 }
7991 else
7992 lua_pushnil(L);
7993 lua_rawset(L, -3);
7994 }
7995
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007996 /* Pop a class sesison metatable and affect it to the userdata. */
7997 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7998 lua_setmetatable(L, -2);
7999
8000 return 1;
8001}
8002
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008003__LJMP static int hlua_txn_deflog(lua_State *L)
8004{
8005 const char *msg;
8006 struct hlua_txn *htxn;
8007
8008 MAY_LJMP(check_args(L, 2, "deflog"));
8009 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8010 msg = MAY_LJMP(luaL_checkstring(L, 2));
8011
8012 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
8013 return 0;
8014}
8015
8016__LJMP static int hlua_txn_log(lua_State *L)
8017{
8018 int level;
8019 const char *msg;
8020 struct hlua_txn *htxn;
8021
8022 MAY_LJMP(check_args(L, 3, "log"));
8023 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8024 level = MAY_LJMP(luaL_checkinteger(L, 2));
8025 msg = MAY_LJMP(luaL_checkstring(L, 3));
8026
8027 if (level < 0 || level >= NB_LOG_LEVELS)
8028 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8029
8030 hlua_sendlog(htxn->s->be, level, msg);
8031 return 0;
8032}
8033
8034__LJMP static int hlua_txn_log_debug(lua_State *L)
8035{
8036 const char *msg;
8037 struct hlua_txn *htxn;
8038
8039 MAY_LJMP(check_args(L, 2, "Debug"));
8040 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8041 msg = MAY_LJMP(luaL_checkstring(L, 2));
8042 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
8043 return 0;
8044}
8045
8046__LJMP static int hlua_txn_log_info(lua_State *L)
8047{
8048 const char *msg;
8049 struct hlua_txn *htxn;
8050
8051 MAY_LJMP(check_args(L, 2, "Info"));
8052 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8053 msg = MAY_LJMP(luaL_checkstring(L, 2));
8054 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
8055 return 0;
8056}
8057
8058__LJMP static int hlua_txn_log_warning(lua_State *L)
8059{
8060 const char *msg;
8061 struct hlua_txn *htxn;
8062
8063 MAY_LJMP(check_args(L, 2, "Warning"));
8064 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8065 msg = MAY_LJMP(luaL_checkstring(L, 2));
8066 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
8067 return 0;
8068}
8069
8070__LJMP static int hlua_txn_log_alert(lua_State *L)
8071{
8072 const char *msg;
8073 struct hlua_txn *htxn;
8074
8075 MAY_LJMP(check_args(L, 2, "Alert"));
8076 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8077 msg = MAY_LJMP(luaL_checkstring(L, 2));
8078 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
8079 return 0;
8080}
8081
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008082__LJMP static int hlua_txn_set_loglevel(lua_State *L)
8083{
8084 struct hlua_txn *htxn;
8085 int ll;
8086
8087 MAY_LJMP(check_args(L, 2, "set_loglevel"));
8088 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8089 ll = MAY_LJMP(luaL_checkinteger(L, 2));
8090
8091 if (ll < 0 || ll > 7)
8092 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
8093
8094 htxn->s->logs.level = ll;
8095 return 0;
8096}
8097
8098__LJMP static int hlua_txn_set_tos(lua_State *L)
8099{
8100 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008101 int tos;
8102
8103 MAY_LJMP(check_args(L, 2, "set_tos"));
8104 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8105 tos = MAY_LJMP(luaL_checkinteger(L, 2));
8106
Willy Tarreau1a18b542018-12-11 16:37:42 +01008107 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008108 return 0;
8109}
8110
8111__LJMP static int hlua_txn_set_mark(lua_State *L)
8112{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008113 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008114 int mark;
8115
8116 MAY_LJMP(check_args(L, 2, "set_mark"));
8117 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8118 mark = MAY_LJMP(luaL_checkinteger(L, 2));
8119
Lukas Tribus579e3e32019-08-11 18:03:45 +02008120 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01008121 return 0;
8122}
8123
Patrick Hemmer268a7072018-05-11 12:52:31 -04008124__LJMP static int hlua_txn_set_priority_class(lua_State *L)
8125{
8126 struct hlua_txn *htxn;
8127
8128 MAY_LJMP(check_args(L, 2, "set_priority_class"));
8129 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8130 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
8131 return 0;
8132}
8133
8134__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
8135{
8136 struct hlua_txn *htxn;
8137
8138 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
8139 htxn = MAY_LJMP(hlua_checktxn(L, 1));
8140 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
8141 return 0;
8142}
8143
Christopher Faulet700d9e82020-01-31 12:21:52 +01008144/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008145 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01008146 * message and terminate the transaction. It returns 1 on success and 0 on
8147 * error. The Reply must be on top of the stack.
8148 */
8149__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
8150{
8151 struct htx *htx;
8152 struct htx_sl *sl;
8153 struct h1m h1m;
8154 const char *status, *reason, *body;
8155 size_t status_len, reason_len, body_len;
8156 int ret, code, flags;
8157
8158 code = 200;
8159 status = "200";
8160 status_len = 3;
8161 ret = lua_getfield(L, -1, "status");
8162 if (ret == LUA_TNUMBER) {
8163 code = lua_tointeger(L, -1);
8164 status = lua_tolstring(L, -1, &status_len);
8165 }
8166 lua_pop(L, 1);
8167
8168 reason = http_get_reason(code);
8169 reason_len = strlen(reason);
8170 ret = lua_getfield(L, -1, "reason");
8171 if (ret == LUA_TSTRING)
8172 reason = lua_tolstring(L, -1, &reason_len);
8173 lua_pop(L, 1);
8174
8175 body = NULL;
8176 body_len = 0;
8177 ret = lua_getfield(L, -1, "body");
8178 if (ret == LUA_TSTRING)
8179 body = lua_tolstring(L, -1, &body_len);
8180 lua_pop(L, 1);
8181
8182 /* Prepare the response before inserting the headers */
8183 h1m_init_res(&h1m);
8184 htx = htx_from_buf(&s->res.buf);
8185 channel_htx_truncate(&s->res, htx);
8186 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
8187 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
8188 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
8189 ist2(status, status_len), ist2(reason, reason_len));
8190 }
8191 else {
8192 flags = HTX_SL_F_IS_RESP;
8193 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
8194 ist2(status, status_len), ist2(reason, reason_len));
8195 }
8196 if (!sl)
8197 goto fail;
8198 sl->info.res.status = code;
8199
8200 /* Push in the stack the "headers" entry. */
8201 ret = lua_getfield(L, -1, "headers");
8202 if (ret != LUA_TTABLE)
8203 goto skip_headers;
8204
8205 lua_pushnil(L);
8206 while (lua_next(L, -2) != 0) {
8207 struct ist name, value;
8208 const char *n, *v;
8209 size_t nlen, vlen;
8210
8211 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
8212 /* Skip element if the key is not a string or if the value is not a table */
8213 goto next_hdr;
8214 }
8215
8216 n = lua_tolstring(L, -2, &nlen);
8217 name = ist2(n, nlen);
8218 if (isteqi(name, ist("content-length"))) {
8219 /* Always skip content-length header. It will be added
8220 * later with the correct len
8221 */
8222 goto next_hdr;
8223 }
8224
8225 /* Loop on header's values */
8226 lua_pushnil(L);
8227 while (lua_next(L, -2)) {
8228 if (!lua_isstring(L, -1)) {
8229 /* Skip the value if it is not a string */
8230 goto next_value;
8231 }
8232
8233 v = lua_tolstring(L, -1, &vlen);
8234 value = ist2(v, vlen);
8235
8236 if (isteqi(name, ist("transfer-encoding")))
8237 h1_parse_xfer_enc_header(&h1m, value);
8238 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
8239 goto fail;
8240
8241 next_value:
8242 lua_pop(L, 1);
8243 }
8244
8245 next_hdr:
8246 lua_pop(L, 1);
8247 }
8248 skip_headers:
8249 lua_pop(L, 1);
8250
8251 /* Update h1m flags: CLEN is set if CHNK is not present */
8252 if (!(h1m.flags & H1_MF_CHNK)) {
8253 const char *clen = ultoa(body_len);
8254
8255 h1m.flags |= H1_MF_CLEN;
8256 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
8257 goto fail;
8258 }
8259 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
8260 h1m.flags |= H1_MF_XFER_LEN;
8261
8262 /* Update HTX start-line flags */
8263 if (h1m.flags & H1_MF_XFER_ENC)
8264 flags |= HTX_SL_F_XFER_ENC;
8265 if (h1m.flags & H1_MF_XFER_LEN) {
8266 flags |= HTX_SL_F_XFER_LEN;
8267 if (h1m.flags & H1_MF_CHNK)
8268 flags |= HTX_SL_F_CHNK;
8269 else if (h1m.flags & H1_MF_CLEN)
8270 flags |= HTX_SL_F_CLEN;
8271 if (h1m.body_len == 0)
8272 flags |= HTX_SL_F_BODYLESS;
8273 }
8274 sl->flags |= flags;
8275
8276
8277 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008278 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01008279 goto fail;
8280
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01008281 htx->flags |= HTX_FL_EOM;
8282
Christopher Faulet700d9e82020-01-31 12:21:52 +01008283 /* Now, forward the response and terminate the transaction */
8284 s->txn->status = code;
8285 htx_to_buf(htx, &s->res.buf);
8286 if (!http_forward_proxy_resp(s, 1))
8287 goto fail;
8288
8289 return 1;
8290
8291 fail:
8292 channel_htx_truncate(&s->res, htx);
8293 return 0;
8294}
8295
8296/* Terminate a transaction if called from a lua action. For TCP streams,
8297 * processing is just aborted. Nothing is returned to the client and all
8298 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
8299 * is forwarded to the client before terminating the transaction. On success,
8300 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
8301 * with ACT_RET_ERR code. If this function is not called from a lua action, it
8302 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008303 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008304__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008305{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008306 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008307 struct stream *s;
8308 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008309
Willy Tarreaub2ccb562015-04-06 11:11:15 +02008310 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008311
Christopher Faulet700d9e82020-01-31 12:21:52 +01008312 /* If the flags NOTERM is set, we cannot terminate the session, so we
8313 * just end the execution of the current lua code. */
8314 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008315 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02008316
Christopher Faulet700d9e82020-01-31 12:21:52 +01008317 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008318 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008319 struct channel *req = &s->req;
8320 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01008321
Christopher Faulet700d9e82020-01-31 12:21:52 +01008322 channel_auto_read(req);
8323 channel_abort(req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008324 channel_erase(req);
8325
Christopher Faulet700d9e82020-01-31 12:21:52 +01008326 channel_auto_read(res);
8327 channel_auto_close(res);
Christopher Faulet12762f02023-04-13 15:40:10 +02008328 sc_schedule_abort(s->scb);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008329
8330 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
8331 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008332 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02008333
Christopher Faulet700d9e82020-01-31 12:21:52 +01008334 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
8335 /* No reply or invalid reply */
8336 s->txn->status = 0;
8337 http_reply_and_close(s, 0, NULL);
8338 }
8339 else {
8340 /* Remove extra args to have the reply on top of the stack */
8341 if (lua_gettop(L) > 2)
8342 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008343
Christopher Faulet700d9e82020-01-31 12:21:52 +01008344 if (!hlua_txn_forward_reply(L, s)) {
8345 if (!(s->flags & SF_ERR_MASK))
8346 s->flags |= SF_ERR_PRXCOND;
8347 lua_pushinteger(L, ACT_RET_ERR);
8348 WILL_LJMP(hlua_done(L));
8349 return 0; /* Never reached */
8350 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008351 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008352
Christopher Faulet700d9e82020-01-31 12:21:52 +01008353 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8354 if (htxn->dir == SMP_OPT_DIR_REQ) {
8355 /* let's log the request time */
Willy Tarreau69530f52023-04-28 09:16:15 +02008356 s->logs.request_ts = now_ns;
Christopher Faulet700d9e82020-01-31 12:21:52 +01008357 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008358 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008359 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008360
Christopher Faulet700d9e82020-01-31 12:21:52 +01008361 done:
8362 if (!(s->flags & SF_ERR_MASK))
8363 s->flags |= SF_ERR_LOCAL;
8364 if (!(s->flags & SF_FINST_MASK))
8365 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008366
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008367 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8368 lua_pushinteger(L, -1);
8369 else
8370 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008371 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008372 return 0;
8373}
8374
Christopher Faulet700d9e82020-01-31 12:21:52 +01008375/*
8376 *
8377 *
8378 * Class REPLY
8379 *
8380 *
8381 */
8382
8383/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8384 * free slots, the function fails and returns 0;
8385 */
8386static int hlua_txn_reply_new(lua_State *L)
8387{
8388 struct hlua_txn *htxn;
8389 const char *reason, *body = NULL;
8390 int ret, status;
8391
8392 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008393 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008394 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8395 WILL_LJMP(lua_error(L));
8396 }
8397
8398 /* Default value */
8399 status = 200;
8400 reason = http_get_reason(status);
8401
8402 if (lua_istable(L, 2)) {
8403 /* load status and reason from the table argument at index 2 */
8404 ret = lua_getfield(L, 2, "status");
8405 if (ret == LUA_TNIL)
8406 goto reason;
8407 else if (ret != LUA_TNUMBER) {
8408 /* invalid status: ignore the reason */
8409 goto body;
8410 }
8411 status = lua_tointeger(L, -1);
8412
8413 reason:
8414 lua_pop(L, 1); /* restore the stack: remove status */
8415 ret = lua_getfield(L, 2, "reason");
8416 if (ret == LUA_TSTRING)
8417 reason = lua_tostring(L, -1);
8418
8419 body:
8420 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8421 ret = lua_getfield(L, 2, "body");
8422 if (ret == LUA_TSTRING)
8423 body = lua_tostring(L, -1);
8424 lua_pop(L, 1); /* restore the stack: remove body */
8425 }
8426
8427 /* Create the Reply table */
8428 lua_newtable(L);
8429
8430 /* Add status element */
8431 lua_pushstring(L, "status");
8432 lua_pushinteger(L, status);
8433 lua_settable(L, -3);
8434
8435 /* Add reason element */
8436 reason = http_get_reason(status);
8437 lua_pushstring(L, "reason");
8438 lua_pushstring(L, reason);
8439 lua_settable(L, -3);
8440
8441 /* Add body element, nil if undefined */
8442 lua_pushstring(L, "body");
8443 if (body)
8444 lua_pushstring(L, body);
8445 else
8446 lua_pushnil(L);
8447 lua_settable(L, -3);
8448
8449 /* Add headers element */
8450 lua_pushstring(L, "headers");
8451 lua_newtable(L);
8452
8453 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8454 if (lua_istable(L, 2)) {
8455 /* load headers from the table argument at index 2. If it is a table, copy it. */
8456 ret = lua_getfield(L, 2, "headers");
8457 if (ret == LUA_TTABLE) {
8458 /* stack: [ ... <headers:table>, <table> ] */
8459 lua_pushnil(L);
8460 while (lua_next(L, -2) != 0) {
8461 /* stack: [ ... <headers:table>, <table>, k, v] */
8462 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8463 /* invalid value type, skip it */
8464 lua_pop(L, 1);
8465 continue;
8466 }
8467
8468
8469 /* Duplicate the key and swap it with the value. */
8470 lua_pushvalue(L, -2);
8471 lua_insert(L, -2);
8472 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8473
8474 lua_newtable(L);
8475 lua_insert(L, -2);
8476 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8477
8478 if (lua_isstring(L, -1)) {
8479 /* push the value in the inner table */
8480 lua_rawseti(L, -2, 1);
8481 }
8482 else { /* table */
8483 lua_pushnil(L);
8484 while (lua_next(L, -2) != 0) {
8485 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8486 if (!lua_isstring(L, -1)) {
8487 /* invalid value type, skip it*/
8488 lua_pop(L, 1);
8489 continue;
8490 }
8491 /* push the value in the inner table */
8492 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8493 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8494 }
8495 lua_pop(L, 1);
8496 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8497 }
8498
8499 /* push (k,v) on the stack in the headers table:
8500 * stack: [ ... <headers:table>, <table>, k, k, v ]
8501 */
8502 lua_settable(L, -5);
8503 /* stack: [ ... <headers:table>, <table>, k ] */
8504 }
8505 }
8506 lua_pop(L, 1);
8507 }
8508 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8509 lua_settable(L, -3);
8510 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8511
8512 /* Pop a class sesison metatable and affect it to the userdata. */
8513 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8514 lua_setmetatable(L, -2);
8515 return 1;
8516}
8517
8518/* Set the reply status code, and optionally the reason. If no reason is
8519 * provided, the default one corresponding to the status code is used.
8520 */
8521__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8522{
8523 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8524 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8525
8526 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008527 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008528
8529 if (status < 100 || status > 599) {
8530 lua_pushboolean(L, 0);
8531 return 1;
8532 }
8533 if (!reason)
8534 reason = http_get_reason(status);
8535
8536 lua_pushinteger(L, status);
8537 lua_setfield(L, 1, "status");
8538
8539 lua_pushstring(L, reason);
8540 lua_setfield(L, 1, "reason");
8541
8542 lua_pushboolean(L, 1);
8543 return 1;
8544}
8545
8546/* Add a header into the reply object. Each header name is associated to an
8547 * array of values in the "headers" table. If the header name is not found, a
8548 * new entry is created.
8549 */
8550__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8551{
8552 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8553 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8554 int ret;
8555
8556 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008557 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008558
8559 /* Push in the stack the "headers" entry. */
8560 ret = lua_getfield(L, 1, "headers");
8561 if (ret != LUA_TTABLE) {
8562 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8563 WILL_LJMP(lua_error(L));
8564 }
8565
8566 /* check if the header is already registered. If not, register it. */
8567 ret = lua_getfield(L, -1, name);
8568 if (ret == LUA_TNIL) {
8569 /* Entry not found. */
8570 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8571
8572 /* Insert the new header name in the array in the top of the stack.
8573 * It left the new array in the top of the stack.
8574 */
8575 lua_newtable(L);
8576 lua_pushstring(L, name);
8577 lua_pushvalue(L, -2);
8578 lua_settable(L, -4);
8579 }
8580 else if (ret != LUA_TTABLE) {
8581 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8582 WILL_LJMP(lua_error(L));
8583 }
8584
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008585 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008586 * the header value as new entry.
8587 */
8588 lua_pushstring(L, value);
8589 ret = lua_rawlen(L, -2);
8590 lua_rawseti(L, -2, ret + 1);
8591
8592 lua_pushboolean(L, 1);
8593 return 1;
8594}
8595
8596/* Remove all occurrences of a given header name. */
8597__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8598{
8599 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8600 int ret;
8601
8602 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008603 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008604
8605 /* Push in the stack the "headers" entry. */
8606 ret = lua_getfield(L, 1, "headers");
8607 if (ret != LUA_TTABLE) {
8608 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8609 WILL_LJMP(lua_error(L));
8610 }
8611
8612 lua_pushstring(L, name);
8613 lua_pushnil(L);
8614 lua_settable(L, -3);
8615
8616 lua_pushboolean(L, 1);
8617 return 1;
8618}
8619
8620/* Set the reply's body. Overwrite any existing entry. */
8621__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8622{
8623 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8624
8625 /* First argument (self) must be a table */
Aurelien DARRAGONd83d0452022-10-05 11:46:45 +02008626 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
Christopher Faulet700d9e82020-01-31 12:21:52 +01008627
8628 lua_pushstring(L, payload);
8629 lua_setfield(L, 1, "body");
8630
8631 lua_pushboolean(L, 1);
8632 return 1;
8633}
8634
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008635__LJMP static int hlua_log(lua_State *L)
8636{
8637 int level;
8638 const char *msg;
8639
8640 MAY_LJMP(check_args(L, 2, "log"));
8641 level = MAY_LJMP(luaL_checkinteger(L, 1));
8642 msg = MAY_LJMP(luaL_checkstring(L, 2));
8643
8644 if (level < 0 || level >= NB_LOG_LEVELS)
8645 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8646
8647 hlua_sendlog(NULL, level, msg);
8648 return 0;
8649}
8650
8651__LJMP static int hlua_log_debug(lua_State *L)
8652{
8653 const char *msg;
8654
8655 MAY_LJMP(check_args(L, 1, "debug"));
8656 msg = MAY_LJMP(luaL_checkstring(L, 1));
8657 hlua_sendlog(NULL, LOG_DEBUG, msg);
8658 return 0;
8659}
8660
8661__LJMP static int hlua_log_info(lua_State *L)
8662{
8663 const char *msg;
8664
8665 MAY_LJMP(check_args(L, 1, "info"));
8666 msg = MAY_LJMP(luaL_checkstring(L, 1));
8667 hlua_sendlog(NULL, LOG_INFO, msg);
8668 return 0;
8669}
8670
8671__LJMP static int hlua_log_warning(lua_State *L)
8672{
8673 const char *msg;
8674
8675 MAY_LJMP(check_args(L, 1, "warning"));
8676 msg = MAY_LJMP(luaL_checkstring(L, 1));
8677 hlua_sendlog(NULL, LOG_WARNING, msg);
8678 return 0;
8679}
8680
8681__LJMP static int hlua_log_alert(lua_State *L)
8682{
8683 const char *msg;
8684
8685 MAY_LJMP(check_args(L, 1, "alert"));
8686 msg = MAY_LJMP(luaL_checkstring(L, 1));
8687 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008688 return 0;
8689}
8690
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008691__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008692{
8693 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008694 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008695 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008696 return 0;
8697}
8698
8699__LJMP static int hlua_sleep(lua_State *L)
8700{
8701 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008702 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008703
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008704 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008705
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008706 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008707 wakeup_ms = tick_add(now_ms, delay);
8708 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008709
Willy Tarreau9635e032018-10-16 17:52:55 +02008710 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008711 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008712}
8713
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008714__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008715{
8716 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +02008717 int wakeup_ms; // tick value
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008718
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008719 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008720
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008721 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008722 wakeup_ms = tick_add(now_ms, delay);
8723 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008724
Willy Tarreau9635e032018-10-16 17:52:55 +02008725 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008726 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008727}
8728
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008729/* This functionis an LUA binding. it permits to give back
8730 * the hand at the HAProxy scheduler. It is used when the
8731 * LUA processing consumes a lot of time.
8732 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008733__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008734{
8735 return 0;
8736}
8737
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008738__LJMP static int hlua_yield(lua_State *L)
8739{
Willy Tarreau9635e032018-10-16 17:52:55 +02008740 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008741 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008742}
8743
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008744/* This function change the nice of the currently executed
8745 * task. It is used set low or high priority at the current
8746 * task.
8747 */
Willy Tarreau59551662015-03-10 14:23:13 +01008748__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008749{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008750 struct hlua *hlua;
8751 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008752
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008753 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008754 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008755
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008756 /* Get hlua struct, or NULL if we execute from main lua state */
8757 hlua = hlua_gethlua(L);
8758
8759 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008760 if (!hlua || !hlua->task)
8761 return 0;
8762
8763 if (nice < -1024)
8764 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008765 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008766 nice = 1024;
8767
8768 hlua->task->nice = nice;
8769 return 0;
8770}
8771
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +02008772/* safe lua coroutine.create() function:
8773 *
8774 * This is a simple wrapper for coroutine.create() that
8775 * ensures the current hlua state ctx is available from
8776 * the new subroutine state
8777 */
8778__LJMP static int hlua_coroutine_create(lua_State *L)
8779{
8780 lua_State *new; /* new coroutine state */
8781 struct hlua **hlua_store;
8782 struct hlua *hlua = hlua_gethlua(L);
8783
8784 new = lua_newthread(L);
8785 if (!new)
8786 return 0;
8787
8788 hlua_store = lua_getextraspace(new);
8789 /* Expose current hlua ctx on new lua thread
8790 * (hlua_gethlua() will properly return the last "known"
8791 * hlua ctx instead of NULL when it is called from such coroutines)
8792 */
8793 *hlua_store = hlua;
8794
8795 /* new lua thread is on the top of the stack, we
8796 * need to duplicate first stack argument (<f> from coroutine.create(<f>))
8797 * on the top of the stack to be able to use xmove() to move it on the new
8798 * stack
8799 */
8800 lua_pushvalue(L, 1);
8801 /* move <f> function to the new stack */
8802 lua_xmove(L, new, 1);
8803 /* new lua thread is back at the top of the stack */
8804 return 1;
8805}
8806
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008807/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008808 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8809 * return an E_AGAIN signal, the emmiter of this signal must set a
8810 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008811 *
8812 * Task wrapper are longjmp safe because the only one Lua code
8813 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008814 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008815struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008816{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008817 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008818 enum hlua_exec status;
8819
Willy Tarreau6ef52f42022-06-15 14:19:48 +02008820 if (task->tid < 0)
8821 task->tid = tid;
8822
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008823 /* If it is the first call to the task, we must initialize the
8824 * execution timeouts.
8825 */
8826 if (!HLUA_IS_RUNNING(hlua))
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01008827 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008828
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008829 /* Execute the Lua code. */
8830 status = hlua_ctx_resume(hlua, 1);
8831
8832 switch (status) {
8833 /* finished or yield */
8834 case HLUA_E_OK:
8835 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008836 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008837 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008838 break;
8839
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008840 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008841 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008842 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008843 break;
8844
8845 /* finished with error. */
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008846 case HLUA_E_ETMOUT:
8847 SEND_ERR(NULL, "Lua task: execution timeout.\n");
8848 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008849 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008850 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008851 goto err_task_abort;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008852 case HLUA_E_ERR:
8853 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008854 SEND_ERR(NULL, "Lua task: unknown error.\n");
Aurelien DARRAGON79544102022-11-24 14:27:15 +01008855 err_task_abort:
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008856 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008857 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008858 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008859 break;
8860 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008861 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008862}
8863
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008864/* This function is an LUA binding that register LUA function to be
8865 * executed after the HAProxy configuration parsing and before the
8866 * HAProxy scheduler starts. This function expect only one LUA
8867 * argument that is a function. This function returns nothing, but
8868 * throws if an error is encountered.
8869 */
8870__LJMP static int hlua_register_init(lua_State *L)
8871{
8872 struct hlua_init_function *init;
8873 int ref;
8874
8875 MAY_LJMP(check_args(L, 1, "register_init"));
8876
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01008877 if (hlua_gethlua(L)) {
8878 /* runtime processing */
8879 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
8880 }
8881
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008882 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8883
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008884 init = calloc(1, sizeof(*init));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008885 if (!init) {
8886 hlua_unref(L, ref);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008887 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008888 }
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008889
8890 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008891 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008892 return 0;
8893}
8894
Ilya Shipitsin6f86eaa2022-11-30 16:22:42 +05008895/* This function is an LUA binding. It permits to register a task
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008896 * executed in parallel of the main HAroxy activity. The task is
8897 * created and it is set in the HAProxy scheduler. It can be called
8898 * from the "init" section, "post init" or during the runtime.
8899 *
8900 * Lua prototype:
8901 *
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008902 * <none> core.register_task(<function>[, <arg1>[, <arg2>[, ...[, <arg4>]]]])
8903 *
8904 * <arg1..4> are optional arguments that will be provided to <function>
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008905 */
Aurelien DARRAGONe0b16352023-04-21 17:38:37 +02008906__LJMP static int hlua_register_task(lua_State *L)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008907{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008908 struct hlua *hlua = NULL;
8909 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008910 int ref;
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008911 int nb_arg;
8912 int it;
8913 int arg_ref[4]; /* optional arguments */
Thierry Fournier021d9862020-11-28 23:42:03 +01008914 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008915
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008916 nb_arg = lua_gettop(L);
8917 if (nb_arg < 1)
8918 WILL_LJMP(luaL_error(L, "register_task: <func> argument is required"));
8919 else if (nb_arg > 5)
8920 WILL_LJMP(luaL_error(L, "register_task: no more that 4 optional arguments may be provided"));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008921
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008922 /* first arg: function ref */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008923 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8924
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008925 /* extract optional args (if any) */
8926 it = 0;
8927 while (--nb_arg) {
8928 lua_pushvalue(L, 2 + it);
8929 arg_ref[it] = hlua_ref(L); /* get arg reference */
8930 it += 1;
8931 }
8932 nb_arg = it;
8933
Thierry Fournier75fc0292020-11-28 13:18:56 +01008934 /* Get the reference state. If the reference is NULL, L is the master
8935 * state, otherwise hlua->T is.
8936 */
8937 hlua = hlua_gethlua(L);
8938 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008939 /* we are in runtime processing */
8940 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008941 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008942 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008943 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008944
Willy Tarreaubafbe012017-11-24 17:34:44 +01008945 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008946 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008947 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008948 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008949
Thierry Fournier59f11be2020-11-29 00:37:41 +01008950 /* We are in the common lua state, execute the task anywhere,
8951 * otherwise, inherit the current thread identifier
8952 */
8953 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008954 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008955 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008956 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008957 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008958 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008959
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008960 task->context = hlua;
8961 task->process = hlua_process_task;
8962
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01008963 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008964 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008965
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008966 /* Ensure there is enough space on the stack for the function
8967 * plus optional arguments
8968 */
8969 if (!lua_checkstack(hlua->T, (1 + nb_arg)))
8970 goto alloc_error;
8971
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008972 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01008973 hlua_pushref(hlua->T, ref);
Aurelien DARRAGONbe58d662023-03-13 14:09:21 +01008974 /* function ref not needed anymore since it was pushed to the substack */
8975 hlua_unref(L, ref);
8976
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008977 hlua->nargs = nb_arg;
8978
8979 /* push optional arguments to the function */
8980 for (it = 0; it < nb_arg; it++) {
8981 /* push arg to the stack */
8982 hlua_pushref(hlua->T, arg_ref[it]);
8983 /* arg ref not needed anymore since it was pushed to the substack */
8984 hlua_unref(L, arg_ref[it]);
8985 }
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008986
8987 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008988 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008989
8990 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008991
8992 alloc_error:
8993 task_destroy(task);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +01008994 hlua_unref(L, ref);
Aurelien DARRAGONb8038992023-03-09 16:48:30 +01008995 for (it = 0; it < nb_arg; it++) {
8996 hlua_unref(L, arg_ref[it]);
8997 }
Christopher Faulet5294ec02021-04-12 12:24:47 +02008998 hlua_ctx_destroy(hlua);
8999 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9000 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01009001}
9002
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009003/* called from unsafe location */
9004static void hlua_event_subscription_destroy(struct hlua_event_sub *hlua_sub)
9005{
9006 /* hlua cleanup */
9007
9008 hlua_lock(hlua_sub->hlua);
9009 /* registry is shared between coroutines */
9010 hlua_unref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9011 hlua_unlock(hlua_sub->hlua);
9012
9013 hlua_ctx_destroy(hlua_sub->hlua);
9014
9015 /* free */
9016 pool_free(pool_head_hlua_event_sub, hlua_sub);
9017}
9018
9019/* single event handler: hlua ctx is shared between multiple events handlers
9020 * issued from the same subscription. Thus, it is not destroyed when the event
9021 * is processed: it is destroyed when no more events are expected for the
9022 * subscription (ie: when the subscription ends).
9023 *
9024 * Moreover, events are processed sequentially within the subscription:
9025 * one event must be fully processed before another one may be processed.
9026 * This ensures proper consistency for lua event handling from an ordering
9027 * point of view. This is especially useful with server events for example
9028 * where ADD/DEL/UP/DOWN events ordering really matters to trigger specific
9029 * actions from lua (e.g.: sending emails or making API calls).
9030 *
9031 * Due to this design, each lua event handler is pleased to process the event
9032 * as fast as possible to prevent the event queue from growing up.
9033 * Strictly speaking, there is no runtime limit for the callback function
9034 * (timeout set to default task timeout), but if the event queue goes past
9035 * the limit of unconsumed events an error will be reported and the
9036 * susbscription will pause itself for as long as it takes for the handler to
9037 * catch up (events will be lost as a result).
9038 * If the event handler does not need the sequential ordering and wants to
9039 * process multiple events at a time, it may spawn a new side-task using
9040 * 'core.register_task' to delegate the event handling and make parallel event
9041 * processing within the same subscription set.
9042 */
9043static void hlua_event_handler(struct hlua *hlua)
9044{
9045 enum hlua_exec status;
9046
9047 /* If it is the first call to the task, we must initialize the
9048 * execution timeouts.
9049 */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009050 if (!HLUA_IS_RUNNING(hlua))
9051 hlua_timer_init(&hlua->timer, hlua_timeout_task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009052
9053 /* make sure to reset the task expiry before each hlua_ctx_resume()
9054 * since the task is re-used for multiple cb function calls
9055 * We couldn't risk to have t->expire pointing to a past date because
9056 * it was set during last function invocation but was never reset since
9057 * (ie: E_AGAIN)
9058 */
9059 hlua->task->expire = TICK_ETERNITY;
9060
9061 /* Execute the Lua code. */
9062 status = hlua_ctx_resume(hlua, 1);
9063
9064 switch (status) {
9065 /* finished or yield */
9066 case HLUA_E_OK:
9067 break;
9068
9069 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
9070 notification_gc(&hlua->com);
9071 hlua->task->expire = hlua->wake_time;
9072 break;
9073
9074 /* finished with error. */
9075 case HLUA_E_ETMOUT:
9076 SEND_ERR(NULL, "Lua event_hdl: execution timeout.\n");
9077 break;
9078
9079 case HLUA_E_ERRMSG:
9080 SEND_ERR(NULL, "Lua event_hdl: %s.\n", lua_tostring(hlua->T, -1));
9081 break;
9082
9083 case HLUA_E_ERR:
9084 default:
9085 SEND_ERR(NULL, "Lua event_hdl: unknown error.\n");
9086 break;
9087 }
9088}
9089
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009090__LJMP static void hlua_event_hdl_cb_push_event_checkres(lua_State *L,
9091 struct event_hdl_cb_data_server_checkres *check)
9092{
9093 lua_pushstring(L, "agent");
9094 lua_pushboolean(L, check->agent);
9095 lua_settable(L, -3);
9096 lua_pushstring(L, "result");
9097 switch (check->result) {
9098 case CHK_RES_FAILED:
9099 lua_pushstring(L, "FAILED");
9100 break;
9101 case CHK_RES_PASSED:
9102 lua_pushstring(L, "PASSED");
9103 break;
9104 case CHK_RES_CONDPASS:
9105 lua_pushstring(L, "CONDPASS");
9106 break;
9107 default:
9108 lua_pushnil(L);
9109 break;
9110 }
9111 lua_settable(L, -3);
9112
9113 lua_pushstring(L, "duration");
9114 lua_pushinteger(L, check->duration);
9115 lua_settable(L, -3);
9116
9117 lua_pushstring(L, "reason");
9118 lua_newtable(L);
9119
9120 lua_pushstring(L, "short");
9121 lua_pushstring(L, get_check_status_info(check->reason.status));
9122 lua_settable(L, -3);
9123 lua_pushstring(L, "desc");
9124 lua_pushstring(L, get_check_status_description(check->reason.status));
9125 lua_settable(L, -3);
9126 if (check->reason.status >= HCHK_STATUS_L57DATA) {
9127 /* code only available when the check reached data analysis stage */
9128 lua_pushstring(L, "code");
9129 lua_pushinteger(L, check->reason.code);
9130 lua_settable(L, -3);
9131 }
9132
9133 lua_settable(L, -3); /* reason table */
9134
9135 lua_pushstring(L, "health");
9136 lua_newtable(L);
9137
9138 lua_pushstring(L, "cur");
9139 lua_pushinteger(L, check->health.cur);
9140 lua_settable(L, -3);
9141 lua_pushstring(L, "rise");
9142 lua_pushinteger(L, check->health.rise);
9143 lua_settable(L, -3);
9144 lua_pushstring(L, "fall");
9145 lua_pushinteger(L, check->health.fall);
9146 lua_settable(L, -3);
9147
9148 lua_settable(L, -3); /* health table */
9149}
9150
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009151/* This function pushes various arguments such as event type and event data to
9152 * the lua function that will be called to consume the event.
9153 */
9154__LJMP static void hlua_event_hdl_cb_push_args(struct hlua_event_sub *hlua_sub,
9155 struct event_hdl_async_event *e)
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009156{
9157 struct hlua *hlua = hlua_sub->hlua;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009158 struct event_hdl_sub_type event = e->type;
9159 void *data = e->data;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009160
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009161 /* push event type */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009162 hlua->nargs = 1;
9163 lua_pushstring(hlua->T, event_hdl_sub_type_to_string(event));
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009164
9165 /* push event data (according to event type) */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009166 if (event_hdl_sub_family_equal(EVENT_HDL_SUB_SERVER, event)) {
9167 struct event_hdl_cb_data_server *e_server = data;
9168 struct proxy *px;
9169 struct server *server;
9170
9171 hlua->nargs += 1;
9172 lua_newtable(hlua->T);
9173 /* Add server name */
9174 lua_pushstring(hlua->T, "name");
9175 lua_pushstring(hlua->T, e_server->safe.name);
9176 lua_settable(hlua->T, -3);
9177 /* Add server puid */
9178 lua_pushstring(hlua->T, "puid");
9179 lua_pushinteger(hlua->T, e_server->safe.puid);
9180 lua_settable(hlua->T, -3);
9181 /* Add server rid */
9182 lua_pushstring(hlua->T, "rid");
9183 lua_pushinteger(hlua->T, e_server->safe.rid);
9184 lua_settable(hlua->T, -3);
9185 /* Add server proxy name */
9186 lua_pushstring(hlua->T, "proxy_name");
9187 lua_pushstring(hlua->T, e_server->safe.proxy_name);
9188 lua_settable(hlua->T, -3);
Aurelien DARRAGON55f84c72023-03-22 17:49:04 +01009189 /* Add server proxy uuid */
9190 lua_pushstring(hlua->T, "proxy_uuid");
9191 lua_pushinteger(hlua->T, e_server->safe.proxy_uuid);
9192 lua_settable(hlua->T, -3);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009193
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009194 /* special events, fetch additional info with explicit type casting */
9195 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_STATE, event)) {
9196 struct event_hdl_cb_data_server_state *state = data;
9197 int it;
9198
9199 if (!lua_checkstack(hlua->T, 20))
9200 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9201
9202 /* state subclass */
9203 lua_pushstring(hlua->T, "state");
9204 lua_newtable(hlua->T);
9205
9206 lua_pushstring(hlua->T, "admin");
9207 lua_pushboolean(hlua->T, state->safe.type);
9208 lua_settable(hlua->T, -3);
9209
9210 /* is it because of a check ? */
9211 if (!state->safe.type &&
9212 (state->safe.op_st_chg.cause == SRV_OP_STCHGC_HEALTH ||
9213 state->safe.op_st_chg.cause == SRV_OP_STCHGC_AGENT)) {
9214 /* yes, provide check result */
9215 lua_pushstring(hlua->T, "check");
9216 lua_newtable(hlua->T);
9217 hlua_event_hdl_cb_push_event_checkres(hlua->T, &state->safe.op_st_chg.check);
9218 lua_settable(hlua->T, -3); /* check table */
9219 }
9220
9221 lua_pushstring(hlua->T, "cause");
9222 if (state->safe.type)
9223 lua_pushstring(hlua->T, srv_adm_st_chg_cause(state->safe.adm_st_chg.cause));
9224 else
9225 lua_pushstring(hlua->T, srv_op_st_chg_cause(state->safe.op_st_chg.cause));
9226 lua_settable(hlua->T, -3);
9227
9228 /* old_state, new_state */
9229 for (it = 0; it < 2; it++) {
9230 enum srv_state srv_state = (!it) ? state->safe.old_state : state->safe.new_state;
9231
9232 lua_pushstring(hlua->T, (!it) ? "old_state" : "new_state");
9233 switch (srv_state) {
9234 case SRV_ST_STOPPED:
9235 lua_pushstring(hlua->T, "STOPPED");
9236 break;
9237 case SRV_ST_STOPPING:
9238 lua_pushstring(hlua->T, "STOPPING");
9239 break;
9240 case SRV_ST_STARTING:
9241 lua_pushstring(hlua->T, "STARTING");
9242 break;
9243 case SRV_ST_RUNNING:
9244 lua_pushstring(hlua->T, "RUNNING");
9245 break;
9246 default:
9247 lua_pushnil(hlua->T);
9248 break;
9249 }
9250 lua_settable(hlua->T, -3);
9251 }
9252
9253 /* requeued */
9254 lua_pushstring(hlua->T, "requeued");
9255 lua_pushinteger(hlua->T, state->safe.requeued);
9256 lua_settable(hlua->T, -3);
9257
9258 lua_settable(hlua->T, -3); /* state table */
9259 }
Aurelien DARRAGON948dd3d2023-04-26 11:27:09 +02009260 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_ADMIN, event)) {
9261 struct event_hdl_cb_data_server_admin *admin = data;
9262 int it;
9263
9264 if (!lua_checkstack(hlua->T, 20))
9265 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9266
9267 /* admin subclass */
9268 lua_pushstring(hlua->T, "admin");
9269 lua_newtable(hlua->T);
9270
9271 lua_pushstring(hlua->T, "cause");
9272 lua_pushstring(hlua->T, srv_adm_st_chg_cause(admin->safe.cause));
9273 lua_settable(hlua->T, -3);
9274
9275 /* old_admin, new_admin */
9276 for (it = 0; it < 2; it++) {
9277 enum srv_admin srv_admin = (!it) ? admin->safe.old_admin : admin->safe.new_admin;
9278
9279 lua_pushstring(hlua->T, (!it) ? "old_admin" : "new_admin");
9280
9281 /* admin state matrix */
9282 lua_newtable(hlua->T);
9283
9284 lua_pushstring(hlua->T, "MAINT");
9285 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_MAINT);
9286 lua_settable(hlua->T, -3);
9287 lua_pushstring(hlua->T, "FMAINT");
9288 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FMAINT);
9289 lua_settable(hlua->T, -3);
9290 lua_pushstring(hlua->T, "IMAINT");
9291 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IMAINT);
9292 lua_settable(hlua->T, -3);
9293 lua_pushstring(hlua->T, "RMAINT");
9294 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_RMAINT);
9295 lua_settable(hlua->T, -3);
9296 lua_pushstring(hlua->T, "CMAINT");
9297 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_CMAINT);
9298 lua_settable(hlua->T, -3);
9299
9300 lua_pushstring(hlua->T, "DRAIN");
9301 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_DRAIN);
9302 lua_settable(hlua->T, -3);
9303 lua_pushstring(hlua->T, "FDRAIN");
9304 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_FDRAIN);
9305 lua_settable(hlua->T, -3);
9306 lua_pushstring(hlua->T, "IDRAIN");
9307 lua_pushboolean(hlua->T, srv_admin & SRV_ADMF_IDRAIN);
9308 lua_settable(hlua->T, -3);
9309
9310 lua_settable(hlua->T, -3); /* matrix table */
9311 }
9312 /* requeued */
9313 lua_pushstring(hlua->T, "requeued");
9314 lua_pushinteger(hlua->T, admin->safe.requeued);
9315 lua_settable(hlua->T, -3);
9316
9317 lua_settable(hlua->T, -3); /* admin table */
9318 }
Aurelien DARRAGON0bd53b22023-03-30 15:53:33 +02009319 else if (event_hdl_sub_type_equal(EVENT_HDL_SUB_SERVER_CHECK, event)) {
9320 struct event_hdl_cb_data_server_check *check = data;
9321
9322 if (!lua_checkstack(hlua->T, 20))
9323 WILL_LJMP(luaL_error(hlua->T, "Lua out of memory error."));
9324
9325 /* check subclass */
9326 lua_pushstring(hlua->T, "check");
9327 lua_newtable(hlua->T);
9328
9329 /* check result snapshot */
9330 hlua_event_hdl_cb_push_event_checkres(hlua->T, &check->safe.res);
9331
9332 lua_settable(hlua->T, -3); /* check table */
9333 }
Aurelien DARRAGONc99f3ad2023-04-12 15:47:16 +02009334
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009335 /* attempt to provide reference server object
9336 * (if it wasn't removed yet, SERVER_DEL will never succeed here)
9337 */
Aurelien DARRAGON3d9bf4e2023-03-22 17:46:12 +01009338 px = proxy_find_by_id(e_server->safe.proxy_uuid, PR_CAP_BE, 0);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009339 BUG_ON(!px);
9340 server = findserver_unique_id(px, e_server->safe.puid, e_server->safe.rid);
9341 if (server) {
9342 lua_pushstring(hlua->T, "reference");
9343 hlua_fcn_new_server(hlua->T, server);
9344 lua_settable(hlua->T, -3);
9345 }
9346 }
9347 /* sub mgmt */
9348 hlua->nargs += 1;
9349 hlua_fcn_new_event_sub(hlua->T, hlua_sub->sub);
Aurelien DARRAGON096b3832023-04-20 11:32:46 +02009350
9351 /* when? */
9352 hlua->nargs += 1;
9353 lua_pushinteger(hlua->T, e->when.tv_sec);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009354}
9355
9356/* events runner: if there's an ongoing hlua event handling process, finish it
9357 * then, check if there are new events waiting to be processed
9358 * (events are processed sequentially)
9359 *
9360 * We have a safety measure to warn/guard if the event queue is growing up
9361 * too much due to many events being generated and lua handler is unable to
9362 * keep up the pace (e.g.: when the event queue grows past 100 unconsumed events).
9363 * TODO: make it tunable
9364 */
9365static struct task *hlua_event_runner(struct task *task, void *context, unsigned int state)
9366{
9367 struct hlua_event_sub *hlua_sub = context;
9368 struct event_hdl_async_event *event;
9369 const char *error = NULL;
9370
9371 if (!hlua_sub->paused && event_hdl_async_equeue_size(&hlua_sub->equeue) > 100) {
Aurelien DARRAGON7428ada2023-05-15 18:46:44 +02009372 const char *trace = NULL;
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009373
9374 /* We reached the limit of pending events in the queue: we should
9375 * warn the user, and temporarily pause the subscription to give a chance
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009376 * to the handler to catch up? (it also prevents resource shortage since
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009377 * the queue could grow indefinitely otherwise)
9378 * TODO: find a way to inform the handler that it missed some events
9379 * (example: stats within the subscription in event_hdl api exposed via lua api?)
9380 *
9381 * Nonetheless, reaching this limit means that the handler is not fast enough
9382 * and/or that it subscribed to events that happen too frequently and did not
9383 * expect it. This could come from an inadequate design in the user's script.
9384 */
9385 event_hdl_pause(hlua_sub->sub);
9386 hlua_sub->paused = 1;
9387
Aurelien DARRAGON7428ada2023-05-15 18:46:44 +02009388 if (SET_SAFE_LJMP(hlua_sub->hlua)) {
9389 /* The following Lua call may fail. */
9390 trace = hlua_traceback(hlua_sub->hlua->T, ", ");
9391 /* At this point the execution is safe. */
9392 RESET_SAFE_LJMP(hlua_sub->hlua);
9393 } else {
9394 /* Lua error was raised while fetching lua trace from current ctx */
9395 SEND_ERR(NULL, "Lua event_hdl: unexpected error (memory failure?).\n");
9396 }
9397 ha_warning("Lua event_hdl: pausing the subscription because the handler fails "
9398 "to keep up the pace (%u unconsumed events) from %s.\n",
9399 event_hdl_async_equeue_size(&hlua_sub->equeue),
9400 (trace) ? trace : "[unknown]");
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009401 }
9402
9403 if (HLUA_IS_RUNNING(hlua_sub->hlua)) {
9404 /* ongoing hlua event handler, resume it */
9405 hlua_event_handler(hlua_sub->hlua);
9406 } else if ((event = event_hdl_async_equeue_pop(&hlua_sub->equeue))) { /* check for new events */
9407 if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
9408 /* ending event: no more events to come */
9409 event_hdl_async_free_event(event);
9410 task_destroy(task);
9411 hlua_event_subscription_destroy(hlua_sub);
9412 return NULL;
9413 }
9414 /* new event: start processing it */
9415
9416 /* The following Lua calls can fail. */
9417 if (!SET_SAFE_LJMP(hlua_sub->hlua)) {
9418 if (lua_type(hlua_sub->hlua->T, -1) == LUA_TSTRING)
9419 error = lua_tostring(hlua_sub->hlua->T, -1);
9420 else
9421 error = "critical error";
9422 ha_alert("Lua event_hdl: %s.\n", error);
9423 goto skip_event;
9424 }
9425
9426 /* Check stack available size. */
9427 if (!lua_checkstack(hlua_sub->hlua->T, 5)) {
9428 ha_alert("Lua event_hdl: full stack.\n");
9429 RESET_SAFE_LJMP(hlua_sub->hlua);
9430 goto skip_event;
9431 }
9432
9433 /* Restore the function in the stack. */
9434 hlua_pushref(hlua_sub->hlua->T, hlua_sub->fcn_ref);
9435
9436 /* push args */
9437 hlua_sub->hlua->nargs = 0;
Aurelien DARRAGON2f6a07d2023-03-27 18:16:21 +02009438 MAY_LJMP(hlua_event_hdl_cb_push_args(hlua_sub, event));
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009439
9440 /* At this point the execution is safe. */
9441 RESET_SAFE_LJMP(hlua_sub->hlua);
9442
9443 /* At this point the event was successfully translated into hlua ctx,
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009444 * or hlua error occurred, so we can safely discard it
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009445 */
9446 event_hdl_async_free_event(event);
9447 event = NULL;
9448
9449 hlua_event_handler(hlua_sub->hlua);
9450 skip_event:
9451 if (event)
9452 event_hdl_async_free_event(event);
9453
9454 }
9455
9456 if (!HLUA_IS_RUNNING(hlua_sub->hlua)) {
9457 /* we just finished the processing of one event..
9458 * check for new events before becoming idle
9459 */
9460 if (!event_hdl_async_equeue_isempty(&hlua_sub->equeue)) {
9461 /* more events to process, make sure the task
9462 * will be resumed ASAP to process pending events
9463 */
9464 task_wakeup(task, TASK_WOKEN_OTHER);
9465 }
9466 else if (hlua_sub->paused) {
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009467 /* empty queue, the handler caught up: resume the subscription */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009468 event_hdl_resume(hlua_sub->sub);
9469 hlua_sub->paused = 0;
9470 }
9471 }
9472
9473 return task;
9474}
9475
9476/* Must be called directly under lua protected/safe environment
9477 * (not from external callback)
9478 * <fcn_ref> should NOT be dropped after the function successfully returns:
9479 * it will be done automatically in hlua_event_subscription_destroy() when the
9480 * subscription ends.
9481 *
9482 * Returns the new subscription on success and NULL on failure (memory error)
9483 */
9484static struct event_hdl_sub *hlua_event_subscribe(event_hdl_sub_list *list, struct event_hdl_sub_type e_type,
9485 int state_id, int fcn_ref)
9486{
9487 struct hlua_event_sub *hlua_sub;
9488 struct task *task = NULL;
9489
9490 hlua_sub = pool_alloc(pool_head_hlua_event_sub);
9491 if (!hlua_sub)
9492 goto mem_error;
9493 hlua_sub->task = NULL;
9494 hlua_sub->hlua = NULL;
9495 hlua_sub->paused = 0;
9496 if ((task = task_new_here()) == NULL) {
9497 ha_alert("out of memory while allocating hlua event task");
9498 goto mem_error;
9499 }
9500 task->process = hlua_event_runner;
9501 task->context = hlua_sub;
9502 event_hdl_async_equeue_init(&hlua_sub->equeue);
9503 hlua_sub->task = task;
9504 hlua_sub->fcn_ref = fcn_ref;
9505 hlua_sub->state_id = state_id;
9506 hlua_sub->hlua = pool_alloc(pool_head_hlua);
9507 if (!hlua_sub->hlua)
9508 goto mem_error;
9509 HLUA_INIT(hlua_sub->hlua);
9510 if (!hlua_ctx_init(hlua_sub->hlua, hlua_sub->state_id, task))
9511 goto mem_error;
9512
9513 hlua_sub->sub = event_hdl_subscribe_ptr(list, e_type,
9514 EVENT_HDL_ASYNC_TASK(&hlua_sub->equeue,
9515 task,
9516 hlua_sub,
9517 NULL));
9518 if (!hlua_sub->sub)
9519 goto mem_error;
9520
9521 return hlua_sub->sub; /* returns pointer to event_hdl_sub struct */
9522
9523 mem_error:
9524 if (hlua_sub) {
Tim Duesterhusfe83f582023-04-22 17:47:34 +02009525 task_destroy(hlua_sub->task);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009526 if (hlua_sub->hlua)
9527 hlua_ctx_destroy(hlua_sub->hlua);
9528 pool_free(pool_head_hlua_event_sub, hlua_sub);
9529 }
9530
9531 return NULL;
9532}
9533
9534/* looks for an array of strings referring to a composition of event_hdl subscription
9535 * types at <index> in <L> stack
9536 */
9537__LJMP static struct event_hdl_sub_type hlua_check_event_sub_types(lua_State *L, int index)
9538{
9539 struct event_hdl_sub_type subscriptions;
9540 const char *msg;
9541
9542 if (lua_type(L, index) != LUA_TTABLE) {
9543 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9544 luaL_argerror(L, index, msg);
9545 }
9546
9547 subscriptions = EVENT_HDL_SUB_NONE;
9548
9549 /* browse the argument as an array. */
9550 lua_pushnil(L);
9551 while (lua_next(L, index) != 0) {
9552 if (lua_type(L, -1) != LUA_TSTRING) {
9553 msg = lua_pushfstring(L, "table of strings expected, got %s", luaL_typename(L, index));
9554 luaL_argerror(L, index, msg);
9555 }
9556
9557 if (event_hdl_sub_type_equal(EVENT_HDL_SUB_NONE, event_hdl_string_to_sub_type(lua_tostring(L, -1)))) {
9558 msg = lua_pushfstring(L, "'%s' event type is unknown", lua_tostring(L, -1));
9559 luaL_argerror(L, index, msg);
9560 }
9561
9562 /* perform subscriptions |= current sub */
9563 subscriptions = event_hdl_sub_type_add(subscriptions, event_hdl_string_to_sub_type(lua_tostring(L, -1)));
9564
9565 /* pop the current value. */
9566 lua_pop(L, 1);
9567 }
9568
9569 return subscriptions;
9570}
9571
9572/* Wrapper for hlua_fcn_new_event_sub(): catch errors raised by
9573 * the function to prevent LJMP
9574 *
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009575 * If no error occurred, the function returns 1, else it returns 0 and
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009576 * the error message is pushed at the top of the stack
9577 */
9578__LJMP static int _hlua_new_event_sub_safe(lua_State *L)
9579{
9580 struct event_hdl_sub *sub = lua_touserdata(L, 1);
9581
9582 /* this function may raise errors */
9583 return MAY_LJMP(hlua_fcn_new_event_sub(L, sub));
9584}
9585static int hlua_new_event_sub_safe(lua_State *L, struct event_hdl_sub *sub)
9586{
9587 if (!lua_checkstack(L, 2))
9588 return 0;
9589 lua_pushcfunction(L, _hlua_new_event_sub_safe);
9590 lua_pushlightuserdata(L, sub);
9591 switch (lua_pcall(L, 1, 1, 0)) {
9592 case LUA_OK:
9593 return 1;
9594 default:
Ilya Shipitsinccf80122023-04-22 20:20:39 +02009595 /* error was caught */
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +01009596 return 0;
9597 }
9598}
9599
9600/* This function is a LUA helper used for registering lua event callbacks.
9601 * It expects an event subscription array and the function to be executed
9602 * when subscribed events occur (stack arguments).
9603 * It can be called from the "init" section, "post init" or during the runtime.
9604 *
9605 * <sub_list> is the subscription list where the subscription will be attempted
9606 *
9607 * Pushes the newly allocated subscription on the stack on success
9608 */
9609__LJMP int hlua_event_sub(lua_State *L, event_hdl_sub_list *sub_list)
9610{
9611 struct hlua *hlua;
9612 struct event_hdl_sub *sub;
9613 struct event_hdl_sub_type subscriptions;
9614 int fcn_ref;
9615 int state_id;
9616
9617 MAY_LJMP(check_args(L, 2, "event_sub"));
9618
9619 /* Get the reference state */
9620 hlua = hlua_gethlua(L);
9621 if (hlua)
9622 /* we are in runtime processing, any thread may subscribe to events:
9623 * subscription events will be handled by the thread who performed
9624 * the registration.
9625 */
9626 state_id = hlua->state_id;
9627 else {
9628 /* we are in initialization mode, only thread 0 (actual calling thread)
9629 * may subscribe to events to prevent the same handler (from different lua
9630 * stacks) from being registered multiple times
9631 *
9632 * hlua_state_id == 0: monostack (lua-load)
9633 * hlua_state_id > 0: hlua_state_id=tid+1, multi-stack (lua-load-per-thread)
9634 * (thus if hlua_state_id > 1, it means we are not in primary thread ctx)
9635 */
9636 if (hlua_state_id > 1)
9637 return 0; /* skip registration */
9638 state_id = hlua_state_id;
9639 }
9640
9641 /* First argument : event subscriptions. */
9642 subscriptions = MAY_LJMP(hlua_check_event_sub_types(L, 1));
9643
9644 if (event_hdl_sub_type_equal(subscriptions, EVENT_HDL_SUB_NONE)) {
9645 WILL_LJMP(luaL_error(L, "event_sub: no valid event types were provided"));
9646 return 0; /* Never reached */
9647 }
9648
9649 /* Second argument : lua function. */
9650 fcn_ref = MAY_LJMP(hlua_checkfunction(L, 2));
9651
9652 /* try to subscribe */
9653 sub = hlua_event_subscribe(sub_list, subscriptions, state_id, fcn_ref);
9654 if (!sub) {
9655 hlua_unref(L, fcn_ref);
9656 WILL_LJMP(luaL_error(L, "event_sub: lua out of memory error"));
9657 return 0; /* Never reached */
9658 }
9659
9660 /* push the subscription to the stack
9661 *
9662 * Here we use the safe function so that lua errors will be
9663 * handled explicitly to prevent 'sub' from being lost
9664 */
9665 if (!hlua_new_event_sub_safe(L, sub)) {
9666 /* Some events could already be pending in the handler's queue.
9667 * However it is wiser to cancel the subscription since we are unable to
9668 * provide a valid reference to it.
9669 * Pending events will be delivered (unless lua keeps raising errors).
9670 */
9671 event_hdl_unsubscribe(sub); /* cancel the subscription */
9672 WILL_LJMP(luaL_error(L, "event_sub: cannot push the subscription (%s)", lua_tostring(L, -1)));
9673 return 0; /* Never reached */
9674 }
9675 event_hdl_drop(sub); /* sub has been duplicated, discard old ref */
9676
9677 return 1;
9678}
9679
9680/* This function is a LUA wrapper used for registering global lua event callbacks
9681 * The new subscription is pushed onto the stack on success
9682 * Returns the number of arguments pushed to the stack (1 for success)
9683 */
9684__LJMP static int hlua_event_global_sub(lua_State *L)
9685{
9686 /* NULL <sub_list> = global subscription list */
9687 return MAY_LJMP(hlua_event_sub(L, NULL));
9688}
9689
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009690/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
9691 * doesn't allow "yield" functions because the HAProxy engine cannot
9692 * resume converters.
9693 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009694static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009695{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009696 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009697 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009698 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009699
Willy Tarreaube508f12016-03-10 11:47:01 +01009700 if (!stream)
9701 return 0;
9702
Willy Tarreau87b09662015-04-03 00:22:06 +02009703 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009704 * Lua context can be not initialized. This behavior
9705 * permits to save performances because a systematic
9706 * Lua initialization cause 5% performances loss.
9707 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009708 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009709 struct hlua *hlua;
9710
9711 hlua = pool_alloc(pool_head_hlua);
9712 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009713 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9714 return 0;
9715 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009716 HLUA_INIT(hlua);
9717 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009718 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009719 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
9720 return 0;
9721 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009722 }
9723
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009724 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009725 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009726
9727 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009728 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009729 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9730 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009731 else
9732 error = "critical error";
9733 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009734 return 0;
9735 }
9736
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009737 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009738 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009739 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009740 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009741 return 0;
9742 }
9743
9744 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009745 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009746
9747 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009748 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009749 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009750 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009751 return 0;
9752 }
Aurelien DARRAGON41217722023-05-17 10:44:47 +02009753 MAY_LJMP(hlua_smp2lua(stream->hlua->T, smp));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009754 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009755
9756 /* push keywords in the stack. */
9757 if (arg_p) {
9758 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009759 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009760 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009761 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009762 return 0;
9763 }
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +02009764 MAY_LJMP(hlua_arg2lua(stream->hlua->T, arg_p));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009765 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009766 }
9767 }
9768
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009769 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009770 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009771
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009772 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009773 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009774 }
9775
9776 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009777 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009778 /* finished. */
9779 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009780 /* If the stack is empty, the function fails. */
9781 if (lua_gettop(stream->hlua->T) <= 0)
9782 return 0;
9783
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009784 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009785 hlua_lua2smp(stream->hlua->T, -1, smp);
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02009786 /* dup the smp before popping the related lua value and
9787 * returning it to haproxy
9788 */
9789 smp_dup(smp);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009790 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009791 return 1;
9792
9793 /* yield. */
9794 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009795 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009796 return 0;
9797
9798 /* finished with error. */
9799 case HLUA_E_ERRMSG:
9800 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009801 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009802 fcn->name, lua_tostring(stream->hlua->T, -1));
9803 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009804 return 0;
9805
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009806 case HLUA_E_ETMOUT:
9807 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
9808 return 0;
9809
9810 case HLUA_E_NOMEM:
9811 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
9812 return 0;
9813
9814 case HLUA_E_YIELD:
9815 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
9816 return 0;
9817
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009818 case HLUA_E_ERR:
9819 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009820 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009821 __fallthrough;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009822
9823 default:
9824 return 0;
9825 }
9826}
9827
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009828/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
9829 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01009830 * resume sample-fetches. This function will be called by the sample
9831 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009832 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02009833static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
9834 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009835{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009836 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02009837 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009838 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009839 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009840
Willy Tarreaube508f12016-03-10 11:47:01 +01009841 if (!stream)
9842 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01009843
Willy Tarreau87b09662015-04-03 00:22:06 +02009844 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009845 * Lua context can be not initialized. This behavior
9846 * permits to save performances because a systematic
9847 * Lua initialization cause 5% performances loss.
9848 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009849 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009850 struct hlua *hlua;
9851
9852 hlua = pool_alloc(pool_head_hlua);
9853 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009854 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9855 return 0;
9856 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009857 hlua->T = NULL;
9858 stream->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +01009859 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009860 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
9861 return 0;
9862 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009863 }
9864
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009865 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009866 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009867
9868 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009869 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009870 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
9871 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009872 else
9873 error = "critical error";
9874 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009875 return 0;
9876 }
9877
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009878 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009879 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009880 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009881 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009882 return 0;
9883 }
9884
9885 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +01009886 hlua_pushref(stream->hlua->T, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009887
9888 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009889 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009890 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009891 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009892 return 0;
9893 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009894 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009895
9896 /* push keywords in the stack. */
9897 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
9898 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009899 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009900 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009901 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009902 return 0;
9903 }
Aurelien DARRAGONe5c048a2023-05-17 10:51:50 +02009904 MAY_LJMP(hlua_arg2lua(stream->hlua->T, arg_p));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009905 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009906 }
9907
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009908 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +01009909 hlua_timer_init(&stream->hlua->timer, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009910
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009911 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009912 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009913 }
9914
9915 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009916 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009917 /* finished. */
9918 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02009919 /* If the stack is empty, the function fails. */
9920 if (lua_gettop(stream->hlua->T) <= 0)
9921 return 0;
9922
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009923 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009924 hlua_lua2smp(stream->hlua->T, -1, smp);
Aurelien DARRAGON1c07da42023-05-17 16:06:11 +02009925 /* dup the smp before popping the related lua value and
9926 * returning it to haproxy
9927 */
9928 smp_dup(smp);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009929 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009930
9931 /* Set the end of execution flag. */
9932 smp->flags &= ~SMP_F_MAY_CHANGE;
9933 return 1;
9934
9935 /* yield. */
9936 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009937 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009938 return 0;
9939
9940 /* finished with error. */
9941 case HLUA_E_ERRMSG:
9942 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009943 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009944 fcn->name, lua_tostring(stream->hlua->T, -1));
9945 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009946 return 0;
9947
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009948 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009949 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
9950 return 0;
9951
9952 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009953 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
9954 return 0;
9955
9956 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009957 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
9958 return 0;
9959
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009960 case HLUA_E_ERR:
9961 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009962 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Willy Tarreau14de3952022-11-14 07:08:28 +01009963 __fallthrough;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009964
9965 default:
9966 return 0;
9967 }
9968}
9969
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009970/* This function is an LUA binding used for registering
9971 * "sample-conv" functions. It expects a converter name used
9972 * in the haproxy configuration file, and an LUA function.
9973 */
9974__LJMP static int hlua_register_converters(lua_State *L)
9975{
9976 struct sample_conv_kw_list *sck;
9977 const char *name;
9978 int ref;
9979 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02009980 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009981 struct sample_conv *sc;
9982 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009983
9984 MAY_LJMP(check_args(L, 2, "register_converters"));
9985
Aurelien DARRAGON87f52972023-02-24 09:43:54 +01009986 if (hlua_gethlua(L)) {
9987 /* runtime processing */
9988 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
9989 }
9990
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01009991 /* First argument : converter name. */
9992 name = MAY_LJMP(luaL_checkstring(L, 1));
9993
9994 /* Second argument : lua function. */
9995 ref = MAY_LJMP(hlua_checkfunction(L, 2));
9996
Thierry Fournierf67442e2020-11-28 20:41:07 +01009997 /* Check if the converter is already registered */
9998 trash = get_trash_chunk();
9999 chunk_printf(trash, "lua.%s", name);
10000 sc = find_sample_conv(trash->area, trash->data);
10001 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010002 fcn = sc->private;
10003 if (fcn->function_ref[hlua_state_id] != -1) {
10004 ha_warning("Trying to register converter 'lua.%s' more than once. "
10005 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010006 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010007 }
10008 fcn->function_ref[hlua_state_id] = ref;
10009 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010010 }
10011
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010012 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010013 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010014 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +020010015 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010016 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010017 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +020010018 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010019
10020 /* Fill fcn. */
10021 fcn->name = strdup(name);
10022 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +020010023 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010024 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010025
10026 /* List head */
10027 sck->list.n = sck->list.p = NULL;
10028
10029 /* converter keyword. */
10030 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010031 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010032 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +020010033 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010034
10035 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
10036 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010037 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 +010010038 sck->kw[0].val_args = NULL;
10039 sck->kw[0].in_type = SMP_T_STR;
10040 sck->kw[0].out_type = SMP_T_STR;
10041 sck->kw[0].private = fcn;
10042
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010043 /* Register this new converter */
10044 sample_register_convs(sck);
10045
10046 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +020010047
10048 alloc_error:
10049 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010050 hlua_unref(L, ref);
Christopher Fauletaa224302021-04-12 14:08:21 +020010051 ha_free(&sck);
10052 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10053 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +010010054}
10055
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010056/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010057 * "sample-fetch" functions. It expects a converter name used
10058 * in the haproxy configuration file, and an LUA function.
10059 */
10060__LJMP static int hlua_register_fetches(lua_State *L)
10061{
10062 const char *name;
10063 int ref;
10064 int len;
10065 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +020010066 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010067 struct sample_fetch *sf;
10068 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010069
10070 MAY_LJMP(check_args(L, 2, "register_fetches"));
10071
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010072 if (hlua_gethlua(L)) {
10073 /* runtime processing */
10074 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
10075 }
10076
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010077 /* First argument : sample-fetch name. */
10078 name = MAY_LJMP(luaL_checkstring(L, 1));
10079
10080 /* Second argument : lua function. */
10081 ref = MAY_LJMP(hlua_checkfunction(L, 2));
10082
Thierry Fournierf67442e2020-11-28 20:41:07 +010010083 /* Check if the sample-fetch is already registered */
10084 trash = get_trash_chunk();
10085 chunk_printf(trash, "lua.%s", name);
10086 sf = find_sample_fetch(trash->area, trash->data);
10087 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010088 fcn = sf->private;
10089 if (fcn->function_ref[hlua_state_id] != -1) {
10090 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
10091 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010092 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010093 }
10094 fcn->function_ref[hlua_state_id] = ref;
10095 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010096 }
10097
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010098 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010099 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010100 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +020010101 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010102 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010103 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +020010104 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010105
10106 /* Fill fcn. */
10107 fcn->name = strdup(name);
10108 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +020010109 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010110 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010111
10112 /* List head */
10113 sfk->list.n = sfk->list.p = NULL;
10114
10115 /* sample-fetch keyword. */
10116 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010117 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010118 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +020010119 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010120
10121 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
10122 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +010010123 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 +010010124 sfk->kw[0].val_args = NULL;
10125 sfk->kw[0].out_type = SMP_T_STR;
10126 sfk->kw[0].use = SMP_USE_HTTP_ANY;
10127 sfk->kw[0].val = 0;
10128 sfk->kw[0].private = fcn;
10129
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010130 /* Register this new fetch. */
10131 sample_register_fetches(sfk);
10132
10133 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +020010134
10135 alloc_error:
10136 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010137 hlua_unref(L, ref);
Christopher Faulet2567f182021-04-12 14:11:50 +020010138 ha_free(&sfk);
10139 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10140 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +010010141}
10142
Christopher Faulet501465d2020-02-26 14:54:16 +010010143/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010144 */
Christopher Faulet501465d2020-02-26 14:54:16 +010010145__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010146{
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010147 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010148 unsigned int delay;
Aurelien DARRAGON2a9764b2023-04-04 18:41:04 +020010149 int wakeup_ms; // tick value
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010150
Thierry Fournier4234dbd2020-11-28 13:18:23 +010010151 /* Get hlua struct, or NULL if we execute from main lua state */
10152 hlua = hlua_gethlua(L);
10153 if (!hlua) {
10154 return 0;
10155 }
10156
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010157 MAY_LJMP(check_args(L, 1, "wake_time"));
10158
10159 delay = MAY_LJMP(luaL_checkinteger(L, 1));
10160 wakeup_ms = tick_add(now_ms, delay);
10161 hlua->wake_time = wakeup_ms;
10162 return 0;
10163}
10164
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010165/* This function is a wrapper to execute each LUA function declared as an action
10166 * wrapper during the initialisation period. This function may return any
10167 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
10168 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
10169 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010170 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010171static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +020010172 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010173{
10174 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +020010175 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010176 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010177 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010178
10179 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +010010180 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
10181 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
10182 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
10183 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010184 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010185 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010186 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010187 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010188
Willy Tarreau87b09662015-04-03 00:22:06 +020010189 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010190 * Lua context can be not initialized. This behavior
10191 * permits to save performances because a systematic
10192 * Lua initialization cause 5% performances loss.
10193 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010194 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +010010195 struct hlua *hlua;
10196
10197 hlua = pool_alloc(pool_head_hlua);
10198 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010199 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010200 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010201 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010202 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +010010203 HLUA_INIT(hlua);
10204 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010205 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 +010010206 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010207 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010208 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010209 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +010010210 }
10211
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010212 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010213 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010214
10215 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010216 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010217 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10218 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +010010219 else
10220 error = "critical error";
10221 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010222 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010223 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010224 }
10225
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010226 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010227 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010228 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010229 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010230 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010231 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010232 }
10233
10234 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010235 hlua_pushref(s->hlua->T, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010236
Willy Tarreau87b09662015-04-03 00:22:06 +020010237 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +020010238 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010239 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010240 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010241 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010242 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010243 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010244 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010245
10246 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010247 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010248 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010249 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010250 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010251 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010252 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010253 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010254 lua_pushstring(s->hlua->T, *arg);
10255 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010256 }
10257
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010258 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010259 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010260
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010261 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010262 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010263 }
10264
10265 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +010010266 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010267 /* finished. */
10268 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010269 /* Catch the return value */
10270 if (lua_gettop(s->hlua->T) > 0)
10271 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010272
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010273 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +020010274 if (act_ret == ACT_RET_YIELD) {
10275 if (flags & ACT_OPT_FINAL)
10276 goto err_yield;
10277
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010278 if (dir == SMP_OPT_DIR_REQ)
10279 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10280 s->hlua->wake_time);
10281 else
10282 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10283 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010010284 }
10285 goto end;
10286
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010287 /* yield. */
10288 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +010010289 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010290 if (dir == SMP_OPT_DIR_REQ)
10291 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
10292 s->hlua->wake_time);
10293 else
10294 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
10295 s->hlua->wake_time);
10296
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010297 /* Some actions can be wake up when a "write" event
10298 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010299 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010300 */
Christopher Faulet51fa3582019-07-26 14:54:52 +020010301 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010302 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010303 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +010010304 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010305 act_ret = ACT_RET_YIELD;
10306 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010307
10308 /* finished with error. */
10309 case HLUA_E_ERRMSG:
10310 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010311 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010312 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +010010313 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010314 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010315
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010316 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010317 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010318 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010319
10320 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +010010321 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010322 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010323
10324 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +020010325 err_yield:
10326 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010327 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010328 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010329 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010330
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010331 case HLUA_E_ERR:
10332 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +020010333 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010334 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010335
10336 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010337 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010338 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010339
10340 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +020010341 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +020010342 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +010010343 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010344}
10345
Willy Tarreau144f84a2021-03-02 16:09:26 +010010346struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010347{
Olivier Houchard9f6af332018-05-25 14:04:04 +020010348 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010349
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010350 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +020010351 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +020010352 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010353}
10354
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010355static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010356{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010357 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010358 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010359 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010360 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010361 struct task *task;
10362 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010363 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010364
Willy Tarreaubafbe012017-11-24 17:34:44 +010010365 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010366 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010367 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010368 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010369 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010370 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010371 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010372 tcp_ctx->hlua = hlua;
10373 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010374
10375 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010376 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010377 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010378 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010379 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010380 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010381 }
10382 task->nice = 0;
10383 task->context = ctx;
10384 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010385 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010386
10387 /* In the execution wrappers linked with a stream, the
10388 * Lua context can be not initialized. This behavior
10389 * permits to save performances because a systematic
10390 * Lua initialization cause 5% performances loss.
10391 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010392 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010393 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010394 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010395 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010396 }
10397
10398 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010399 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010400
10401 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010402 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010403 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10404 error = lua_tostring(hlua->T, -1);
10405 else
10406 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010407 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010408 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010409 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010410 }
10411
10412 /* Check stack available size. */
10413 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010414 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010415 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010416 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010417 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010418 }
10419
10420 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010421 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010422
10423 /* Create and and push object stream in the stack. */
10424 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010425 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010426 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010427 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010428 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010429 }
10430 hlua->nargs = 1;
10431
10432 /* push keywords in the stack. */
10433 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10434 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010435 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010436 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010437 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010438 return -1;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010439 }
10440 lua_pushstring(hlua->T, *arg);
10441 hlua->nargs++;
10442 }
10443
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010444 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010445
10446 /* Wakeup the applet ASAP. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010447 applet_need_more_data(ctx);
Willy Tarreau4164eb92022-05-25 15:42:03 +020010448 applet_have_more_data(ctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010449
Christopher Fauletc9929382022-05-12 11:52:27 +020010450 return 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010451}
10452
Willy Tarreau60409db2019-08-21 14:14:50 +020010453void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010454{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010455 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010456 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010457 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010458 struct act_rule *rule = ctx->rule;
10459 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010460 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010461
Christopher Faulet31572222023-03-31 11:13:48 +020010462 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10463 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010464
Christopher Faulet31572222023-03-31 11:13:48 +020010465 /* The applet execution is already done. */
10466 if (tcp_ctx->flags & APPLET_DONE)
10467 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010468
10469 /* Execute the function. */
10470 switch (hlua_ctx_resume(hlua, 1)) {
10471 /* finished. */
10472 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010473 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010474 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
10475 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010476
10477 /* yield. */
10478 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +010010479 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010480 task_schedule(tcp_ctx->task, hlua->wake_time);
Christopher Faulet31572222023-03-31 11:13:48 +020010481 break;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010482
10483 /* finished with error. */
10484 case HLUA_E_ERRMSG:
10485 /* Display log. */
10486 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010487 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010488 lua_pop(hlua->T, 1);
10489 goto error;
10490
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010491 case HLUA_E_ETMOUT:
10492 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010493 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010494 goto error;
10495
10496 case HLUA_E_NOMEM:
10497 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010498 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010499 goto error;
10500
10501 case HLUA_E_YIELD: /* unexpected */
10502 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010503 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010504 goto error;
10505
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010506 case HLUA_E_ERR:
10507 /* Display log. */
10508 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010509 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010510 goto error;
10511
10512 default:
10513 goto error;
10514 }
10515
Christopher Faulet31572222023-03-31 11:13:48 +020010516out:
10517 /* eat the whole request */
10518 co_skip(sc_oc(sc), co_data(sc_oc(sc)));
10519 return;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010520
Christopher Faulet31572222023-03-31 11:13:48 +020010521error:
10522 se_fl_set(ctx->sedesc, SE_FL_ERROR);
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010523 tcp_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010524 goto out;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010525}
10526
10527static void hlua_applet_tcp_release(struct appctx *ctx)
10528{
Willy Tarreaue23f33b2022-05-06 14:07:13 +020010529 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
10530
10531 task_destroy(tcp_ctx->task);
10532 tcp_ctx->task = NULL;
10533 hlua_ctx_destroy(tcp_ctx->hlua);
10534 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010535}
10536
Christopher Fauletc9929382022-05-12 11:52:27 +020010537/* The function returns 0 if the initialisation is complete or -1 if
10538 * an errors occurs. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010539 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010540static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010541{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010542 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreauc12b3212022-05-27 11:08:15 +020010543 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010544 struct stream *strm = __sc_strm(sc);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010545 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010546 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010547 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010548 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010549 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010550
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010551 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +010010552 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010553 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010554 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010555 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010556 return -1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010557 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010558 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010559 http_ctx->hlua = hlua;
10560 http_ctx->left_bytes = -1;
10561 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010562
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010563 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010564 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +010010565
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010566 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010567 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010568 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010569 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010570 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010571 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010572 }
10573 task->nice = 0;
10574 task->context = ctx;
10575 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010576 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010577
10578 /* In the execution wrappers linked with a stream, the
10579 * Lua context can be not initialized. This behavior
10580 * permits to save performances because a systematic
10581 * Lua initialization cause 5% performances loss.
10582 */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010010583 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010584 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010585 ctx->rule->arg.hlua_rule->fcn->name);
Christopher Fauletc9929382022-05-12 11:52:27 +020010586 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010587 }
10588
10589 /* Set timeout according with the applet configuration. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010010590 hlua_timer_init(&hlua->timer, ctx->applet->timeout);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010591
10592 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010593 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +010010594 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10595 error = lua_tostring(hlua->T, -1);
10596 else
10597 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010598 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010599 ctx->rule->arg.hlua_rule->fcn->name, error);
Christopher Fauletc9929382022-05-12 11:52:27 +020010600 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010601 }
10602
10603 /* Check stack available size. */
10604 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010605 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010606 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010607 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010608 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010609 }
10610
10611 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010010612 hlua_pushref(hlua->T, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010613
10614 /* Create and and push object stream in the stack. */
10615 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010616 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010617 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010618 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010619 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010620 }
10621 hlua->nargs = 1;
10622
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010623 /* push keywords in the stack. */
10624 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
10625 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +010010626 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +010010627 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010628 RESET_SAFE_LJMP(hlua);
Christopher Fauletc9929382022-05-12 11:52:27 +020010629 return -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010630 }
10631 lua_pushstring(hlua->T, *arg);
10632 hlua->nargs++;
10633 }
10634
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010635 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010636
10637 /* Wakeup the applet when data is ready for read. */
Willy Tarreau90e8b452022-05-25 18:21:43 +020010638 applet_need_more_data(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010639
Christopher Fauletc9929382022-05-12 11:52:27 +020010640 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010641}
10642
Willy Tarreau60409db2019-08-21 14:14:50 +020010643void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010644{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010645 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreauc12b3212022-05-27 11:08:15 +020010646 struct stconn *sc = appctx_sc(ctx);
Willy Tarreau3e7be362022-05-27 10:35:27 +020010647 struct stream *strm = __sc_strm(sc);
10648 struct channel *req = sc_oc(sc);
10649 struct channel *res = sc_ic(sc);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010650 struct act_rule *rule = ctx->rule;
10651 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010652 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010653 struct htx *req_htx, *res_htx;
10654
10655 res_htx = htx_from_buf(&res->buf);
10656
Christopher Faulet31572222023-03-31 11:13:48 +020010657 if (unlikely(se_fl_test(ctx->sedesc, (SE_FL_EOS|SE_FL_ERROR|SE_FL_SHR|SE_FL_SHW))))
10658 goto out;
10659
10660 /* The applet execution is already done. */
10661 if (http_ctx->flags & APPLET_DONE)
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010662 goto out;
10663
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010664 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010665 if (!b_size(&res->buf)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010666 sc_need_room(sc, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010667 goto out;
10668 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010669
10670 /* Set the currently running flag. */
10671 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010672 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +020010673 if (!co_data(req)) {
Willy Tarreau90e8b452022-05-25 18:21:43 +020010674 applet_need_more_data(ctx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010675 goto out;
10676 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010677 }
10678
Christopher Faulet31572222023-03-31 11:13:48 +020010679 /* Execute the function. */
10680 switch (hlua_ctx_resume(hlua, 1)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010681 /* finished. */
10682 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010683 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010684 break;
10685
10686 /* yield. */
10687 case HLUA_E_AGAIN:
10688 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010689 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010690 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010691
10692 /* finished with error. */
10693 case HLUA_E_ERRMSG:
10694 /* Display log. */
10695 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010696 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010697 lua_pop(hlua->T, 1);
10698 goto error;
10699
10700 case HLUA_E_ETMOUT:
10701 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010702 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010703 goto error;
10704
10705 case HLUA_E_NOMEM:
10706 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010707 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010708 goto error;
10709
10710 case HLUA_E_YIELD: /* unexpected */
10711 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010712 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010713 goto error;
10714
10715 case HLUA_E_ERR:
10716 /* Display log. */
10717 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Christopher Faulet31572222023-03-31 11:13:48 +020010718 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010719 goto error;
10720
10721 default:
10722 goto error;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010723 }
10724
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010725 if (http_ctx->flags & APPLET_DONE) {
10726 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet31572222023-03-31 11:13:48 +020010727 goto out;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +010010728
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010729 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010730 goto error;
10731
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010732 /* no more data are expected. If the response buffer is empty
10733 * for a chunked message, be sure to add something (EOT block in
10734 * this case) to have something to send. It is important to be
10735 * sure the EOM flags will be handled by the endpoint.
10736 */
10737 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
10738 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020010739 sc_need_room(sc, sizeof(struct htx_blk)+1);
Christopher Fauletf89af9c2022-04-07 10:07:18 +020010740 goto out;
10741 }
10742 channel_add_input(res, 1);
10743 }
10744
Christopher Fauletd1ac2b92020-12-02 19:12:22 +010010745 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet31572222023-03-31 11:13:48 +020010746 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010747 strm->txn->status = http_ctx->status;
10748 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010749 }
10750
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010751 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010752 htx_to_buf(res_htx, &res->buf);
Christopher Faulet31572222023-03-31 11:13:48 +020010753 /* eat the whole request */
10754 if (co_data(req)) {
10755 req_htx = htx_from_buf(&req->buf);
10756 co_htx_skip(req, req_htx, co_data(req));
10757 htx_to_buf(req_htx, &req->buf);
10758 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010759 return;
10760
10761 error:
10762
10763 /* If we are in HTTP mode, and we are not send any
10764 * data, return a 500 server error in best effort:
10765 * if there is no room available in the buffer,
10766 * just close the connection.
10767 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010768 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +020010769 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010770
10771 channel_erase(res);
10772 res->buf.data = b_data(err);
10773 memcpy(res->buf.area, b_head(err), b_data(err));
10774 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +010010775 channel_add_input(res, res_htx->data);
Christopher Faulet31572222023-03-31 11:13:48 +020010776 se_fl_set(ctx->sedesc, SE_FL_EOI|SE_FL_EOS);
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010777 }
Christopher Faulet31572222023-03-31 11:13:48 +020010778 else
10779 se_fl_set(ctx->sedesc, SE_FL_ERROR);
10780
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010781 if (!(strm->flags & SF_ERR_MASK))
10782 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010783 http_ctx->flags |= APPLET_DONE;
Christopher Faulet31572222023-03-31 11:13:48 +020010784 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +010010785}
10786
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010787static void hlua_applet_http_release(struct appctx *ctx)
10788{
Willy Tarreauaa229cc2022-05-06 14:26:10 +020010789 struct hlua_http_ctx *http_ctx = ctx->svcctx;
10790
10791 task_destroy(http_ctx->task);
10792 http_ctx->task = NULL;
10793 hlua_ctx_destroy(http_ctx->hlua);
10794 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010795}
10796
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010797/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010798 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010799 *
10800 * This function can fail with an abort() due to an Lua critical error.
10801 * We are in the configuration parsing process of HAProxy, this abort() is
10802 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010803 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010804static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
10805 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010806{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010807 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010808 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010809
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010810 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010811 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010812 if (!rule->arg.hlua_rule) {
10813 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010814 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010815 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010816
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010817 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +020010818 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
10819 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010820 if (!rule->arg.hlua_rule->args) {
10821 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010822 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010823 }
10824
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010825 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010826 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010827
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010828 /* Expect some arguments */
10829 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010830 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010831 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +020010832 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010833 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +010010834 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010835 if (!rule->arg.hlua_rule->args[i]) {
10836 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +020010837 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010838 }
10839 (*cur_arg)++;
10840 }
10841 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010842
Thierry FOURNIER42148732015-09-02 17:17:33 +020010843 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +020010844 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +020010845 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +020010846
10847 error:
10848 if (rule->arg.hlua_rule) {
10849 if (rule->arg.hlua_rule->args) {
10850 for (i = 0; i < fcn->nargs; i++)
10851 ha_free(&rule->arg.hlua_rule->args[i]);
10852 ha_free(&rule->arg.hlua_rule->args);
10853 }
10854 ha_free(&rule->arg.hlua_rule);
10855 }
10856 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010010857}
10858
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010859static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
10860 struct act_rule *rule, char **err)
10861{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020010862 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010863
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010864 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010865 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010866 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010867 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +010010868 * the call of this analyzer.
10869 */
10870 if (rule->from != ACT_F_HTTP_REQ) {
10871 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
10872 return ACT_RET_PRS_ERR;
10873 }
10874
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010875 /* Memory for the rule. */
10876 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
10877 if (!rule->arg.hlua_rule) {
10878 memprintf(err, "out of memory error");
10879 return ACT_RET_PRS_ERR;
10880 }
10881
10882 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010010883 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010884
10885 /* TODO: later accept arguments. */
10886 rule->arg.hlua_rule->args = NULL;
10887
10888 /* Add applet pointer in the rule. */
10889 rule->applet.obj_type = OBJ_TYPE_APPLET;
10890 rule->applet.name = fcn->name;
10891 rule->applet.init = hlua_applet_http_init;
10892 rule->applet.fct = hlua_applet_http_fct;
10893 rule->applet.release = hlua_applet_http_release;
10894 rule->applet.timeout = hlua_timeout_applet;
10895
10896 return ACT_RET_PRS_OK;
10897}
10898
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010899/* This function is an LUA binding used for registering
10900 * "sample-conv" functions. It expects a converter name used
10901 * in the haproxy configuration file, and an LUA function.
10902 */
10903__LJMP static int hlua_register_action(lua_State *L)
10904{
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010905 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010906 const char *name;
10907 int ref;
10908 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010909 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010910 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010911 struct buffer *trash;
10912 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010913
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010914 /* Initialise the number of expected arguments at 0. */
10915 nargs = 0;
10916
10917 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
10918 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010919
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010010920 if (hlua_gethlua(L)) {
10921 /* runtime processing */
10922 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
10923 }
10924
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010925 /* First argument : converter name. */
10926 name = MAY_LJMP(luaL_checkstring(L, 1));
10927
10928 /* Second argument : environment. */
10929 if (lua_type(L, 2) != LUA_TTABLE)
10930 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
10931
10932 /* Third argument : lua function. */
10933 ref = MAY_LJMP(hlua_checkfunction(L, 3));
10934
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010935 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010936 if (lua_gettop(L) >= 4)
10937 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
10938
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010939 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010940 lua_pushnil(L);
10941 while (lua_next(L, 2) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010942 if (lua_type(L, -1) != LUA_TSTRING) {
10943 hlua_unref(L, ref);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010944 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010945 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010946
Thierry Fournierf67442e2020-11-28 20:41:07 +010010947 /* Check if action exists */
10948 trash = get_trash_chunk();
10949 chunk_printf(trash, "lua.%s", name);
10950 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
10951 akw = tcp_req_cont_action(trash->area);
10952 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
10953 akw = tcp_res_cont_action(trash->area);
10954 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
10955 akw = action_http_req_custom(trash->area);
10956 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
10957 akw = action_http_res_custom(trash->area);
10958 } else {
10959 akw = NULL;
10960 }
10961 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010962 fcn = akw->private;
10963 if (fcn->function_ref[hlua_state_id] != -1) {
10964 ha_warning("Trying to register action 'lua.%s' more than once. "
10965 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010010966 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010967 }
10968 fcn->function_ref[hlua_state_id] = ref;
10969
10970 /* pop the environment string. */
10971 lua_pop(L, 1);
10972 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010973 }
10974
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010975 /* Check required environment. Only accepted "http" or "tcp". */
10976 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010977 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010978 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010979 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010980 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010981 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010982 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010983
10984 /* Fill fcn. */
10985 fcn->name = strdup(name);
10986 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020010987 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +010010988 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010989
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010990 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +010010991 fcn->nargs = nargs;
10992
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010993 /* List head */
10994 akl->list.n = akl->list.p = NULL;
10995
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010996 /* action keyword. */
10997 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +020010998 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010999 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011000 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011001
11002 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11003
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011004 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011005 akl->kw[0].private = fcn;
11006 akl->kw[0].parse = action_register_lua;
11007
11008 /* select the action registering point. */
11009 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
11010 tcp_req_cont_keywords_register(akl);
11011 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
11012 tcp_res_cont_keywords_register(akl);
11013 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
11014 http_req_keywords_register(akl);
11015 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
11016 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011017 else {
11018 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011019 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011020 if (akl)
11021 ha_free((char **)&(akl->kw[0].kw));
11022 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011023 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011024 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
11025 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011026 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011027
11028 /* pop the environment string. */
11029 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011030
11031 /* reset for next loop */
11032 akl = NULL;
11033 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011034 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011035 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011036
11037 alloc_error:
11038 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011039 hlua_unref(L, ref);
Christopher Faulet4fc9da02021-04-12 15:08:12 +020011040 ha_free(&akl);
11041 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11042 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011043}
11044
11045static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
11046 struct act_rule *rule, char **err)
11047{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +020011048 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011049
Christopher Faulet280f85b2019-07-15 15:02:04 +020011050 if (px->mode == PR_MODE_HTTP) {
11051 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +010011052 return ACT_RET_PRS_ERR;
11053 }
11054
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011055 /* Memory for the rule. */
11056 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
11057 if (!rule->arg.hlua_rule) {
11058 memprintf(err, "out of memory error");
11059 return ACT_RET_PRS_ERR;
11060 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011061
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011062 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +010011063 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011064
11065 /* TODO: later accept arguments. */
11066 rule->arg.hlua_rule->args = NULL;
11067
11068 /* Add applet pointer in the rule. */
11069 rule->applet.obj_type = OBJ_TYPE_APPLET;
11070 rule->applet.name = fcn->name;
11071 rule->applet.init = hlua_applet_tcp_init;
11072 rule->applet.fct = hlua_applet_tcp_fct;
11073 rule->applet.release = hlua_applet_tcp_release;
11074 rule->applet.timeout = hlua_timeout_applet;
11075
11076 return 0;
11077}
11078
11079/* This function is an LUA binding used for registering
11080 * "sample-conv" functions. It expects a converter name used
11081 * in the haproxy configuration file, and an LUA function.
11082 */
11083__LJMP static int hlua_register_service(lua_State *L)
11084{
11085 struct action_kw_list *akl;
11086 const char *name;
11087 const char *env;
11088 int ref;
11089 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011090 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011091 struct buffer *trash;
11092 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011093
11094 MAY_LJMP(check_args(L, 3, "register_service"));
11095
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011096 if (hlua_gethlua(L)) {
11097 /* runtime processing */
11098 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
11099 }
11100
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011101 /* First argument : converter name. */
11102 name = MAY_LJMP(luaL_checkstring(L, 1));
11103
11104 /* Second argument : environment. */
11105 env = MAY_LJMP(luaL_checkstring(L, 2));
11106
11107 /* Third argument : lua function. */
11108 ref = MAY_LJMP(hlua_checkfunction(L, 3));
11109
Thierry Fournierf67442e2020-11-28 20:41:07 +010011110 /* Check for service already registered */
11111 trash = get_trash_chunk();
11112 chunk_printf(trash, "lua.%s", name);
11113 akw = service_find(trash->area);
11114 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011115 fcn = akw->private;
11116 if (fcn->function_ref[hlua_state_id] != -1) {
11117 ha_warning("Trying to register service 'lua.%s' more than once. "
11118 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011119 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011120 }
11121 fcn->function_ref[hlua_state_id] = ref;
11122 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011123 }
11124
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011125 /* Allocate and fill the sample fetch keyword struct. */
11126 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
11127 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011128 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011129 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011130 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011131 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011132
11133 /* Fill fcn. */
11134 len = strlen("<lua.>") + strlen(name) + 1;
11135 fcn->name = calloc(1, len);
11136 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011137 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011138 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010011139 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011140
11141 /* List head */
11142 akl->list.n = akl->list.p = NULL;
11143
11144 /* converter keyword. */
11145 len = strlen("lua.") + strlen(name) + 1;
11146 akl->kw[0].kw = calloc(1, len);
11147 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020011148 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011149
11150 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
11151
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010011152 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011153 if (strcmp(env, "tcp") == 0)
11154 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011155 else if (strcmp(env, "http") == 0)
11156 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011157 else {
11158 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011159 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011160 if (akl)
11161 ha_free((char **)&(akl->kw[0].kw));
11162 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010011163 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010011164 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020011165 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011166
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020011167 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011168 akl->kw[0].private = fcn;
11169
11170 /* End of array. */
11171 memset(&akl->kw[1], 0, sizeof(*akl->kw));
11172
11173 /* Register this new converter */
11174 service_keywords_register(akl);
11175
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011176 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020011177
11178 alloc_error:
11179 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011180 hlua_unref(L, ref);
Christopher Faulet5c028d72021-04-12 15:11:44 +020011181 ha_free(&akl);
11182 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11183 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020011184}
11185
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011186/* This function initialises Lua cli handler. It copies the
11187 * arguments in the Lua stack and create channel IO objects.
11188 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020011189static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011190{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011191 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011192 struct hlua *hlua;
11193 struct hlua_function *fcn;
11194 int i;
11195 const char *error;
11196
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011197 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011198 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011199
Willy Tarreaubafbe012017-11-24 17:34:44 +010011200 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011201 if (!hlua) {
11202 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011203 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010011204 }
11205 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011206 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011207
11208 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050011209 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011210 * applet_http. It is absolutely compatible.
11211 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011212 ctx->task = task_new_here();
11213 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010011214 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011215 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011216 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011217 ctx->task->nice = 0;
11218 ctx->task->context = appctx;
11219 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011220
11221 /* Initialises the Lua context */
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011222 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011223 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010011224 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011225 }
11226
11227 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011228 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011229 if (lua_type(hlua->T, -1) == LUA_TSTRING)
11230 error = lua_tostring(hlua->T, -1);
11231 else
11232 error = "critical error";
11233 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
11234 goto error;
11235 }
11236
11237 /* Check stack available size. */
11238 if (!lua_checkstack(hlua->T, 2)) {
11239 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11240 goto error;
11241 }
11242
11243 /* Restore the function in the stack. */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011244 hlua_pushref(hlua->T, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011245
11246 /* Once the arguments parsed, the CLI is like an AppletTCP,
11247 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011248 */
11249 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
11250 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11251 goto error;
11252 }
11253 hlua->nargs = 1;
11254
11255 /* push keywords in the stack. */
11256 for (i = 0; *args[i]; i++) {
11257 /* Check stack available size. */
11258 if (!lua_checkstack(hlua->T, 1)) {
11259 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
11260 goto error;
11261 }
11262 lua_pushstring(hlua->T, args[i]);
11263 hlua->nargs++;
11264 }
11265
11266 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011267 hlua_timer_init(&hlua->timer, hlua_timeout_session);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011268
11269 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011270 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011271
11272 /* It's ok */
11273 return 0;
11274
11275 /* It's not ok. */
11276error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010011277 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011278 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011279 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011280 return 1;
11281}
11282
11283static int hlua_cli_io_handler_fct(struct appctx *appctx)
11284{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011285 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011286 struct hlua *hlua;
Willy Tarreau475e4632022-05-27 10:26:46 +020011287 struct stconn *sc;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011288 struct hlua_function *fcn;
11289
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011290 hlua = ctx->hlua;
Willy Tarreauc12b3212022-05-27 11:08:15 +020011291 sc = appctx_sc(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011292 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011293
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011294 /* Execute the function. */
11295 switch (hlua_ctx_resume(hlua, 1)) {
11296
11297 /* finished. */
11298 case HLUA_E_OK:
11299 return 1;
11300
11301 /* yield. */
11302 case HLUA_E_AGAIN:
11303 /* We want write. */
11304 if (HLUA_IS_WAKERESWR(hlua))
Christopher Faulet7b3d38a2023-05-05 11:28:45 +020011305 sc_need_room(sc, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011306 /* Set the timeout. */
11307 if (hlua->wake_time != TICK_ETERNITY)
11308 task_schedule(hlua->task, hlua->wake_time);
11309 return 0;
11310
11311 /* finished with error. */
11312 case HLUA_E_ERRMSG:
11313 /* Display log. */
11314 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
11315 fcn->name, lua_tostring(hlua->T, -1));
11316 lua_pop(hlua->T, 1);
11317 return 1;
11318
Thierry Fournierd5b073c2018-05-21 19:42:47 +020011319 case HLUA_E_ETMOUT:
11320 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
11321 fcn->name);
11322 return 1;
11323
11324 case HLUA_E_NOMEM:
11325 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
11326 fcn->name);
11327 return 1;
11328
11329 case HLUA_E_YIELD: /* unexpected */
11330 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
11331 fcn->name);
11332 return 1;
11333
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011334 case HLUA_E_ERR:
11335 /* Display log. */
11336 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
11337 fcn->name);
11338 return 1;
11339
11340 default:
11341 return 1;
11342 }
11343
11344 return 1;
11345}
11346
11347static void hlua_cli_io_release_fct(struct appctx *appctx)
11348{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020011349 struct hlua_cli_ctx *ctx = appctx->svcctx;
11350
11351 hlua_ctx_destroy(ctx->hlua);
11352 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011353}
11354
11355/* This function is an LUA binding used for registering
11356 * new keywords in the cli. It expects a list of keywords
11357 * which are the "path". It is limited to 5 keywords. A
11358 * description of the command, a function to be executed
11359 * for the parsing and a function for io handlers.
11360 */
11361__LJMP static int hlua_register_cli(lua_State *L)
11362{
11363 struct cli_kw_list *cli_kws;
11364 const char *message;
11365 int ref_io;
11366 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011367 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011368 int index;
11369 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011370 struct buffer *trash;
11371 const char *kw[5];
11372 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011373 const char *errmsg;
Willy Tarreau22450af2023-04-07 15:27:55 +020011374 char *end;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011375
11376 MAY_LJMP(check_args(L, 3, "register_cli"));
11377
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010011378 if (hlua_gethlua(L)) {
11379 /* runtime processing */
11380 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
11381 }
11382
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011383 /* First argument : an array of maximum 5 keywords. */
11384 if (!lua_istable(L, 1))
11385 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
11386
11387 /* Second argument : string with contextual message. */
11388 message = MAY_LJMP(luaL_checkstring(L, 2));
11389
11390 /* Third and fourth argument : lua function. */
11391 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
11392
Thierry Fournierf67442e2020-11-28 20:41:07 +010011393 /* Check for CLI service already registered */
11394 trash = get_trash_chunk();
11395 index = 0;
11396 lua_pushnil(L);
11397 memset(kw, 0, sizeof(kw));
11398 while (lua_next(L, 1) != 0) {
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011399 if (index >= CLI_PREFIX_KW_NB) {
11400 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011401 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 +010011402 }
11403 if (lua_type(L, -1) != LUA_TSTRING) {
11404 hlua_unref(L, ref_io);
Thierry Fournierf67442e2020-11-28 20:41:07 +010011405 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011406 }
Thierry Fournierf67442e2020-11-28 20:41:07 +010011407 kw[index] = lua_tostring(L, -1);
11408 if (index == 0)
11409 chunk_printf(trash, "%s", kw[index]);
11410 else
11411 chunk_appendf(trash, " %s", kw[index]);
11412 index++;
11413 lua_pop(L, 1);
11414 }
11415 cli_kw = cli_find_kw_exact((char **)kw);
11416 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010011417 fcn = cli_kw->private;
11418 if (fcn->function_ref[hlua_state_id] != -1) {
11419 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
11420 "This will become a hard error in version 2.5.\n", trash->area);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011421 hlua_unref(L, fcn->function_ref[hlua_state_id]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011422 }
11423 fcn->function_ref[hlua_state_id] = ref_io;
11424 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010011425 }
11426
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011427 /* Allocate and fill the sample fetch keyword struct. */
11428 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011429 if (!cli_kws) {
11430 errmsg = "Lua out of memory error.";
11431 goto error;
11432 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010011433 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011434 if (!fcn) {
11435 errmsg = "Lua out of memory error.";
11436 goto error;
11437 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011438
11439 /* Fill path. */
11440 index = 0;
11441 lua_pushnil(L);
11442 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011443 if (index >= 5) {
11444 errmsg = "1st argument must be a table with a maximum of 5 entries";
11445 goto error;
11446 }
11447 if (lua_type(L, -1) != LUA_TSTRING) {
11448 errmsg = "1st argument must be a table filled with strings";
11449 goto error;
11450 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011451 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011452 if (!cli_kws->kw[0].str_kw[index]) {
11453 errmsg = "Lua out of memory error.";
11454 goto error;
11455 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011456 index++;
11457 lua_pop(L, 1);
11458 }
11459
11460 /* Copy help message. */
11461 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011462 if (!cli_kws->kw[0].usage) {
11463 errmsg = "Lua out of memory error.";
11464 goto error;
11465 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011466
11467 /* Fill fcn io handler. */
11468 len = strlen("<lua.cli>") + 1;
11469 for (i = 0; i < index; i++)
11470 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
11471 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011472 if (!fcn->name) {
11473 errmsg = "Lua out of memory error.";
11474 goto error;
11475 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011476
11477 end = fcn->name;
11478 len = 8;
11479 memcpy(end, "<lua.cli", len);
11480 end += len;
11481
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011482 for (i = 0; i < index; i++) {
Willy Tarreau22450af2023-04-07 15:27:55 +020011483 *(end++) = '.';
11484 len = strlen(cli_kws->kw[0].str_kw[i]);
11485 memcpy(end, cli_kws->kw[0].str_kw[i], len);
11486 end += len;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011487 }
Willy Tarreau22450af2023-04-07 15:27:55 +020011488 *(end++) = '>';
11489 *(end++) = 0;
11490
Thierry Fournierc7492592020-11-28 23:57:24 +010011491 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011492
11493 /* Fill last entries. */
11494 cli_kws->kw[0].private = fcn;
11495 cli_kws->kw[0].parse = hlua_cli_parse_fct;
11496 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
11497 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
11498
11499 /* Register this new converter */
11500 cli_register_kw(cli_kws);
11501
11502 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011503
11504 error:
11505 release_hlua_function(fcn);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010011506 hlua_unref(L, ref_io);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020011507 if (cli_kws) {
11508 for (i = 0; i < index; i++)
11509 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
11510 ha_free((char **)&(cli_kws->kw[0].usage));
11511 }
11512 ha_free(&cli_kws);
11513 WILL_LJMP(luaL_error(L, errmsg));
11514 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010011515}
11516
Christopher Faulet69c581a2021-05-31 08:54:04 +020011517static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
11518{
11519 struct hlua_flt_config *conf = fconf->conf;
11520 lua_State *L;
11521 int error, pos, state_id, flt_ref;
11522
11523 state_id = reg_flt_to_stack_id(conf->reg);
11524 L = hlua_states[state_id];
11525 pos = lua_gettop(L);
11526
11527 /* The filter parsing function */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011528 hlua_pushref(L, conf->reg->fun_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011529
11530 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011531 hlua_pushref(L, conf->reg->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011532
11533 /* Duplicate the filter class so each filter will have its own copy */
11534 lua_newtable(L);
11535 lua_pushnil(L);
11536
11537 while (lua_next(L, pos+2)) {
11538 lua_pushvalue(L, -2);
11539 lua_insert(L, -2);
11540 lua_settable(L, -4);
11541 }
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011542 flt_ref = hlua_ref(L);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011543
11544 /* Remove the original lua filter class from the stack */
11545 lua_pop(L, 1);
11546
11547 /* Push the copy on the stack */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011548 hlua_pushref(L, flt_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011549
11550 /* extra args are pushed in a table */
11551 lua_newtable(L);
11552 for (pos = 0; conf->args[pos]; pos++) {
11553 /* Check stack available size. */
11554 if (!lua_checkstack(L, 1)) {
11555 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
11556 goto error;
11557 }
11558 lua_pushstring(L, conf->args[pos]);
11559 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
11560 }
11561
11562 error = lua_pcall(L, 2, LUA_MULTRET, 0);
11563 switch (error) {
11564 case LUA_OK:
11565 /* replace the filter ref */
11566 conf->ref[state_id] = flt_ref;
11567 break;
11568 case LUA_ERRRUN:
11569 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
11570 goto error;
11571 case LUA_ERRMEM:
11572 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
11573 goto error;
11574 case LUA_ERRERR:
11575 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
11576 goto error;
11577#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
11578 case LUA_ERRGCMM:
11579 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
11580 goto error;
11581#endif
11582 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011583 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020011584 goto error;
11585 }
11586
11587 lua_settop(L, 0);
11588 return 0;
11589
11590 error:
11591 lua_settop(L, 0);
11592 return -1;
11593}
11594
11595static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
11596{
11597 struct hlua_flt_config *conf = fconf->conf;
11598 lua_State *L;
11599 int state_id;
11600
11601 if (!conf)
11602 return;
11603
11604 state_id = reg_flt_to_stack_id(conf->reg);
11605 L = hlua_states[state_id];
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011606 hlua_unref(L, conf->ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011607}
11608
11609static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
11610{
11611 struct hlua_flt_config *conf = fconf->conf;
11612 int state_id = reg_flt_to_stack_id(conf->reg);
11613
11614 /* Rely on per-thread init for global scripts */
11615 if (!state_id)
11616 return hlua_filter_init_per_thread(px, fconf);
11617 return 0;
11618}
11619
11620static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
11621{
11622
11623 if (fconf->conf) {
11624 struct hlua_flt_config *conf = fconf->conf;
11625 int state_id = reg_flt_to_stack_id(conf->reg);
11626 int pos;
11627
11628 /* Rely on per-thread deinit for global scripts */
11629 if (!state_id)
11630 hlua_filter_deinit_per_thread(px, fconf);
11631
11632 for (pos = 0; conf->args[pos]; pos++)
11633 free(conf->args[pos]);
11634 free(conf->args);
11635 }
11636 ha_free(&fconf->conf);
11637 ha_free((char **)&fconf->id);
11638 ha_free(&fconf->ops);
11639}
11640
11641static int hlua_filter_new(struct stream *s, struct filter *filter)
11642{
11643 struct hlua_flt_config *conf = FLT_CONF(filter);
11644 struct hlua_flt_ctx *flt_ctx = NULL;
11645 int ret = 1;
11646
11647 /* In the execution wrappers linked with a stream, the
11648 * Lua context can be not initialized. This behavior
11649 * permits to save performances because a systematic
11650 * Lua initialization cause 5% performances loss.
11651 */
11652 if (!s->hlua) {
11653 struct hlua *hlua;
11654
11655 hlua = pool_alloc(pool_head_hlua);
11656 if (!hlua) {
11657 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11658 conf->reg->name);
11659 ret = 0;
11660 goto end;
11661 }
11662 HLUA_INIT(hlua);
11663 s->hlua = hlua;
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011664 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011665 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
11666 conf->reg->name);
11667 ret = 0;
11668 goto end;
11669 }
11670 }
11671
11672 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
11673 if (!flt_ctx) {
11674 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11675 conf->reg->name);
11676 ret = 0;
11677 goto end;
11678 }
11679 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
11680 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
11681 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
11682 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11683 conf->reg->name);
11684 ret = 0;
11685 goto end;
11686 }
11687 HLUA_INIT(flt_ctx->hlua[0]);
11688 HLUA_INIT(flt_ctx->hlua[1]);
Aurelien DARRAGON6b0b9bd2023-03-21 14:02:16 +010011689 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task) ||
11690 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task)) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020011691 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
11692 conf->reg->name);
11693 ret = 0;
11694 goto end;
11695 }
11696
11697 if (!HLUA_IS_RUNNING(s->hlua)) {
11698 /* The following Lua calls can fail. */
11699 if (!SET_SAFE_LJMP(s->hlua)) {
11700 const char *error;
11701
11702 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
11703 error = lua_tostring(s->hlua->T, -1);
11704 else
11705 error = "critical error";
11706 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11707 ret = 0;
11708 goto end;
11709 }
11710
11711 /* Check stack size. */
11712 if (!lua_checkstack(s->hlua->T, 1)) {
11713 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020011714 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011715 ret = 0;
11716 goto end;
11717 }
11718
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011719 hlua_pushref(s->hlua->T, conf->ref[s->hlua->state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011720 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
11721 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
11722 conf->reg->name);
11723 RESET_SAFE_LJMP(s->hlua);
11724 ret = 0;
11725 goto end;
11726 }
11727 lua_insert(s->hlua->T, -2);
11728
11729 /* Push the copy on the stack */
11730 s->hlua->nargs = 1;
11731
11732 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011733 hlua_timer_init(&s->hlua->timer, hlua_timeout_session);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011734
11735 /* At this point the execution is safe. */
11736 RESET_SAFE_LJMP(s->hlua);
11737 }
11738
11739 switch (hlua_ctx_resume(s->hlua, 0)) {
11740 case HLUA_E_OK:
11741 /* Nothing returned or not a table, ignore the filter for current stream */
11742 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
11743 ret = 0;
11744 goto end;
11745 }
11746
11747 /* Attached the filter pointer to the ctx */
11748 lua_pushstring(s->hlua->T, "__filter");
11749 lua_pushlightuserdata(s->hlua->T, filter);
11750 lua_settable(s->hlua->T, -3);
11751
11752 /* Save a ref on the filter ctx */
11753 lua_pushvalue(s->hlua->T, 1);
Aurelien DARRAGON73d1a982023-03-20 17:42:08 +010011754 flt_ctx->ref = hlua_ref(s->hlua->T);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011755 filter->ctx = flt_ctx;
11756 break;
11757 case HLUA_E_ERRMSG:
11758 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
11759 ret = -1;
11760 goto end;
11761 case HLUA_E_ETMOUT:
11762 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
11763 ret = 0;
11764 goto end;
11765 case HLUA_E_NOMEM:
11766 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11767 ret = 0;
11768 goto end;
11769 case HLUA_E_AGAIN:
11770 case HLUA_E_YIELD:
11771 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11772 " are not allowed from 'new' function.\n", conf->reg->name);
11773 ret = 0;
11774 goto end;
11775 case HLUA_E_ERR:
11776 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
11777 ret = 0;
11778 goto end;
11779 default:
11780 ret = 0;
11781 goto end;
11782 }
11783
11784 end:
11785 if (s->hlua)
11786 lua_settop(s->hlua->T, 0);
11787 if (ret <= 0) {
11788 if (flt_ctx) {
11789 hlua_ctx_destroy(flt_ctx->hlua[0]);
11790 hlua_ctx_destroy(flt_ctx->hlua[1]);
11791 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11792 }
11793 }
11794 return ret;
11795}
11796
11797static void hlua_filter_delete(struct stream *s, struct filter *filter)
11798{
11799 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11800
Aurelien DARRAGONfde199d2023-03-20 15:09:33 +010011801 hlua_unref(s->hlua->T, flt_ctx->ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011802 hlua_ctx_destroy(flt_ctx->hlua[0]);
11803 hlua_ctx_destroy(flt_ctx->hlua[1]);
11804 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
11805 filter->ctx = NULL;
11806}
11807
Christopher Faulet9f55a502020-02-25 15:21:02 +010011808static int hlua_filter_from_payload(struct filter *filter)
11809{
11810 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11811
11812 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
11813}
11814
Christopher Fauletc404f112020-02-26 15:03:09 +010011815static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
11816 int dir, unsigned int flags)
11817{
11818 struct hlua *flt_hlua;
11819 struct hlua_flt_config *conf = FLT_CONF(filter);
11820 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11821 unsigned int hflags = HLUA_TXN_FLT_CTX;
11822 int ret = 1;
11823
11824 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
11825 if (!flt_hlua)
11826 goto end;
11827
11828 if (!HLUA_IS_RUNNING(flt_hlua)) {
11829 int extra_idx = lua_gettop(flt_hlua->T);
11830
11831 /* The following Lua calls can fail. */
11832 if (!SET_SAFE_LJMP(flt_hlua)) {
11833 const char *error;
11834
11835 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
11836 error = lua_tostring(flt_hlua->T, -1);
11837 else
11838 error = "critical error";
11839 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
11840 goto end;
11841 }
11842
11843 /* Check stack size. */
11844 if (!lua_checkstack(flt_hlua->T, 3)) {
11845 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11846 RESET_SAFE_LJMP(flt_hlua);
11847 goto end;
11848 }
11849
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010011850 hlua_pushref(flt_hlua->T, flt_ctx->ref);
Christopher Fauletc404f112020-02-26 15:03:09 +010011851 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
11852 RESET_SAFE_LJMP(flt_hlua);
11853 goto end;
11854 }
11855 lua_insert(flt_hlua->T, -2);
11856
11857 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
11858 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11859 RESET_SAFE_LJMP(flt_hlua);
11860 goto end;
11861 }
11862 flt_hlua->nargs = 2;
11863
11864 if (flags & HLUA_FLT_CB_ARG_CHN) {
11865 if (dir == SMP_OPT_DIR_REQ)
11866 lua_getfield(flt_hlua->T, -1, "req");
11867 else
11868 lua_getfield(flt_hlua->T, -1, "res");
11869 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11870 lua_pushstring(flt_hlua->T, "__filter");
11871 lua_pushlightuserdata(flt_hlua->T, filter);
11872 lua_settable(flt_hlua->T, -3);
11873 }
11874 flt_hlua->nargs++;
11875 }
11876 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011877 if (dir == SMP_OPT_DIR_REQ)
11878 lua_getfield(flt_hlua->T, -1, "http_req");
11879 else
11880 lua_getfield(flt_hlua->T, -1, "http_res");
11881 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
11882 lua_pushstring(flt_hlua->T, "__filter");
11883 lua_pushlightuserdata(flt_hlua->T, filter);
11884 lua_settable(flt_hlua->T, -3);
11885 }
11886 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010011887 }
11888
11889 /* Check stack size. */
11890 if (!lua_checkstack(flt_hlua->T, 1)) {
11891 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
11892 RESET_SAFE_LJMP(flt_hlua);
11893 goto end;
11894 }
11895
11896 while (extra_idx--) {
11897 lua_pushvalue(flt_hlua->T, 1);
11898 lua_remove(flt_hlua->T, 1);
11899 flt_hlua->nargs++;
11900 }
11901
11902 /* We must initialize the execution timeouts. */
Aurelien DARRAGONda9503c2022-11-25 09:10:07 +010011903 hlua_timer_init(&flt_hlua->timer, hlua_timeout_session);
Christopher Fauletc404f112020-02-26 15:03:09 +010011904
11905 /* At this point the execution is safe. */
11906 RESET_SAFE_LJMP(flt_hlua);
11907 }
11908
11909 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
11910 case HLUA_E_OK:
11911 /* Catch the return value if it required */
11912 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
11913 ret = lua_tointeger(flt_hlua->T, -1);
11914 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
11915 }
11916
11917 /* Set timeout in the required channel. */
11918 if (flt_hlua->wake_time != TICK_ETERNITY) {
11919 if (dir == SMP_OPT_DIR_REQ)
11920 s->req.analyse_exp = flt_hlua->wake_time;
11921 else
11922 s->res.analyse_exp = flt_hlua->wake_time;
11923 }
11924 break;
11925 case HLUA_E_AGAIN:
11926 /* Set timeout in the required channel. */
11927 if (flt_hlua->wake_time != TICK_ETERNITY) {
11928 if (dir == SMP_OPT_DIR_REQ)
11929 s->req.analyse_exp = flt_hlua->wake_time;
11930 else
11931 s->res.analyse_exp = flt_hlua->wake_time;
11932 }
11933 /* Some actions can be wake up when a "write" event
11934 * is detected on a response channel. This is useful
11935 * only for actions targeted on the requests.
11936 */
11937 if (HLUA_IS_WAKERESWR(flt_hlua))
11938 s->res.flags |= CF_WAKE_WRITE;
11939 if (HLUA_IS_WAKEREQWR(flt_hlua))
11940 s->req.flags |= CF_WAKE_WRITE;
11941 ret = 0;
11942 goto end;
11943 case HLUA_E_ERRMSG:
11944 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
11945 ret = -1;
11946 goto end;
11947 case HLUA_E_ETMOUT:
11948 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
11949 goto end;
11950 case HLUA_E_NOMEM:
11951 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
11952 goto end;
11953 case HLUA_E_YIELD:
11954 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
11955 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
11956 goto end;
11957 case HLUA_E_ERR:
11958 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
11959 goto end;
11960 default:
11961 goto end;
11962 }
11963
11964
11965 end:
11966 return ret;
11967}
11968
11969static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11970{
11971 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11972
11973 flt_ctx->flags = 0;
11974 return hlua_filter_callback(s, filter, "start_analyze",
11975 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11976 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11977}
11978
11979static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
11980{
11981 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11982
11983 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11984 return hlua_filter_callback(s, filter, "end_analyze",
11985 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11986 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
11987}
11988
Christopher Fauleteae8afa2020-02-26 17:15:48 +010011989static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
11990{
11991 struct hlua_flt_ctx *flt_ctx = filter->ctx;
11992
11993 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
11994 return hlua_filter_callback(s, filter, "http_headers",
11995 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
11996 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
11997}
11998
11999static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
12000 unsigned int offset, unsigned int len)
12001{
12002 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12003 struct hlua *flt_hlua;
12004 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
12005 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
12006 int ret;
12007
12008 flt_hlua = flt_ctx->hlua[idx];
12009 flt_ctx->cur_off[idx] = offset;
12010 flt_ctx->cur_len[idx] = len;
12011 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
12012 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12013 if (ret != -1) {
12014 ret = flt_ctx->cur_len[idx];
12015 if (lua_gettop(flt_hlua->T) > 0) {
12016 ret = lua_tointeger(flt_hlua->T, -1);
12017 if (ret > flt_ctx->cur_len[idx])
12018 ret = flt_ctx->cur_len[idx];
12019 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12020 }
12021 }
12022 return ret;
12023}
12024
12025static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
12026{
12027 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12028
12029 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
12030 return hlua_filter_callback(s, filter, "http_end",
12031 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
12032 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
12033}
12034
Christopher Fauletc404f112020-02-26 15:03:09 +010012035static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
12036 unsigned int offset, unsigned int len)
12037{
12038 struct hlua_flt_ctx *flt_ctx = filter->ctx;
12039 struct hlua *flt_hlua;
12040 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
12041 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
12042 int ret;
12043
12044 flt_hlua = flt_ctx->hlua[idx];
12045 flt_ctx->cur_off[idx] = offset;
12046 flt_ctx->cur_len[idx] = len;
12047 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
12048 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
12049 if (ret != -1) {
12050 ret = flt_ctx->cur_len[idx];
12051 if (lua_gettop(flt_hlua->T) > 0) {
12052 ret = lua_tointeger(flt_hlua->T, -1);
12053 if (ret > flt_ctx->cur_len[idx])
12054 ret = flt_ctx->cur_len[idx];
12055 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
12056 }
12057 }
12058 return ret;
12059}
12060
Christopher Faulet69c581a2021-05-31 08:54:04 +020012061static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
12062 struct flt_conf *fconf, char **err, void *private)
12063{
12064 struct hlua_reg_filter *reg_flt = private;
12065 lua_State *L;
12066 struct hlua_flt_config *conf = NULL;
12067 const char *flt_id = NULL;
12068 int state_id, pos, flt_flags = 0;
12069 struct flt_ops *hlua_flt_ops = NULL;
12070
12071 state_id = reg_flt_to_stack_id(reg_flt);
12072 L = hlua_states[state_id];
12073
12074 /* Initialize the filter ops with default callbacks */
12075 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012076 if (!hlua_flt_ops)
12077 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012078 hlua_flt_ops->init = hlua_filter_init;
12079 hlua_flt_ops->deinit = hlua_filter_deinit;
12080 if (state_id) {
12081 /* Set per-thread callback if script is loaded per-thread */
12082 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
12083 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
12084 }
12085 hlua_flt_ops->attach = hlua_filter_new;
12086 hlua_flt_ops->detach = hlua_filter_delete;
12087
12088 /* Push the filter class on the stack and resolve all callbacks */
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012089 hlua_pushref(L, reg_flt->flt_ref[state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012090
Christopher Fauletc404f112020-02-26 15:03:09 +010012091 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
12092 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
12093 lua_pop(L, 1);
12094 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
12095 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
12096 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010012097 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
12098 hlua_flt_ops->http_headers = hlua_filter_http_headers;
12099 lua_pop(L, 1);
12100 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
12101 hlua_flt_ops->http_payload = hlua_filter_http_payload;
12102 lua_pop(L, 1);
12103 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
12104 hlua_flt_ops->http_end = hlua_filter_http_end;
12105 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010012106 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
12107 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
12108 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012109
12110 /* Get id and flags of the filter class */
12111 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
12112 flt_id = lua_tostring(L, -1);
12113 lua_pop(L, 1);
12114 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
12115 flt_flags = lua_tointeger(L, -1);
12116 lua_pop(L, 1);
12117
12118 /* Create the filter config */
12119 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012120 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020012121 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012122 conf->reg = reg_flt;
12123
12124 /* duplicate args */
12125 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
12126 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020012127 if (!conf->args)
12128 goto error;
12129 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020012130 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012131 if (!conf->args[pos])
12132 goto error;
12133 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012134 conf->args[pos] = NULL;
12135 *cur_arg += pos + 1;
12136
Christopher Fauletc86bb872021-08-13 08:33:57 +020012137 if (flt_id) {
12138 fconf->id = strdup(flt_id);
12139 if (!fconf->id)
12140 goto error;
12141 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012142 fconf->flags = flt_flags;
12143 fconf->conf = conf;
12144 fconf->ops = hlua_flt_ops;
12145
12146 lua_settop(L, 0);
12147 return 0;
12148
12149 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020012150 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012151 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012152 if (conf && conf->args) {
12153 for (pos = 0; conf->args[pos]; pos++)
12154 free(conf->args[pos]);
12155 free(conf->args);
12156 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020012157 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020012158 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012159 lua_settop(L, 0);
12160 return -1;
12161}
12162
Christopher Fauletc404f112020-02-26 15:03:09 +010012163__LJMP static int hlua_register_data_filter(lua_State *L)
12164{
12165 struct filter *filter;
12166 struct channel *chn;
12167
12168 MAY_LJMP(check_args(L, 2, "register_data_filter"));
12169 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12170 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12171
12172 lua_getfield(L, 1, "__filter");
12173 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12174 filter = lua_touserdata (L, -1);
12175 lua_pop(L, 1);
12176
12177 register_data_filter(chn_strm(chn), chn, filter);
12178 return 1;
12179}
12180
12181__LJMP static int hlua_unregister_data_filter(lua_State *L)
12182{
12183 struct filter *filter;
12184 struct channel *chn;
12185
12186 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
12187 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
12188 chn = MAY_LJMP(hlua_checkchannel(L, 2));
12189
12190 lua_getfield(L, 1, "__filter");
12191 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
12192 filter = lua_touserdata (L, -1);
12193 lua_pop(L, 1);
12194
12195 unregister_data_filter(chn_strm(chn), chn, filter);
12196 return 1;
12197}
12198
Christopher Faulet69c581a2021-05-31 08:54:04 +020012199/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012200 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020012201 * parse configuration arguments.
12202 */
12203__LJMP static int hlua_register_filter(lua_State *L)
12204{
12205 struct buffer *trash;
12206 struct flt_kw_list *fkl;
12207 struct flt_kw *fkw;
12208 const char *name;
12209 struct hlua_reg_filter *reg_flt= NULL;
12210 int flt_ref, fun_ref;
12211 int len;
12212
12213 MAY_LJMP(check_args(L, 3, "register_filter"));
12214
Aurelien DARRAGON87f52972023-02-24 09:43:54 +010012215 if (hlua_gethlua(L)) {
12216 /* runtime processing */
12217 WILL_LJMP(luaL_error(L, "register_filter: not available outside of body context"));
12218 }
12219
Christopher Faulet69c581a2021-05-31 08:54:04 +020012220 /* First argument : filter name. */
12221 name = MAY_LJMP(luaL_checkstring(L, 1));
12222
12223 /* Second argument : The filter class */
12224 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
12225
12226 /* Third argument : lua function. */
12227 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
12228
12229 trash = get_trash_chunk();
12230 chunk_printf(trash, "lua.%s", name);
12231 fkw = flt_find_kw(trash->area);
12232 if (fkw != NULL) {
12233 reg_flt = fkw->private;
12234 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
12235 ha_warning("Trying to register filter 'lua.%s' more than once. "
12236 "This will become a hard error in version 2.5.\n", name);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012237 if (reg_flt->flt_ref[hlua_state_id] != -1)
12238 hlua_unref(L, reg_flt->flt_ref[hlua_state_id]);
12239 if (reg_flt->fun_ref[hlua_state_id] != -1)
12240 hlua_unref(L, reg_flt->fun_ref[hlua_state_id]);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012241 }
12242 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12243 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12244 return 0;
12245 }
12246
12247 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
12248 if (!fkl)
12249 goto alloc_error;
12250 fkl->scope = "HLUA";
12251
12252 reg_flt = new_hlua_reg_filter(name);
12253 if (!reg_flt)
12254 goto alloc_error;
12255
12256 reg_flt->flt_ref[hlua_state_id] = flt_ref;
12257 reg_flt->fun_ref[hlua_state_id] = fun_ref;
12258
12259 /* The filter keyword */
12260 len = strlen("lua.") + strlen(name) + 1;
12261 fkl->kw[0].kw = calloc(1, len);
12262 if (!fkl->kw[0].kw)
12263 goto alloc_error;
12264
12265 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
12266
12267 fkl->kw[0].parse = hlua_filter_parse_fct;
12268 fkl->kw[0].private = reg_flt;
12269 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
12270
12271 /* Register this new filter */
12272 flt_register_keywords(fkl);
12273
12274 return 0;
12275
12276 alloc_error:
12277 release_hlua_reg_filter(reg_flt);
Aurelien DARRAGON55afbed2023-03-02 18:42:06 +010012278 hlua_unref(L, flt_ref);
12279 hlua_unref(L, fun_ref);
Christopher Faulet69c581a2021-05-31 08:54:04 +020012280 ha_free(&fkl);
12281 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
12282 return 0; /* Never reached */
12283}
12284
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012285static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012286 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012287 char **err, unsigned int *timeout)
12288{
12289 const char *error;
12290
12291 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020012292 if (error == PARSE_TIME_OVER) {
12293 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
12294 args[1], args[0]);
12295 return -1;
12296 }
12297 else if (error == PARSE_TIME_UNDER) {
12298 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
12299 args[1], args[0]);
12300 return -1;
12301 }
12302 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012303 memprintf(err, "%s: invalid timeout", args[0]);
12304 return -1;
12305 }
12306 return 0;
12307}
12308
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012309static int hlua_burst_timeout(char **args, int section_type, struct proxy *curpx,
12310 const struct proxy *defpx, const char *file, int line,
12311 char **err)
12312{
12313 return hlua_read_timeout(args, section_type, curpx, defpx,
12314 file, line, err, &hlua_timeout_burst);
12315}
12316
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012317static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012318 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012319 char **err)
12320{
12321 return hlua_read_timeout(args, section_type, curpx, defpx,
12322 file, line, err, &hlua_timeout_session);
12323}
12324
12325static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012326 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012327 char **err)
12328{
12329 return hlua_read_timeout(args, section_type, curpx, defpx,
12330 file, line, err, &hlua_timeout_task);
12331}
12332
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012333static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012334 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012335 char **err)
12336{
12337 return hlua_read_timeout(args, section_type, curpx, defpx,
12338 file, line, err, &hlua_timeout_applet);
12339}
12340
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012341static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012342 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012343 char **err)
12344{
12345 char *error;
12346
12347 hlua_nb_instruction = strtoll(args[1], &error, 10);
12348 if (*error != '\0') {
12349 memprintf(err, "%s: invalid number", args[0]);
12350 return -1;
12351 }
12352 return 0;
12353}
12354
Willy Tarreau32f61e22015-03-18 17:54:59 +010012355static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012356 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010012357 char **err)
12358{
12359 char *error;
12360
12361 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012362 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).", args[0]);
Willy Tarreau32f61e22015-03-18 17:54:59 +010012363 return -1;
12364 }
12365 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
12366 if (*error != '\0') {
12367 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
12368 return -1;
12369 }
12370 return 0;
12371}
12372
12373
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012374/* This function is called by the main configuration key "lua-load". It loads and
12375 * execute an lua file during the parsing of the HAProxy configuration file. It is
12376 * the main lua entry point.
12377 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012378 * This function runs with the HAProxy keywords API. It returns -1 if an error
12379 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012380 *
12381 * In some error case, LUA set an error message in top of the stack. This function
12382 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012383 *
12384 * This function can fail with an abort() due to an Lua critical error.
12385 * We are in the configuration parsing process of HAProxy, this abort() is
12386 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012387 */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012388static int hlua_load_state(char **args, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012389{
12390 int error;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012391 int nargs;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012392
12393 /* Just load and compile the file. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012394 error = luaL_loadfile(L, args[0]);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012395 if (error) {
Thierry Fournierae6b5682022-09-19 09:04:16 +020012396 memprintf(err, "error in Lua file '%s': %s", args[0], lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012397 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012398 return -1;
12399 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012400
12401 /* Push args in the Lua stack, except the first one which is the filename */
12402 for (nargs = 1; *(args[nargs]) != 0; nargs++) {
Aurelien DARRAGON4d7aefe2022-09-23 10:22:14 +020012403 /* Check stack size. */
12404 if (!lua_checkstack(L, 1)) {
12405 memprintf(err, "Lua runtime error while loading arguments: stack is full.");
12406 return -1;
12407 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012408 lua_pushstring(L, args[nargs]);
12409 }
12410 nargs--;
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012411
12412 /* If no syntax error where detected, execute the code. */
Thierry Fournierae6b5682022-09-19 09:04:16 +020012413 error = lua_pcall(L, nargs, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012414 switch (error) {
12415 case LUA_OK:
12416 break;
12417 case LUA_ERRRUN:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012418 memprintf(err, "Lua runtime error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012419 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012420 return -1;
12421 case LUA_ERRMEM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012422 memprintf(err, "Lua out of memory error");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012423 return -1;
12424 case LUA_ERRERR:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012425 memprintf(err, "Lua message handler error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012426 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012427 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012428#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012429 case LUA_ERRGCMM:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012430 memprintf(err, "Lua garbage collector error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012431 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012432 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020012433#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012434 default:
Thierry Fournier70e38e92022-09-19 09:01:53 +020012435 memprintf(err, "Lua unknown error: %s", lua_tostring(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012436 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012437 return -1;
12438 }
12439
12440 return 0;
12441}
12442
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012443static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012444 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012445 char **err)
12446{
12447 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012448 memprintf(err, "'%s' expects a file name as parameter.", args[0]);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012449 return -1;
12450 }
12451
Thierry Fournier59f11be2020-11-29 00:37:41 +010012452 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010012453 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012454 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012455 return hlua_load_state(&args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010012456}
12457
Thierry Fournier59f11be2020-11-29 00:37:41 +010012458static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012459 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010012460 char **err)
12461{
12462 int len;
Thierry Fournierae6b5682022-09-19 09:04:16 +020012463 int i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012464
12465 if (*(args[1]) == 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012466 memprintf(err, "'%s' expects a file as parameter.", args[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012467 return -1;
12468 }
12469
12470 if (per_thread_load == NULL) {
12471 /* allocate the first entry large enough to store the final NULL */
12472 per_thread_load = calloc(1, sizeof(*per_thread_load));
12473 if (per_thread_load == NULL) {
12474 memprintf(err, "out of memory error");
12475 return -1;
12476 }
12477 }
12478
12479 /* count used entries */
12480 for (len = 0; per_thread_load[len] != NULL; len++)
12481 ;
12482
12483 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
12484 if (per_thread_load == NULL) {
12485 memprintf(err, "out of memory error");
12486 return -1;
12487 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012488 per_thread_load[len + 1] = NULL;
12489
Thierry Fournierae6b5682022-09-19 09:04:16 +020012490 /* count args excepting the first, allocate array and copy args */
12491 for (i = 0; *(args[i + 1]) != 0; i++);
Aurelien DARRAGONb12d1692022-09-23 08:48:34 +020012492 per_thread_load[len] = calloc(i + 1, sizeof(*per_thread_load[len]));
Thierry Fournier59f11be2020-11-29 00:37:41 +010012493 if (per_thread_load[len] == NULL) {
12494 memprintf(err, "out of memory error");
12495 return -1;
12496 }
Thierry Fournierae6b5682022-09-19 09:04:16 +020012497 for (i = 1; *(args[i]) != 0; i++) {
12498 per_thread_load[len][i - 1] = strdup(args[i]);
12499 if (per_thread_load[len][i - 1] == NULL) {
12500 memprintf(err, "out of memory error");
12501 return -1;
12502 }
12503 }
12504 per_thread_load[len][i - 1] = strdup("");
12505 if (per_thread_load[len][i - 1] == NULL) {
12506 memprintf(err, "out of memory error");
12507 return -1;
12508 }
Thierry Fournier59f11be2020-11-29 00:37:41 +010012509
12510 /* loading for thread 1 only */
12511 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012512 ha_set_thread(NULL);
Thierry Fournierae6b5682022-09-19 09:04:16 +020012513 return hlua_load_state(per_thread_load[len], hlua_states[1], err);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012514}
12515
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012516/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
12517 * in the given <ctx>.
12518 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012519static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012520{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010012521 lua_getglobal(L, "package"); /* push package variable */
12522 lua_pushstring(L, path); /* push given path */
12523 lua_pushstring(L, ";"); /* push semicolon */
12524 lua_getfield(L, -3, type); /* push old path */
12525 lua_concat(L, 3); /* concatenate to new path */
12526 lua_setfield(L, -2, type); /* store new path */
12527 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010012528
12529 return 0;
12530}
12531
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012532static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010012533 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012534 char **err)
12535{
12536 char *path;
12537 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012538 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012539 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012540
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012541 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012542 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012543 }
12544
12545 if (!(*args[1])) {
12546 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012547 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012548 }
12549 path = args[1];
12550
12551 if (*args[2]) {
12552 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
12553 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012554 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012555 }
12556 type = args[2];
12557 }
12558
Thierry Fournier59f11be2020-11-29 00:37:41 +010012559 p = calloc(1, sizeof(*p));
12560 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012561 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012562 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012563 }
12564 p->path = strdup(path);
12565 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012566 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012567 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012568 }
12569 p->type = strdup(type);
12570 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010012571 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012572 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012573 }
Willy Tarreau2b718102021-04-21 07:32:39 +020012574 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012575
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012576 /* Handle the global state and the per-thread state for the first
12577 * thread. The remaining threads will be initialized based on
12578 * prepend_path_list.
12579 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000012580 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020012581 lua_State *L = hlua_states[i];
12582 const char *error;
12583
12584 if (setjmp(safe_ljmp_env) != 0) {
12585 lua_atpanic(L, hlua_panic_safe);
12586 if (lua_type(L, -1) == LUA_TSTRING)
12587 error = lua_tostring(L, -1);
12588 else
12589 error = "critical error";
12590 fprintf(stderr, "lua-prepend-path: %s.\n", error);
12591 exit(1);
12592 } else {
12593 lua_atpanic(L, hlua_panic_ljmp);
12594 }
12595
12596 hlua_prepend_path(L, type, path);
12597
12598 lua_atpanic(L, hlua_panic_safe);
12599 }
12600
Thierry Fournier59f11be2020-11-29 00:37:41 +010012601 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010012602
12603err2:
12604 free(p->type);
12605 free(p->path);
12606err:
12607 free(p);
12608 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012609}
12610
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012611/* configuration keywords declaration */
12612static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010012613 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012614 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010012615 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010012616 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
12617 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020012618 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Aurelien DARRAGON58e36e52023-04-06 22:51:56 +020012619 { CFG_GLOBAL, "tune.lua.burst-timeout", hlua_burst_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010012620 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010012621 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010012622 { 0, NULL, NULL },
12623}};
12624
Willy Tarreau0108d902018-11-25 19:14:37 +010012625INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
12626
William Lallemand52139182022-03-30 15:05:42 +020012627#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010012628
William Lallemand30fcca12022-03-30 12:03:12 +020012629/*
12630 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
12631 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
12632 * difference is that the yield in lua and for the CLI is not handled the same
12633 * way.
12634 */
12635__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
12636{
12637 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
12638 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
12639 struct ckch_inst *ckchi = *lua_ckchi;
12640 struct ckch_store *old_ckchs = lua_ckchs[0];
12641 struct ckch_store *new_ckchs = lua_ckchs[1];
12642 struct hlua *hlua;
12643 char *err = NULL;
12644 int y = 1;
12645
12646 hlua = hlua_gethlua(L);
12647
12648 /* get the first ckchi to copy */
12649 if (ckchi == NULL)
12650 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
12651
12652 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
12653 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
12654 struct ckch_inst *new_inst;
12655
12656 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
12657 if (y % 10 == 0) {
12658
12659 *lua_ckchi = ckchi;
12660
12661 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12662 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12663 }
12664
12665 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
12666 goto error;
12667
12668 /* link the new ckch_inst to the duplicate */
12669 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
12670 y++;
12671 }
12672
12673 /* The generation is finished, we can insert everything */
12674 ckch_store_replace(old_ckchs, new_ckchs);
12675
12676 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
12677
12678 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12679
12680 return 0;
12681
12682error:
12683 ckch_store_free(new_ckchs);
12684 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12685 WILL_LJMP(luaL_error(L, "%s", err));
12686 free(err);
12687
12688 return 0;
12689}
12690
12691/*
12692 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
12693 * from the table in parameter.
12694 *
12695 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
12696 * means it does not need to have a transaction since everything is done in the
12697 * same function.
12698 *
12699 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
12700 *
12701 */
12702__LJMP static int hlua_ckch_set(lua_State *L)
12703{
12704 struct hlua *hlua;
12705 struct ckch_inst **lua_ckchi;
12706 struct ckch_store **lua_ckchs;
12707 struct ckch_store *old_ckchs = NULL;
12708 struct ckch_store *new_ckchs = NULL;
12709 int errcode = 0;
12710 char *err = NULL;
12711 struct cert_exts *cert_ext = NULL;
12712 char *filename;
William Lallemand52ddd992022-11-22 11:51:53 +010012713 struct ckch_data *data;
William Lallemand30fcca12022-03-30 12:03:12 +020012714 int ret;
12715
12716 if (lua_type(L, -1) != LUA_TTABLE)
12717 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
12718
12719 hlua = hlua_gethlua(L);
12720
12721 /* FIXME: this should not return an error but should come back later */
12722 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
12723 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
12724
12725 ret = lua_getfield(L, -1, "filename");
12726 if (ret != LUA_TSTRING) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012727 memprintf(&err, "%sNo filename specified!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012728 errcode |= ERR_ALERT | ERR_FATAL;
12729 goto end;
12730 }
12731 filename = (char *)lua_tostring(L, -1);
12732
12733
12734 /* look for the filename in the tree */
12735 old_ckchs = ckchs_lookup(filename);
12736 if (!old_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012737 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012738 errcode |= ERR_ALERT | ERR_FATAL;
12739 goto end;
12740 }
12741 /* TODO: handle extra_files_noext */
12742
12743 new_ckchs = ckchs_dup(old_ckchs);
12744 if (!new_ckchs) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012745 memprintf(&err, "%sCannot allocate memory!", err ? err : "");
William Lallemand30fcca12022-03-30 12:03:12 +020012746 errcode |= ERR_ALERT | ERR_FATAL;
12747 goto end;
12748 }
12749
William Lallemand52ddd992022-11-22 11:51:53 +010012750 data = new_ckchs->data;
William Lallemand30fcca12022-03-30 12:03:12 +020012751
12752 /* loop on the field in the table, which have the same name as the
12753 * possible extensions of files */
12754 lua_pushnil(L);
12755 while (lua_next(L, 1)) {
12756 int i;
12757 const char *field = lua_tostring(L, -2);
12758 char *payload = (char *)lua_tostring(L, -1);
12759
12760 if (!field || strcmp(field, "filename") == 0) {
12761 lua_pop(L, 1);
12762 continue;
12763 }
12764
12765 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
12766 if (strcmp(field, cert_exts[i].ext) == 0) {
12767 cert_ext = &cert_exts[i];
12768 break;
12769 }
12770 }
12771
12772 /* this is the default type, the field is not supported */
12773 if (cert_ext == NULL) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012774 memprintf(&err, "%sUnsupported field '%s'", err ? err : "", field);
William Lallemand30fcca12022-03-30 12:03:12 +020012775 errcode |= ERR_ALERT | ERR_FATAL;
12776 goto end;
12777 }
12778
12779 /* appply the change on the duplicate */
William Lallemand52ddd992022-11-22 11:51:53 +010012780 if (cert_ext->load(filename, payload, data, &err) != 0) {
Thierry Fournier70e38e92022-09-19 09:01:53 +020012781 memprintf(&err, "%sCan't load the payload for '%s'", err ? err : "", cert_ext->ext);
William Lallemand30fcca12022-03-30 12:03:12 +020012782 errcode |= ERR_ALERT | ERR_FATAL;
12783 goto end;
12784 }
12785 lua_pop(L, 1);
12786 }
12787
12788 /* store the pointers on the lua stack */
12789 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
12790 lua_ckchs[0] = old_ckchs;
12791 lua_ckchs[1] = new_ckchs;
12792 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
12793 *lua_ckchi = NULL;
12794
12795 task_wakeup(hlua->task, TASK_WOKEN_MSG);
12796 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
12797
12798end:
12799 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
12800
12801 if (errcode & ERR_CODE) {
12802 ckch_store_free(new_ckchs);
12803 WILL_LJMP(luaL_error(L, "%s", err));
12804 }
12805 free(err);
12806
12807 return 0;
12808}
12809
William Lallemand52139182022-03-30 15:05:42 +020012810#else
12811
12812__LJMP static int hlua_ckch_set(lua_State *L)
12813{
12814 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
12815
12816 return 0;
12817}
12818#endif /* ! USE_OPENSSL */
12819
12820
12821
Thierry FOURNIERbabae282015-09-17 11:36:37 +020012822/* This function can fail with an abort() due to an Lua critical error.
12823 * We are in the initialisation process of HAProxy, this abort() is
12824 * tolerated.
12825 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010012826int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012827{
12828 struct hlua_init_function *init;
12829 const char *msg;
12830 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010012831 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010012832 const char *kind;
12833 const char *trace;
12834 int return_status = 1;
12835#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
12836 int nres;
12837#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012838
Willy Tarreaucdb53462020-12-02 12:12:00 +010012839 /* disable memory limit checks if limit is not set */
12840 if (!hlua_global_allocator.limit)
12841 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
12842
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050012843 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010012844 if (setjmp(safe_ljmp_env) != 0) {
12845 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012846 if (lua_type(L, -1) == LUA_TSTRING)
12847 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012848 else
12849 error = "critical error";
12850 fprintf(stderr, "Lua post-init: %s.\n", error);
12851 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010012852 } else {
12853 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010012854 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020012855
Thierry Fournierc7492592020-11-28 23:57:24 +010012856 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Aurelien DARRAGON4fdf8b52023-03-20 17:22:37 +010012857 hlua_pushref(L, init->function_ref);
Aurelien DARRAGON16d047b2023-03-20 16:29:55 +010012858 /* function ref should be released right away since it was pushed
12859 * on the stack and will not be used anymore
12860 */
12861 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010012862
12863#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010012864 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010012865#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010012866 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010012867#endif
12868 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012869 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010012870
12871 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010012872 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010012873 break;
Thierry Fournier670db242020-11-28 10:49:59 +010012874
12875 case LUA_ERRERR:
12876 kind = "message handler error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012877 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012878 case LUA_ERRRUN:
12879 if (!kind)
12880 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012881 msg = lua_tostring(L, -1);
12882 lua_settop(L, 0); /* Empty the stack. */
12883 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012884 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012885 if (msg)
12886 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
12887 else
12888 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
12889 return_status = 0;
12890 break;
12891
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012892 default:
Thierry Fournier670db242020-11-28 10:49:59 +010012893 /* Unknown error */
12894 kind = "Unknown error";
Willy Tarreau14de3952022-11-14 07:08:28 +010012895 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012896 case LUA_YIELD:
12897 /* yield is not configured at this step, this state doesn't happen */
12898 if (!kind)
12899 kind = "yield not allowed";
Willy Tarreau14de3952022-11-14 07:08:28 +010012900 __fallthrough;
Thierry Fournier670db242020-11-28 10:49:59 +010012901 case LUA_ERRMEM:
12902 if (!kind)
12903 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010012904 lua_settop(L, 0);
12905 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010012906 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010012907 ha_alert("Lua init: %s: %s\n", kind, trace);
12908 return_status = 0;
12909 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012910 }
Thierry Fournier670db242020-11-28 10:49:59 +010012911 if (!return_status)
12912 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012913 }
Thierry Fournier3c539322020-11-28 16:05:05 +010012914
12915 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010012916 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012917}
12918
Thierry Fournierb8cef172020-11-28 15:37:17 +010012919int hlua_post_init()
12920{
Thierry Fournier59f11be2020-11-29 00:37:41 +010012921 int ret;
12922 int i;
12923 int errors;
12924 char *err = NULL;
12925 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012926 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010012927
Willy Tarreaub1310492021-08-30 09:35:18 +020012928#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010012929 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012930 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010012931 int saved_used_backed = global.ssl_used_backend;
12932 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012933 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010012934 global.ssl_used_backend = saved_used_backed;
12935 }
12936#endif
12937
Thierry Fournierc7492592020-11-28 23:57:24 +010012938 /* Perform post init of common thread */
12939 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012940 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012941 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12942 if (ret == 0)
12943 return 0;
12944
12945 /* init remaining lua states and load files */
12946 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12947
12948 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012949 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012950
12951 /* Init lua state */
12952 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
12953
12954 /* Load lua files */
12955 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
12956 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
12957 if (ret != 0) {
12958 ha_alert("Lua init: %s\n", err);
12959 return 0;
12960 }
12961 }
12962 }
12963
12964 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012965 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012966
12967 /* Execute post init for all states */
12968 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
12969
12970 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012971 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012972
12973 /* run post init */
12974 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
12975 if (ret == 0)
12976 return 0;
12977 }
12978
12979 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012980 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010012981
12982 /* control functions registering. Each function must have:
12983 * - only the function_ref[0] set positive and all other to -1
12984 * - only the function_ref[0] set to -1 and all other positive
12985 * This ensure a same reference is not used both in shared
12986 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050012987 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010012988 * complicated to found for the end user.
12989 */
12990 errors = 0;
12991 list_for_each_entry(fcn, &referenced_functions, l) {
12992 ret = 0;
12993 for (i = 1; i < global.nbthread + 1; i++) {
12994 if (fcn->function_ref[i] == -1)
12995 ret--;
12996 else
12997 ret++;
12998 }
12999 if (abs(ret) != global.nbthread) {
13000 ha_alert("Lua function '%s' is not referenced in all thread. "
13001 "Expect function in all thread or in none thread.\n", fcn->name);
13002 errors++;
13003 continue;
13004 }
13005
13006 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013007 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
13008 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010013009 "exclusive.\n", fcn->name);
13010 errors++;
13011 }
13012 }
13013
Christopher Faulet69c581a2021-05-31 08:54:04 +020013014 /* Do the same with registered filters */
13015 list_for_each_entry(reg_flt, &referenced_filters, l) {
13016 ret = 0;
13017 for (i = 1; i < global.nbthread + 1; i++) {
13018 if (reg_flt->flt_ref[i] == -1)
13019 ret--;
13020 else
13021 ret++;
13022 }
13023 if (abs(ret) != global.nbthread) {
13024 ha_alert("Lua filter '%s' is not referenced in all thread. "
13025 "Expect function in all thread or in none thread.\n", reg_flt->name);
13026 errors++;
13027 continue;
13028 }
13029
13030 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
13031 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
13032 "and per-thread Lua context (through lua-load-per-thread). these two context "
13033 "exclusive.\n", fcn->name);
13034 errors++;
13035 }
13036 }
13037
13038
Thierry Fournier59f11be2020-11-29 00:37:41 +010013039 if (errors > 0)
13040 return 0;
13041
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050013042 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010013043 * -1 in order to have probably a segfault if someone use it
13044 */
13045 hlua_state_id = -1;
13046
13047 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010013048}
13049
Willy Tarreau32f61e22015-03-18 17:54:59 +010013050/* The memory allocator used by the Lua stack. <ud> is a pointer to the
13051 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
13052 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013053 * allocation. <nsize> is the requested new size. A new allocation is
13054 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010013055 * zero. This one verifies that the limits are respected but is optimized
13056 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013057 *
13058 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
13059 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
13060 * that and will simply allocate zero as if it were the result of malloc(0),
13061 * so mapping this onto realloc() will lead to memory leaks on non-glibc
13062 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010013063 */
13064static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
13065{
13066 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010013067 size_t limit, old, new;
13068
13069 /* a limit of ~0 means unlimited and boot complete, so there's no need
13070 * for accounting anymore.
13071 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013072 if (likely(~zone->limit == 0)) {
13073 if (!nsize)
13074 ha_free(&ptr);
13075 else
13076 ptr = realloc(ptr, nsize);
13077 return ptr;
13078 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010013079
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010013080 if (!ptr)
13081 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010013082
Willy Tarreaucdb53462020-12-02 12:12:00 +010013083 /* enforce strict limits across all threads */
13084 limit = zone->limit;
13085 old = _HA_ATOMIC_LOAD(&zone->allocated);
13086 do {
13087 new = old + nsize - osize;
13088 if (unlikely(nsize && limit && new > limit))
13089 return NULL;
13090 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010013091
Willy Tarreaua5efdff2021-10-22 16:00:02 +020013092 if (!nsize)
13093 ha_free(&ptr);
13094 else
13095 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010013096
13097 if (unlikely(!ptr && nsize)) // failed
13098 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
13099
13100 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010013101 return ptr;
13102}
13103
Thierry Fournierecb83c22020-11-28 15:49:44 +010013104/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013105 * We are in the initialisation process of HAProxy, this abort() is
13106 * tolerated.
13107 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010013108lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013109{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013110 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013111 int idx;
13112 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013113 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013114 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010013115 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013116 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013117 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010013118 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013119
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013120 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013121 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013122
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013123 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013124 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010013125 *context = NULL;
13126
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013127 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020013128 * the Lua function can fail with an abort. We are in the initialisation
13129 * process of HAProxy, this abort() is tolerated.
13130 */
13131
Thierry Fournier3c539322020-11-28 16:05:05 +010013132 /* Call post initialisation function in safe environment. */
13133 if (setjmp(safe_ljmp_env) != 0) {
13134 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013135 if (lua_type(L, -1) == LUA_TSTRING)
13136 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013137 else
13138 error_msg = "critical error";
13139 fprintf(stderr, "Lua init: %s.\n", error_msg);
13140 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010013141 } else {
13142 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010013143 }
13144
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013145 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013146 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013147#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
13148#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
13149#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013150 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013151#endif
13152#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013153 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010013154#endif
13155#undef HLUA_PREPEND_PATH_TOSTRING
13156#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013157
Thierry Fournier59f11be2020-11-29 00:37:41 +010013158 /* Apply configured prepend path */
13159 list_for_each_entry(pp, &prepend_path_list, l)
13160 hlua_prepend_path(L, pp->type, pp->path);
13161
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013162 /*
Aurelien DARRAGON8cd620b2023-04-07 17:37:46 +020013163 * Override some lua functions.
13164 *
13165 */
13166
13167 /* push our "safe" coroutine.create() function */
13168 lua_getglobal(L, "coroutine");
13169 lua_pushcclosure(L, hlua_coroutine_create, 0);
13170 lua_setfield(L, -2, "create");
13171
13172 /*
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013173 *
13174 * Create "core" object.
13175 *
13176 */
13177
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010013178 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013179 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013180
Thierry Fournierecb83c22020-11-28 15:49:44 +010013181 /* set the thread id */
13182 hlua_class_const_int(L, "thread", thread_num);
13183
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013184 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010013185 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013186 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010013187
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013188 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013189 hlua_class_function(L, "register_init", hlua_register_init);
13190 hlua_class_function(L, "register_task", hlua_register_task);
13191 hlua_class_function(L, "register_fetches", hlua_register_fetches);
13192 hlua_class_function(L, "register_converters", hlua_register_converters);
13193 hlua_class_function(L, "register_action", hlua_register_action);
13194 hlua_class_function(L, "register_service", hlua_register_service);
13195 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020013196 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013197 hlua_class_function(L, "yield", hlua_yield);
13198 hlua_class_function(L, "set_nice", hlua_set_nice);
13199 hlua_class_function(L, "sleep", hlua_sleep);
13200 hlua_class_function(L, "msleep", hlua_msleep);
13201 hlua_class_function(L, "add_acl", hlua_add_acl);
13202 hlua_class_function(L, "del_acl", hlua_del_acl);
13203 hlua_class_function(L, "set_map", hlua_set_map);
13204 hlua_class_function(L, "del_map", hlua_del_map);
13205 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020013206 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Aurelien DARRAGONc84899c2023-02-20 18:18:59 +010013207 hlua_class_function(L, "event_sub", hlua_event_global_sub);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013208 hlua_class_function(L, "log", hlua_log);
13209 hlua_class_function(L, "Debug", hlua_log_debug);
13210 hlua_class_function(L, "Info", hlua_log_info);
13211 hlua_class_function(L, "Warning", hlua_log_warning);
13212 hlua_class_function(L, "Alert", hlua_log_alert);
13213 hlua_class_function(L, "done", hlua_done);
Aurelien DARRAGON5bed48f2023-04-21 17:32:46 +020013214 hlua_class_function(L, "disable_legacy_mailers", hlua_disable_legacy_mailers);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013215 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010013216
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013217 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013218
13219 /*
13220 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013221 * Create "act" object.
13222 *
13223 */
13224
13225 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013226 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013227
13228 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013229 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
13230 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
13231 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
13232 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
13233 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
13234 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
13235 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
13236 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013237
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013238 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010013239
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013240 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010013241
13242 /*
13243 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020013244 * Create "Filter" object.
13245 *
13246 */
13247
13248 /* This table entry is the object "filter" base. */
13249 lua_newtable(L);
13250
13251 /* push flags and constants */
13252 hlua_class_const_int(L, "CONTINUE", 1);
13253 hlua_class_const_int(L, "WAIT", 0);
13254 hlua_class_const_int(L, "ERROR", -1);
13255
13256 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
13257
Christopher Fauletc404f112020-02-26 15:03:09 +010013258 hlua_class_function(L, "wake_time", hlua_set_wake_time);
13259 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
13260 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
13261
Christopher Faulet69c581a2021-05-31 08:54:04 +020013262 lua_setglobal(L, "filter");
13263
13264 /*
13265 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013266 * Register class Map
13267 *
13268 */
13269
13270 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013271 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013272
13273 /* register pattern types. */
13274 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013275 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013276 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013277 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013278 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010013279 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013280
13281 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013282 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013283
13284 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013285 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013286
Ilya Shipitsind4259502020-04-08 01:07:56 +050013287 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013288 lua_pushstring(L, "__index");
13289 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013290
13291 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013292 hlua_class_function(L, "lookup", hlua_map_lookup);
13293 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013294
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013295 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013296
Thierry Fournier45e78d72016-02-19 18:34:46 +010013297 /* Register previous table in the registry with reference and named entry.
13298 * The function hlua_register_metatable() pops the stack, so we
13299 * previously create a copy of the table.
13300 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013301 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
13302 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013303
13304 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013305 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013306
13307 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013308 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020013309
13310 /*
13311 *
William Lallemand30fcca12022-03-30 12:03:12 +020013312 * Register "CertCache" class
13313 *
13314 */
13315
13316 /* Create and fill the metatable. */
13317 lua_newtable(L);
13318 /* Register */
13319 hlua_class_function(L, "set", hlua_ckch_set);
13320 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
13321
13322 /*
13323 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013324 * Register class Channel
13325 *
13326 */
13327
13328 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013329 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013330
Ilya Shipitsind4259502020-04-08 01:07:56 +050013331 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013332 lua_pushstring(L, "__index");
13333 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013334
13335 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013336 hlua_class_function(L, "data", hlua_channel_get_data);
13337 hlua_class_function(L, "line", hlua_channel_get_line);
13338 hlua_class_function(L, "set", hlua_channel_set_data);
13339 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013340 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013341 hlua_class_function(L, "prepend", hlua_channel_prepend);
13342 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013343 hlua_class_function(L, "send", hlua_channel_send);
13344 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013345 hlua_class_function(L, "input", hlua_channel_get_in_len);
13346 hlua_class_function(L, "output", hlua_channel_get_out_len);
13347 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013348 hlua_class_function(L, "is_full", hlua_channel_is_full);
13349 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013350
Christopher Faulet6a79fc12021-08-06 16:02:36 +020013351 /* Deprecated API */
13352 hlua_class_function(L, "get", hlua_channel_get);
13353 hlua_class_function(L, "dup", hlua_channel_dup);
13354 hlua_class_function(L, "getline", hlua_channel_getline);
13355 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
13356 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
13357
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013358 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013359
13360 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013361 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010013362
13363 /*
13364 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013365 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013366 *
13367 */
13368
13369 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013370 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013371
Ilya Shipitsind4259502020-04-08 01:07:56 +050013372 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013373 lua_pushstring(L, "__index");
13374 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013375
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013376 /* Browse existing fetches and create the associated
13377 * object method.
13378 */
13379 sf = NULL;
13380 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013381 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13382 * by an underscore.
13383 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013384 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013385 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013386 if (*p == '.' || *p == '-' || *p == '+')
13387 *p = '_';
13388
13389 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013390 lua_pushstring(L, trash.area);
13391 lua_pushlightuserdata(L, sf);
13392 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
13393 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010013394 }
13395
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013396 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013397
13398 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013399 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013400
13401 /*
13402 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013403 * Register class Converters
13404 *
13405 */
13406
13407 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013408 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013409
13410 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013411 lua_pushstring(L, "__index");
13412 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013413
13414 /* Browse existing converters and create the associated
13415 * object method.
13416 */
13417 sc = NULL;
13418 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013419 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
13420 * by an underscore.
13421 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020013422 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020013423 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013424 if (*p == '.' || *p == '-' || *p == '+')
13425 *p = '_';
13426
13427 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013428 lua_pushstring(L, trash.area);
13429 lua_pushlightuserdata(L, sc);
13430 lua_pushcclosure(L, hlua_run_sample_conv, 1);
13431 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013432 }
13433
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013434 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013435
13436 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013437 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010013438
13439 /*
13440 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013441 * Register class HTTP
13442 *
13443 */
13444
13445 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013446 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013447
Ilya Shipitsind4259502020-04-08 01:07:56 +050013448 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013449 lua_pushstring(L, "__index");
13450 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013451
13452 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013453 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
13454 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
13455 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
13456 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
13457 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
13458 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
13459 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
13460 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
13461 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
13462 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013463
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013464 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
13465 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
13466 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
13467 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
13468 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
13469 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
13470 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013471
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013472 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013473
13474 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013475 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013476
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013477 /*
13478 *
13479 * Register class HTTPMessage
13480 *
13481 */
13482
13483 /* Create and fill the metatable. */
13484 lua_newtable(L);
13485
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050013486 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010013487 lua_pushstring(L, "__index");
13488 lua_newtable(L);
13489
13490 /* Register Lua functions. */
13491 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
13492 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
13493 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
13494 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
13495 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
13496 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
13497 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
13498 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
13499 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
13500 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
13501 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
13502 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
13503 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
13504 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
13505 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
13506 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
13507 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
13508 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
13509
13510 hlua_class_function(L, "body", hlua_http_msg_get_body);
13511 hlua_class_function(L, "set", hlua_http_msg_set_data);
13512 hlua_class_function(L, "remove", hlua_http_msg_del_data);
13513 hlua_class_function(L, "append", hlua_http_msg_append);
13514 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
13515 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
13516 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
13517 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
13518
13519 hlua_class_function(L, "send", hlua_http_msg_send);
13520 hlua_class_function(L, "forward", hlua_http_msg_forward);
13521
13522 lua_rawset(L, -3);
13523
13524 /* Register previous table in the registry with reference and named entry. */
13525 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020013526
13527 /*
13528 *
13529 * Register class HTTPClient
13530 *
13531 */
13532
13533 /* Create and fill the metatable. */
13534 lua_newtable(L);
13535 lua_pushstring(L, "__index");
13536 lua_newtable(L);
13537 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020013538 hlua_class_function(L, "head", hlua_httpclient_head);
13539 hlua_class_function(L, "put", hlua_httpclient_put);
13540 hlua_class_function(L, "post", hlua_httpclient_post);
13541 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020013542 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020013543 /* Register the garbage collector entry. */
13544 lua_pushstring(L, "__gc");
13545 lua_pushcclosure(L, hlua_httpclient_gc, 0);
13546 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
13547
William Lallemand3956c4e2021-09-21 16:25:15 +020013548
13549
13550 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010013551 /*
13552 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013553 * Register class AppletTCP
13554 *
13555 */
13556
13557 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013558 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013559
Ilya Shipitsind4259502020-04-08 01:07:56 +050013560 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013561 lua_pushstring(L, "__index");
13562 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013563
13564 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013565 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
13566 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
13567 hlua_class_function(L, "send", hlua_applet_tcp_send);
13568 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
13569 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
13570 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
13571 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
13572 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013573
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013574 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013575
13576 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013577 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020013578
13579 /*
13580 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013581 * Register class AppletHTTP
13582 *
13583 */
13584
13585 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013586 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013587
Ilya Shipitsind4259502020-04-08 01:07:56 +050013588 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013589 lua_pushstring(L, "__index");
13590 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013591
13592 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013593 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
13594 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
13595 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
13596 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
13597 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
13598 hlua_class_function(L, "getline", hlua_applet_http_getline);
13599 hlua_class_function(L, "receive", hlua_applet_http_recv);
13600 hlua_class_function(L, "send", hlua_applet_http_send);
13601 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
13602 hlua_class_function(L, "set_status", hlua_applet_http_status);
13603 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013604
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013605 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013606
13607 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013608 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020013609
13610 /*
13611 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010013612 * Register class TXN
13613 *
13614 */
13615
13616 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013617 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +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 FOURNIERbb53c7b2015-03-11 18:28:02 +010013622
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013623 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013624 hlua_class_function(L, "set_priv", hlua_set_priv);
13625 hlua_class_function(L, "get_priv", hlua_get_priv);
13626 hlua_class_function(L, "set_var", hlua_set_var);
13627 hlua_class_function(L, "unset_var", hlua_unset_var);
13628 hlua_class_function(L, "get_var", hlua_get_var);
13629 hlua_class_function(L, "done", hlua_txn_done);
13630 hlua_class_function(L, "reply", hlua_txn_reply_new);
13631 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
13632 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
13633 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
13634 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
13635 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
13636 hlua_class_function(L, "deflog", hlua_txn_deflog);
13637 hlua_class_function(L, "log", hlua_txn_log);
13638 hlua_class_function(L, "Debug", hlua_txn_log_debug);
13639 hlua_class_function(L, "Info", hlua_txn_log_info);
13640 hlua_class_function(L, "Warning", hlua_txn_log_warning);
13641 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010013642
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013643 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010013644
13645 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013646 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013647
13648 /*
13649 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010013650 * Register class reply
13651 *
13652 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013653 lua_newtable(L);
13654 lua_pushstring(L, "__index");
13655 lua_newtable(L);
13656 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
13657 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
13658 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
13659 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
13660 lua_settable(L, -3); /* Sets the __index entry. */
13661 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010013662
13663
13664 /*
13665 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013666 * Register class Socket
13667 *
13668 */
13669
13670 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013671 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013672
Ilya Shipitsind4259502020-04-08 01:07:56 +050013673 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013674 lua_pushstring(L, "__index");
13675 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013676
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013677#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013678 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010013679#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013680 hlua_class_function(L, "connect", hlua_socket_connect);
13681 hlua_class_function(L, "send", hlua_socket_send);
13682 hlua_class_function(L, "receive", hlua_socket_receive);
13683 hlua_class_function(L, "close", hlua_socket_close);
13684 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
13685 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
13686 hlua_class_function(L, "setoption", hlua_socket_setoption);
13687 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013688
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013689 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013690
13691 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013692 lua_pushstring(L, "__gc");
13693 lua_pushcclosure(L, hlua_socket_gc, 0);
13694 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013695
13696 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010013697 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013698
Thierry Fournieraafc7772020-12-04 11:47:47 +010013699 lua_atpanic(L, hlua_panic_safe);
13700
13701 return L;
13702}
13703
13704void hlua_init(void) {
13705 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013706 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010013707#ifdef USE_OPENSSL
13708 struct srv_kw *kw;
13709 int tmp_error;
13710 char *error;
13711 char *args[] = { /* SSL client configuration. */
13712 "ssl",
13713 "verify",
13714 "none",
13715 NULL
13716 };
13717#endif
13718
13719 /* Init post init function list head */
13720 for (i = 0; i < MAX_THREADS + 1; i++)
13721 LIST_INIT(&hlua_init_functions[i]);
13722
13723 /* Init state for common/shared lua parts */
13724 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013725 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013726 hlua_states[0] = hlua_init_state(0);
13727
13728 /* Init state 1 for thread 0. We have at least one thread. */
13729 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020013730 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010013731 hlua_states[1] = hlua_init_state(1);
13732
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013733 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020013734 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013735 if (!socket_proxy) {
13736 fprintf(stderr, "Lua init: %s\n", errmsg);
13737 exit(1);
13738 }
13739 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013740
13741 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013742 socket_tcp = new_server(socket_proxy);
13743 if (!socket_tcp) {
13744 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
13745 exit(1);
13746 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013747
13748#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013749 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013750 socket_ssl = new_server(socket_proxy);
13751 if (!socket_ssl) {
13752 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
13753 exit(1);
13754 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013755
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013756 socket_ssl->use_ssl = 1;
13757 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013758
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013759 for (i = 0; args[i] != NULL; i++) {
13760 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013761 /*
13762 *
13763 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080013764 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013765 * features like client certificates and ssl_verify.
13766 *
13767 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010013768 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013769 if (tmp_error != 0) {
13770 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
13771 abort(); /* This must be never arrives because the command line
13772 not editable by the user. */
13773 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000013774 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013775 }
13776 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013777#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010013778
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010013779}
Willy Tarreaubb57d942016-12-21 19:04:56 +010013780
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013781static void hlua_deinit()
13782{
Willy Tarreau186f3762020-12-04 11:48:12 +010013783 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020013784 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
13785
13786 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
13787 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010013788
13789 for (thr = 0; thr < MAX_THREADS+1; thr++) {
13790 if (hlua_states[thr])
13791 lua_close(hlua_states[thr]);
13792 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013793
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013794 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010013795
Willy Tarreau0f143af2021-03-05 10:41:48 +010013796#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020013797 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010013798#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010013799
13800 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020013801}
13802
13803REGISTER_POST_DEINIT(hlua_deinit);
13804
Willy Tarreau80713382018-11-26 10:19:54 +010013805static void hlua_register_build_options(void)
13806{
Willy Tarreaubb57d942016-12-21 19:04:56 +010013807 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010013808
Willy Tarreaubb57d942016-12-21 19:04:56 +010013809 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
13810 hap_register_build_opts(ptr, 1);
13811}
Willy Tarreau80713382018-11-26 10:19:54 +010013812
13813INITCALL0(STG_REGISTER, hlua_register_build_options);