blob: 91a9f7cad244f9182c6047ac196950fc35497d1b [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 Faulet908628c2022-03-25 16:43:49 +010037#include <haproxy/conn_stream.h>
38#include <haproxy/cs_utils.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020039#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020040#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020041#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020042#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020043#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020044#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020045#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020047#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020048#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020049#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020050#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020051#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020052#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020053#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020055#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010056#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020057#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020058#include <haproxy/ssl_ckch.h>
59#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020060#include <haproxy/stats-t.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>
68
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
148static char **per_thread_load = NULL;
149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
155void lua_take_global_lock()
156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaue23f33b2022-05-06 14:07:13 +0200255/* appctx context used by TCP services */
256struct hlua_tcp_ctx {
257 struct hlua *hlua;
258 int flags;
259 struct task *task;
260};
261
Willy Tarreauaa229cc2022-05-06 14:26:10 +0200262/* appctx context used by HTTP services */
263struct hlua_http_ctx {
264 struct hlua *hlua;
265 int left_bytes; /* The max amount of bytes that we can read. */
266 int flags;
267 int status;
268 const char *reason;
269 struct task *task;
270};
271
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200272/* used by registered CLI keywords */
273struct hlua_cli_ctx {
274 struct hlua *hlua;
275 struct task *task;
276 struct hlua_function *fcn;
277};
278
Christopher Faulet69c581a2021-05-31 08:54:04 +0200279DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
280
Christopher Faulet9f55a502020-02-25 15:21:02 +0100281static int hlua_filter_from_payload(struct filter *filter);
282
Christopher Faulet69c581a2021-05-31 08:54:04 +0200283/* This is the chained list of struct hlua_flt referenced
284 * for haproxy filters. It is used for a post-initialisation control.
285 */
286static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
287
288
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100289/* This is the memory pool containing struct lua for applets
290 * (including cli).
291 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100292DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100294/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100295static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100296static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100297#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100298static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100299#endif
300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100301/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100302struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100303
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100304/* The following variables contains the reference of the different
305 * Lua classes. These references are useful for identify metadata
306 * associated with an object.
307 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100308static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100309static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100310static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100311static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100312static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100313static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100314static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200315static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200316static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200317static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200318static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100319static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100320
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100321/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200322 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100323 * short timeout. Lua linked with tasks doesn't have a timeout
324 * because a task may remain alive during all the haproxy execution.
325 */
326static unsigned int hlua_timeout_session = 4000; /* session timeout. */
327static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200328static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100329
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100330/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
331 * it is used for preventing infinite loops.
332 *
333 * I test the scheer with an infinite loop containing one incrementation
334 * and one test. I run this loop between 10 seconds, I raise a ceil of
335 * 710M loops from one interrupt each 9000 instructions, so I fix the value
336 * to one interrupt each 10 000 instructions.
337 *
338 * configured | Number of
339 * instructions | loops executed
340 * between two | in milions
341 * forced yields |
342 * ---------------+---------------
343 * 10 | 160
344 * 500 | 670
345 * 1000 | 680
346 * 5000 | 700
347 * 7000 | 700
348 * 8000 | 700
349 * 9000 | 710 <- ceil
350 * 10000 | 710
351 * 100000 | 710
352 * 1000000 | 710
353 *
354 */
355static unsigned int hlua_nb_instruction = 10000;
356
Willy Tarreaucdb53462020-12-02 12:12:00 +0100357/* Descriptor for the memory allocation state. The limit is pre-initialised to
358 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
359 * is replaced with ~0 during post_init after everything was loaded. This way
360 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
361 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100362 */
363struct hlua_mem_allocator {
364 size_t allocated;
365 size_t limit;
366};
367
Willy Tarreaucdb53462020-12-02 12:12:00 +0100368static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100369
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370/* These functions converts types between HAProxy internal args or
371 * sample and LUA types. Another function permits to check if the
372 * LUA stack contains arguments according with an required ARG_T
373 * format.
374 */
375static int hlua_arg2lua(lua_State *L, const struct arg *arg);
376static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100377__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100378 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100379static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100380static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
382
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100383__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200384
Thierry Fournier59f11be2020-11-29 00:37:41 +0100385struct prepend_path {
386 struct list l;
387 char *type;
388 char *path;
389};
390
391static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
392
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200393#define SEND_ERR(__be, __fmt, __args...) \
394 do { \
395 send_log(__be, LOG_ERR, __fmt, ## __args); \
396 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100397 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200398 } while (0)
399
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100400static inline struct hlua_function *new_hlua_function()
401{
402 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100403 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100404
405 fcn = calloc(1, sizeof(*fcn));
406 if (!fcn)
407 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200408 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100409 for (i = 0; i < MAX_THREADS + 1; i++)
410 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100411 return fcn;
412}
413
Christopher Fauletdda44442021-04-12 14:05:43 +0200414static inline void release_hlua_function(struct hlua_function *fcn)
415{
416 if (!fcn)
417 return;
418 if (fcn->name)
419 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200420 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200421 ha_free(&fcn);
422}
423
Thierry Fournierc7492592020-11-28 23:57:24 +0100424/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
425static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
426{
427 if (fcn->function_ref[0] == -1)
428 return tid + 1;
429 return 0;
430}
431
Christopher Faulet69c581a2021-05-31 08:54:04 +0200432/* Create a new registered filter. Only its name is filled */
433static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
434{
435 struct hlua_reg_filter *reg_flt;
436 int i;
437
438 reg_flt = calloc(1, sizeof(*reg_flt));
439 if (!reg_flt)
440 return NULL;
441 reg_flt->name = strdup(name);
442 if (!reg_flt->name) {
443 free(reg_flt);
444 return NULL;
445 }
446 LIST_APPEND(&referenced_filters, &reg_flt->l);
447 for (i = 0; i < MAX_THREADS + 1; i++) {
448 reg_flt->flt_ref[i] = -1;
449 reg_flt->fun_ref[i] = -1;
450 }
451 return reg_flt;
452}
453
454/* Release a registered filter */
455static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
456{
457 if (!reg_flt)
458 return;
459 if (reg_flt->name)
460 ha_free(&reg_flt->name);
461 LIST_DELETE(&reg_flt->l);
462 ha_free(&reg_flt);
463}
464
465/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
466static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
467{
468 if (reg_flt->fun_ref[0] == -1)
469 return tid + 1;
470 return 0;
471}
472
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100473/* Used to check an Lua function type in the stack. It creates and
474 * returns a reference of the function. This function throws an
475 * error if the rgument is not a "function".
476 */
477__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
478{
479 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100480 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100481 WILL_LJMP(luaL_argerror(L, argno, msg));
482 }
483 lua_pushvalue(L, argno);
484 return luaL_ref(L, LUA_REGISTRYINDEX);
485}
486
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100487/* Used to check an Lua table type in the stack. It creates and
488 * returns a reference of the table. This function throws an
489 * error if the rgument is not a "table".
490 */
491__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
492{
493 if (!lua_istable(L, argno)) {
494 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
495 WILL_LJMP(luaL_argerror(L, argno, msg));
496 }
497 lua_pushvalue(L, argno);
498 return luaL_ref(L, LUA_REGISTRYINDEX);
499}
500
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200501/* Return the string that is of the top of the stack. */
502const char *hlua_get_top_error_string(lua_State *L)
503{
504 if (lua_gettop(L) < 1)
505 return "unknown error";
506 if (lua_type(L, -1) != LUA_TSTRING)
507 return "unknown error";
508 return lua_tostring(L, -1);
509}
510
Christopher Fauletd09cc512021-03-24 14:48:45 +0100511__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200512{
513 lua_Debug ar;
514 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200515 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200516
517 while (lua_getstack(L, level++, &ar)) {
518
519 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100520 if (b_data(msg))
521 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200522
523 /* Fill fields:
524 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
525 * 'l': fills in the field currentline;
526 * 'n': fills in the field name and namewhat;
527 * 't': fills in the field istailcall;
528 */
529 lua_getinfo(L, "Slnt", &ar);
530
531 /* Append code localisation */
532 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100533 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200534 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100535 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200536
537 /*
538 * Get function name
539 *
540 * if namewhat is no empty, name is defined.
541 * what contains "Lua" for Lua function, "C" for C function,
542 * or "main" for main code.
543 */
544 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100545 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200546
547 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100548 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200549
550 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100551 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200552
553 else /* nothing left... */
554 chunk_appendf(msg, "?");
555
556
557 /* Display tailed call */
558 if (ar.istailcall)
559 chunk_appendf(msg, " ...");
560 }
561
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200562 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200563}
564
565
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100566/* This function check the number of arguments available in the
567 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500568 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100569 */
570__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
571{
572 if (lua_gettop(L) == nb)
573 return;
574 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
575}
576
Mark Lakes22154b42018-01-29 14:38:40 -0800577/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100578 * and the line number where the error is encountered.
579 */
580static int hlua_pusherror(lua_State *L, const char *fmt, ...)
581{
582 va_list argp;
583 va_start(argp, fmt);
584 luaL_where(L, 1);
585 lua_pushvfstring(L, fmt, argp);
586 va_end(argp);
587 lua_concat(L, 2);
588 return 1;
589}
590
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100591/* This functions is used with sample fetch and converters. It
592 * converts the HAProxy configuration argument in a lua stack
593 * values.
594 *
595 * It takes an array of "arg", and each entry of the array is
596 * converted and pushed in the LUA stack.
597 */
598static int hlua_arg2lua(lua_State *L, const struct arg *arg)
599{
600 switch (arg->type) {
601 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 case ARGT_TIME:
603 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100604 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100605 break;
606
607 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200608 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100609 break;
610
611 case ARGT_IPV4:
612 case ARGT_IPV6:
613 case ARGT_MSK4:
614 case ARGT_MSK6:
615 case ARGT_FE:
616 case ARGT_BE:
617 case ARGT_TAB:
618 case ARGT_SRV:
619 case ARGT_USR:
620 case ARGT_MAP:
621 default:
622 lua_pushnil(L);
623 break;
624 }
625 return 1;
626}
627
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500628/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100629 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500630 * with sample fetch wrappers. The input arguments are given to the
631 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100632 */
633static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
634{
635 switch (lua_type(L, ud)) {
636
637 case LUA_TNUMBER:
638 case LUA_TBOOLEAN:
639 arg->type = ARGT_SINT;
640 arg->data.sint = lua_tointeger(L, ud);
641 break;
642
643 case LUA_TSTRING:
644 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200645 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200646 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200647 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200648 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100649 break;
650
651 case LUA_TUSERDATA:
652 case LUA_TNIL:
653 case LUA_TTABLE:
654 case LUA_TFUNCTION:
655 case LUA_TTHREAD:
656 case LUA_TLIGHTUSERDATA:
657 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200658 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100659 break;
660 }
661 return 1;
662}
663
664/* the following functions are used to convert a struct sample
665 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500666 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100668static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100669{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200670 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100671 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200673 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100674 break;
675
676 case SMP_T_BIN:
677 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200678 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100679 break;
680
681 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200682 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100683 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
684 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
685 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
686 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
687 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
688 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
689 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
690 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
691 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200692 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100693 break;
694 default:
695 lua_pushnil(L);
696 break;
697 }
698 break;
699
700 case SMP_T_IPV4:
701 case SMP_T_IPV6:
702 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200703 if (sample_casts[smp->data.type][SMP_T_STR] &&
704 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200705 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100706 else
707 lua_pushnil(L);
708 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100709 default:
710 lua_pushnil(L);
711 break;
712 }
713 return 1;
714}
715
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100716/* the following functions are used to convert a struct sample
717 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500718 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100719 */
720static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
721{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200722 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100723
724 case SMP_T_BIN:
725 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200726 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100727 break;
728
729 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200730 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100731 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
732 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
733 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
734 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
735 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
736 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
737 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
738 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
739 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200740 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100741 break;
742 default:
743 lua_pushstring(L, "");
744 break;
745 }
746 break;
747
748 case SMP_T_SINT:
749 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100750 case SMP_T_IPV4:
751 case SMP_T_IPV6:
752 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200753 if (sample_casts[smp->data.type][SMP_T_STR] &&
754 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200755 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100756 else
757 lua_pushstring(L, "");
758 break;
759 default:
760 lua_pushstring(L, "");
761 break;
762 }
763 return 1;
764}
765
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100766/* the following functions are used to convert an Lua type in a
767 * struct sample. This is useful to provide data from a converter
768 * to the LUA code.
769 */
770static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
771{
772 switch (lua_type(L, ud)) {
773
774 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200775 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200776 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100777 break;
778
779
780 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200781 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200782 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100783 break;
784
785 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200786 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100787 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200788 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200789 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200790 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200791 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100792 break;
793
794 case LUA_TUSERDATA:
795 case LUA_TNIL:
796 case LUA_TTABLE:
797 case LUA_TFUNCTION:
798 case LUA_TTHREAD:
799 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200800 case LUA_TNONE:
801 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200802 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200803 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100804 break;
805 }
806 return 1;
807}
808
Ilya Shipitsind4259502020-04-08 01:07:56 +0500809/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800810 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100812 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500813 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200814 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100815 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100816__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100817 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100818{
819 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200820 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100821 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200822 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200823 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200824 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200825 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100826
827 idx = 0;
828 min_arg = ARGM(mask);
829 mask >>= ARGM_BITS;
830
831 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200832 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100833
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100834 /* Check for mandatory arguments. */
835 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100836 if (idx < min_arg) {
837
838 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200839 if (idx > 0) {
840 msg = "Mandatory argument expected";
841 goto error;
842 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100843
844 /* If first argument have a certain type, some default values
845 * may be used. See the function smp_resolve_args().
846 */
847 switch (mask & ARGT_MASK) {
848
849 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200850 if (!(p->cap & PR_CAP_FE)) {
851 msg = "Mandatory argument expected";
852 goto error;
853 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100854 argp[idx].data.prx = p;
855 argp[idx].type = ARGT_FE;
856 argp[idx+1].type = ARGT_STOP;
857 break;
858
859 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200860 if (!(p->cap & PR_CAP_BE)) {
861 msg = "Mandatory argument expected";
862 goto error;
863 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100864 argp[idx].data.prx = p;
865 argp[idx].type = ARGT_BE;
866 argp[idx+1].type = ARGT_STOP;
867 break;
868
869 case ARGT_TAB:
870 argp[idx].data.prx = p;
871 argp[idx].type = ARGT_TAB;
872 argp[idx+1].type = ARGT_STOP;
873 break;
874
875 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200876 msg = "Mandatory argument expected";
877 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100878 break;
879 }
880 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200881 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100882 }
883
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500884 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100885 if ((mask & ARGT_MASK) == ARGT_STOP &&
886 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200887 msg = "Last argument expected";
888 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100889 }
890
891 if ((mask & ARGT_MASK) == ARGT_STOP &&
892 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200893 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100894 }
895
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200896 /* Convert some argument types. All string in argp[] are for not
897 * duplicated yet.
898 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100899 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100900 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200901 if (argp[idx].type != ARGT_SINT) {
902 msg = "integer expected";
903 goto error;
904 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100905 argp[idx].type = ARGT_SINT;
906 break;
907
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100908 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200909 if (argp[idx].type != ARGT_SINT) {
910 msg = "integer expected";
911 goto error;
912 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200913 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100914 break;
915
916 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200917 if (argp[idx].type != ARGT_SINT) {
918 msg = "integer expected";
919 goto error;
920 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200921 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100922 break;
923
924 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200925 if (argp[idx].type != ARGT_STR) {
926 msg = "string expected";
927 goto error;
928 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200929 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200930 if (!argp[idx].data.prx) {
931 msg = "frontend doesn't exist";
932 goto error;
933 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100934 argp[idx].type = ARGT_FE;
935 break;
936
937 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200938 if (argp[idx].type != ARGT_STR) {
939 msg = "string expected";
940 goto error;
941 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200942 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200943 if (!argp[idx].data.prx) {
944 msg = "backend doesn't exist";
945 goto error;
946 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100947 argp[idx].type = ARGT_BE;
948 break;
949
950 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200951 if (argp[idx].type != ARGT_STR) {
952 msg = "string expected";
953 goto error;
954 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200955 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200956 if (!argp[idx].data.t) {
957 msg = "table doesn't exist";
958 goto error;
959 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100960 argp[idx].type = ARGT_TAB;
961 break;
962
963 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200964 if (argp[idx].type != ARGT_STR) {
965 msg = "string expected";
966 goto error;
967 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200968 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100969 if (sname) {
970 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200971 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200972 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200973 if (!px) {
974 msg = "backend doesn't exist";
975 goto error;
976 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 }
978 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200979 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100980 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100981 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100982 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200983 if (!argp[idx].data.srv) {
984 msg = "server doesn't exist";
985 goto error;
986 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100987 argp[idx].type = ARGT_SRV;
988 break;
989
990 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200991 if (argp[idx].type != ARGT_STR) {
992 msg = "string expected";
993 goto error;
994 }
995 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
996 msg = "invalid IPv4 address";
997 goto error;
998 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100999 argp[idx].type = ARGT_IPV4;
1000 break;
1001
1002 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001003 if (argp[idx].type == ARGT_SINT)
1004 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1005 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001006 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1007 msg = "invalid IPv4 mask";
1008 goto error;
1009 }
1010 }
1011 else {
1012 msg = "integer or string expected";
1013 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001014 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001015 argp[idx].type = ARGT_MSK4;
1016 break;
1017
1018 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001019 if (argp[idx].type != ARGT_STR) {
1020 msg = "string expected";
1021 goto error;
1022 }
1023 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1024 msg = "invalid IPv6 address";
1025 goto error;
1026 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001027 argp[idx].type = ARGT_IPV6;
1028 break;
1029
1030 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001031 if (argp[idx].type == ARGT_SINT)
1032 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1033 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001034 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1035 msg = "invalid IPv6 mask";
1036 goto error;
1037 }
1038 }
1039 else {
1040 msg = "integer or string expected";
1041 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001042 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001043 argp[idx].type = ARGT_MSK6;
1044 break;
1045
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001046 case ARGT_REG:
1047 if (argp[idx].type != ARGT_STR) {
1048 msg = "string expected";
1049 goto error;
1050 }
1051 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1052 if (!reg) {
1053 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1054 argp[idx].data.str.area, err);
1055 free(err);
1056 goto error;
1057 }
1058 argp[idx].type = ARGT_REG;
1059 argp[idx].data.reg = reg;
1060 break;
1061
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001062 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001063 if (argp[idx].type != ARGT_STR) {
1064 msg = "string expected";
1065 goto error;
1066 }
1067 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001068 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001069 ul = p->uri_auth->userlist;
1070 else
1071 ul = auth_find_userlist(argp[idx].data.str.area);
1072
1073 if (!ul) {
1074 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1075 goto error;
1076 }
1077 argp[idx].type = ARGT_USR;
1078 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001079 break;
1080
1081 case ARGT_STR:
1082 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1083 msg = "unable to duplicate string arg";
1084 goto error;
1085 }
1086 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001087 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001088
Christopher Fauletd25d9262020-08-06 11:04:46 +02001089 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001090 msg = "type not yet supported";
1091 goto error;
1092 break;
1093
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001094 }
1095
1096 /* Check for type of argument. */
1097 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001098 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1099 arg_type_names[(mask & ARGT_MASK)],
1100 arg_type_names[argp[idx].type & ARGT_MASK]);
1101 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001102 }
1103
1104 /* Next argument. */
1105 mask >>= ARGT_BITS;
1106 idx++;
1107 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001108 return 0;
1109
1110 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001111 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001112 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1113 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001114}
1115
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001116/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001117 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001118 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 *
1120 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001121 * - hlua_sethlua : create the association between hlua context and lua_state.
1122 */
1123static inline struct hlua *hlua_gethlua(lua_State *L)
1124{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001125 struct hlua **hlua = lua_getextraspace(L);
1126 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001127}
1128static inline void hlua_sethlua(struct hlua *hlua)
1129{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001130 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1131 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001132}
1133
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001134/* This function is used to send logs. It try to send on screen (stderr)
1135 * and on the default syslog server.
1136 */
1137static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1138{
1139 struct tm tm;
1140 char *p;
1141
1142 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001143 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001144 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001145 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001146 /* Break the message if exceed the buffer size. */
1147 *(p-4) = ' ';
1148 *(p-3) = '.';
1149 *(p-2) = '.';
1150 *(p-1) = '.';
1151 break;
1152 }
Willy Tarreau90807112020-02-25 08:16:33 +01001153 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001154 *p = *msg;
1155 else
1156 *p = '.';
1157 }
1158 *p = '\0';
1159
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001160 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001161 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001162 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1163 return;
1164
Willy Tarreaua678b432015-08-28 10:14:59 +02001165 get_localtime(date.tv_sec, &tm);
1166 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001167 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001168 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001169 fflush(stderr);
1170 }
1171}
1172
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001173/* This function just ensure that the yield will be always
1174 * returned with a timeout and permit to set some flags
1175 */
1176__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001177 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001178{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001179 struct hlua *hlua;
1180
1181 /* Get hlua struct, or NULL if we execute from main lua state */
1182 hlua = hlua_gethlua(L);
1183 if (!hlua) {
1184 return;
1185 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001186
1187 /* Set the wake timeout. If timeout is required, we set
1188 * the expiration time.
1189 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001190 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001191
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001192 hlua->flags |= flags;
1193
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001194 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001195 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196}
1197
Willy Tarreau87b09662015-04-03 00:22:06 +02001198/* This function initialises the Lua environment stored in the stream.
1199 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001200 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001201 *
1202 * This function is particular. it initialises a new Lua thread. If the
1203 * initialisation fails (example: out of memory error), the lua function
1204 * throws an error (longjmp).
1205 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001206 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001207 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001208 * threads appear, the safe environment set a lock to ensure only one
1209 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001210 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001211 *
1212 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001213 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001214 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001215 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001216 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001217 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001218 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001219 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001220int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001221{
1222 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001223 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001224 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001225 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001226 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001227 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001228 if (!already_safe) {
1229 if (!SET_SAFE_LJMP_PARENT(lua)) {
1230 lua->Tref = LUA_REFNIL;
1231 return 0;
1232 }
1233 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001234 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001235 if (!lua->T) {
1236 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001237 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001238 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001239 return 0;
1240 }
1241 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001242 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001243 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001244 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001245 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001246 return 1;
1247}
1248
Willy Tarreau87b09662015-04-03 00:22:06 +02001249/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001250 * is destroyed. The destroy also the memory context. The struct "lua"
1251 * is not freed.
1252 */
1253void hlua_ctx_destroy(struct hlua *lua)
1254{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001255 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001256 return;
1257
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001258 if (!lua->T)
1259 goto end;
1260
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001261 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001262 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001263
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001264 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001265 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001266 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001267 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001268
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001269 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001270 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001271 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001272 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001273 /* Forces a garbage collecting process. If the Lua program is finished
1274 * without error, we run the GC on the thread pointer. Its freed all
1275 * the unused memory.
1276 * If the thread is finnish with an error or is currently yielded,
1277 * it seems that the GC applied on the thread doesn't clean anything,
1278 * so e run the GC on the main thread.
1279 * NOTE: maybe this action locks all the Lua threads untiml the en of
1280 * the garbage collection.
1281 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001282 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001283 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001284 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001285 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001286 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001287 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001288
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001289 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001290
1291end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001292 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001293}
1294
1295/* This function is used to restore the Lua context when a coroutine
1296 * fails. This function copy the common memory between old coroutine
1297 * and the new coroutine. The old coroutine is destroyed, and its
1298 * replaced by the new coroutine.
1299 * If the flag "keep_msg" is set, the last entry of the old is assumed
1300 * as string error message and it is copied in the new stack.
1301 */
1302static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1303{
1304 lua_State *T;
1305 int new_ref;
1306
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001307 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001308 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001309 if (!T)
1310 return 0;
1311
1312 /* Copy last error message. */
1313 if (keep_msg)
1314 lua_xmove(lua->T, T, 1);
1315
1316 /* Copy data between the coroutines. */
1317 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1318 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001319 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001320
1321 /* Destroy old data. */
1322 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1323
1324 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001325 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001326
1327 /* Fill the struct with the new coroutine values. */
1328 lua->Mref = new_ref;
1329 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001330 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001331
1332 /* Set context. */
1333 hlua_sethlua(lua);
1334
1335 return 1;
1336}
1337
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001338void hlua_hook(lua_State *L, lua_Debug *ar)
1339{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001340 struct hlua *hlua;
1341
1342 /* Get hlua struct, or NULL if we execute from main lua state */
1343 hlua = hlua_gethlua(L);
1344 if (!hlua)
1345 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001346
1347 /* Lua cannot yield when its returning from a function,
1348 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001349 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001350 */
1351 if (lua_gethookmask(L) & LUA_MASKRET) {
1352 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1353 return;
1354 }
1355
1356 /* restore the interrupt condition. */
1357 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1358
1359 /* If we interrupt the Lua processing in yieldable state, we yield.
1360 * If the state is not yieldable, trying yield causes an error.
1361 */
1362 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001363 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001364
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001365 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001366 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001367 hlua->run_time += now_ms - hlua->start_time;
1368 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001369 lua_pushfstring(L, "execution timeout");
1370 WILL_LJMP(lua_error(L));
1371 }
1372
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001373 /* Update the start time. */
1374 hlua->start_time = now_ms;
1375
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001376 /* Try to interrupt the process at the end of the current
1377 * unyieldable function.
1378 */
1379 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001380}
1381
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001382/* This function start or resumes the Lua stack execution. If the flag
1383 * "yield_allowed" if no set and the LUA stack execution returns a yield
1384 * The function return an error.
1385 *
1386 * The function can returns 4 values:
1387 * - HLUA_E_OK : The execution is terminated without any errors.
1388 * - HLUA_E_AGAIN : The execution must continue at the next associated
1389 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001390 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001391 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001392 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001393 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001394 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001395 * LUA code.
1396 */
1397static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1398{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001399#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1400 int nres;
1401#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001402 int ret;
1403 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001404 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001405
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001406 /* Initialise run time counter. */
1407 if (!HLUA_IS_RUNNING(lua))
1408 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001409
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001410 /* Lock the whole Lua execution. This lock must be before the
1411 * label "resume_execution".
1412 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001413 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001414 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001415
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001416resume_execution:
1417
1418 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1419 * instructions. it is used for preventing infinite loops.
1420 */
1421 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1422
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001423 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001424 HLUA_SET_RUN(lua);
1425 HLUA_CLR_CTRLYIELD(lua);
1426 HLUA_CLR_WAKERESWR(lua);
1427 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001428 HLUA_CLR_NOYIELD(lua);
1429 if (!yield_allowed)
1430 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001431
Christopher Fauletbc275a92020-02-26 14:55:16 +01001432 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001433 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001434 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001435
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001436 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001437#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001438 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001439#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001440 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001441#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001442 switch (ret) {
1443
1444 case LUA_OK:
1445 ret = HLUA_E_OK;
1446 break;
1447
1448 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001449 /* Check if the execution timeout is expired. It it is the case, we
1450 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001451 */
Willy Tarreau55542642021-10-08 09:33:24 +02001452 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001453 lua->run_time += now_ms - lua->start_time;
1454 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001455 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001456 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001457 break;
1458 }
1459 /* Process the forced yield. if the general yield is not allowed or
1460 * if no task were associated this the current Lua execution
1461 * coroutine, we resume the execution. Else we want to return in the
1462 * scheduler and we want to be waked up again, to continue the
1463 * current Lua execution. So we schedule our own task.
1464 */
1465 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001466 if (!yield_allowed || !lua->task)
1467 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001468 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001469 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001470 if (!yield_allowed) {
1471 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001472 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001473 break;
1474 }
1475 ret = HLUA_E_AGAIN;
1476 break;
1477
1478 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001479
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001480 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001481 * because the errors ares the only one mean to return immediately
1482 * from and lua execution.
1483 */
1484 if (lua->flags & HLUA_EXIT) {
1485 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001486 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001487 break;
1488 }
1489
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001490 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001491 if (!lua_checkstack(lua->T, 1)) {
1492 ret = HLUA_E_ERR;
1493 break;
1494 }
1495 msg = lua_tostring(lua->T, -1);
1496 lua_settop(lua->T, 0); /* Empty the stack. */
1497 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001498 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001499 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001500 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001501 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001502 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001503 ret = HLUA_E_ERRMSG;
1504 break;
1505
1506 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001507 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001508 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001509 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001510 break;
1511
1512 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001513 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001514 if (!lua_checkstack(lua->T, 1)) {
1515 ret = HLUA_E_ERR;
1516 break;
1517 }
1518 msg = lua_tostring(lua->T, -1);
1519 lua_settop(lua->T, 0); /* Empty the stack. */
1520 lua_pop(lua->T, 1);
1521 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001522 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001523 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001524 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001525 ret = HLUA_E_ERRMSG;
1526 break;
1527
1528 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001529 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001530 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001531 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001532 break;
1533 }
1534
1535 switch (ret) {
1536 case HLUA_E_AGAIN:
1537 break;
1538
1539 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001540 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001541 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001542 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001543 break;
1544
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001545 case HLUA_E_ETMOUT:
1546 case HLUA_E_NOMEM:
1547 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001548 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001549 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001550 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001551 hlua_ctx_renew(lua, 0);
1552 break;
1553
1554 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001555 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001556 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001557 break;
1558 }
1559
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001560 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001561 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001562 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001563
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001564 return ret;
1565}
1566
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001567/* This function exit the current code. */
1568__LJMP static int hlua_done(lua_State *L)
1569{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001570 struct hlua *hlua;
1571
1572 /* Get hlua struct, or NULL if we execute from main lua state */
1573 hlua = hlua_gethlua(L);
1574 if (!hlua)
1575 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001576
1577 hlua->flags |= HLUA_EXIT;
1578 WILL_LJMP(lua_error(L));
1579
1580 return 0;
1581}
1582
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001583/* This function is an LUA binding. It provides a function
1584 * for deleting ACL from a referenced ACL file.
1585 */
1586__LJMP static int hlua_del_acl(lua_State *L)
1587{
1588 const char *name;
1589 const char *key;
1590 struct pat_ref *ref;
1591
1592 MAY_LJMP(check_args(L, 2, "del_acl"));
1593
1594 name = MAY_LJMP(luaL_checkstring(L, 1));
1595 key = MAY_LJMP(luaL_checkstring(L, 2));
1596
1597 ref = pat_ref_lookup(name);
1598 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001599 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001600
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001601 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001602 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001603 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001604 return 0;
1605}
1606
1607/* This function is an LUA binding. It provides a function
1608 * for deleting map entry from a referenced map file.
1609 */
1610static int hlua_del_map(lua_State *L)
1611{
1612 const char *name;
1613 const char *key;
1614 struct pat_ref *ref;
1615
1616 MAY_LJMP(check_args(L, 2, "del_map"));
1617
1618 name = MAY_LJMP(luaL_checkstring(L, 1));
1619 key = MAY_LJMP(luaL_checkstring(L, 2));
1620
1621 ref = pat_ref_lookup(name);
1622 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001623 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001624
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001625 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001626 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001627 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001628 return 0;
1629}
1630
1631/* This function is an LUA binding. It provides a function
1632 * for adding ACL pattern from a referenced ACL file.
1633 */
1634static int hlua_add_acl(lua_State *L)
1635{
1636 const char *name;
1637 const char *key;
1638 struct pat_ref *ref;
1639
1640 MAY_LJMP(check_args(L, 2, "add_acl"));
1641
1642 name = MAY_LJMP(luaL_checkstring(L, 1));
1643 key = MAY_LJMP(luaL_checkstring(L, 2));
1644
1645 ref = pat_ref_lookup(name);
1646 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001647 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001648
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001649 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001650 if (pat_ref_find_elt(ref, key) == NULL)
1651 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001652 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001653 return 0;
1654}
1655
1656/* This function is an LUA binding. It provides a function
1657 * for setting map pattern and sample from a referenced map
1658 * file.
1659 */
1660static int hlua_set_map(lua_State *L)
1661{
1662 const char *name;
1663 const char *key;
1664 const char *value;
1665 struct pat_ref *ref;
1666
1667 MAY_LJMP(check_args(L, 3, "set_map"));
1668
1669 name = MAY_LJMP(luaL_checkstring(L, 1));
1670 key = MAY_LJMP(luaL_checkstring(L, 2));
1671 value = MAY_LJMP(luaL_checkstring(L, 3));
1672
1673 ref = pat_ref_lookup(name);
1674 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001675 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001676
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001677 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001678 if (pat_ref_find_elt(ref, key) != NULL)
1679 pat_ref_set(ref, key, value, NULL);
1680 else
1681 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001682 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001683 return 0;
1684}
1685
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001686/* A class is a lot of memory that contain data. This data can be a table,
1687 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001688 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001689 * the name of the object (_G[<name>] = <metable> ).
1690 *
1691 * A metable is a table that modify the standard behavior of a standard
1692 * access to the associated data. The entries of this new metatable are
1693 * defined as is:
1694 *
1695 * http://lua-users.org/wiki/MetatableEvents
1696 *
1697 * __index
1698 *
1699 * we access an absent field in a table, the result is nil. This is
1700 * true, but it is not the whole truth. Actually, such access triggers
1701 * the interpreter to look for an __index metamethod: If there is no
1702 * such method, as usually happens, then the access results in nil;
1703 * otherwise, the metamethod will provide the result.
1704 *
1705 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1706 * the key does not appear in the table, but the metatable has an __index
1707 * property:
1708 *
1709 * - if the value is a function, the function is called, passing in the
1710 * table and the key; the return value of that function is returned as
1711 * the result.
1712 *
1713 * - if the value is another table, the value of the key in that table is
1714 * asked for and returned (and if it doesn't exist in that table, but that
1715 * table's metatable has an __index property, then it continues on up)
1716 *
1717 * - Use "rawget(myTable,key)" to skip this metamethod.
1718 *
1719 * http://www.lua.org/pil/13.4.1.html
1720 *
1721 * __newindex
1722 *
1723 * Like __index, but control property assignment.
1724 *
1725 * __mode - Control weak references. A string value with one or both
1726 * of the characters 'k' and 'v' which specifies that the the
1727 * keys and/or values in the table are weak references.
1728 *
1729 * __call - Treat a table like a function. When a table is followed by
1730 * parenthesis such as "myTable( 'foo' )" and the metatable has
1731 * a __call key pointing to a function, that function is invoked
1732 * (passing any specified arguments) and the return value is
1733 * returned.
1734 *
1735 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1736 * called, if the metatable for myTable has a __metatable
1737 * key, the value of that key is returned instead of the
1738 * actual metatable.
1739 *
1740 * __tostring - Control string representation. When the builtin
1741 * "tostring( myTable )" function is called, if the metatable
1742 * for myTable has a __tostring property set to a function,
1743 * that function is invoked (passing myTable to it) and the
1744 * return value is used as the string representation.
1745 *
1746 * __len - Control table length. When the table length is requested using
1747 * the length operator ( '#' ), if the metatable for myTable has
1748 * a __len key pointing to a function, that function is invoked
1749 * (passing myTable to it) and the return value used as the value
1750 * of "#myTable".
1751 *
1752 * __gc - Userdata finalizer code. When userdata is set to be garbage
1753 * collected, if the metatable has a __gc field pointing to a
1754 * function, that function is first invoked, passing the userdata
1755 * to it. The __gc metamethod is not called for tables.
1756 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1757 *
1758 * Special metamethods for redefining standard operators:
1759 * http://www.lua.org/pil/13.1.html
1760 *
1761 * __add "+"
1762 * __sub "-"
1763 * __mul "*"
1764 * __div "/"
1765 * __unm "!"
1766 * __pow "^"
1767 * __concat ".."
1768 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001769 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001770 * http://www.lua.org/pil/13.2.html
1771 *
1772 * __eq "=="
1773 * __lt "<"
1774 * __le "<="
1775 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001776
1777/*
1778 *
1779 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001780 * Class Map
1781 *
1782 *
1783 */
1784
1785/* Returns a struct hlua_map if the stack entry "ud" is
1786 * a class session, otherwise it throws an error.
1787 */
1788__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1789{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001790 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001791}
1792
1793/* This function is the map constructor. It don't need
1794 * the class Map object. It creates and return a new Map
1795 * object. It must be called only during "body" or "init"
1796 * context because it process some filesystem accesses.
1797 */
1798__LJMP static int hlua_map_new(struct lua_State *L)
1799{
1800 const char *fn;
1801 int match = PAT_MATCH_STR;
1802 struct sample_conv conv;
1803 const char *file = "";
1804 int line = 0;
1805 lua_Debug ar;
1806 char *err = NULL;
1807 struct arg args[2];
1808
1809 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1810 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1811
1812 fn = MAY_LJMP(luaL_checkstring(L, 1));
1813
1814 if (lua_gettop(L) >= 2) {
1815 match = MAY_LJMP(luaL_checkinteger(L, 2));
1816 if (match < 0 || match >= PAT_MATCH_NUM)
1817 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1818 }
1819
1820 /* Get Lua filename and line number. */
1821 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1822 lua_getinfo(L, "Sl", &ar); /* get info about it */
1823 if (ar.currentline > 0) { /* is there info? */
1824 file = ar.short_src;
1825 line = ar.currentline;
1826 }
1827 }
1828
1829 /* fill fake sample_conv struct. */
1830 conv.kw = ""; /* unused. */
1831 conv.process = NULL; /* unused. */
1832 conv.arg_mask = 0; /* unused. */
1833 conv.val_args = NULL; /* unused. */
1834 conv.out_type = SMP_T_STR;
1835 conv.private = (void *)(long)match;
1836 switch (match) {
1837 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1838 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1839 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1840 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1841 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1842 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1843 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001844 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001845 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1846 default:
1847 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1848 }
1849
1850 /* fill fake args. */
1851 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001852 args[0].data.str.area = strdup(fn);
1853 args[0].data.str.data = strlen(fn);
1854 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001855 args[1].type = ARGT_STOP;
1856
1857 /* load the map. */
1858 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001859 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001860 * free the err variable.
1861 */
1862 luaL_where(L, 1);
1863 lua_pushfstring(L, "'new': %s.", err);
1864 lua_concat(L, 2);
1865 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001866 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001867 WILL_LJMP(lua_error(L));
1868 }
1869
1870 /* create the lua object. */
1871 lua_newtable(L);
1872 lua_pushlightuserdata(L, args[0].data.map);
1873 lua_rawseti(L, -2, 0);
1874
1875 /* Pop a class Map metatable and affect it to the userdata. */
1876 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1877 lua_setmetatable(L, -2);
1878
1879
1880 return 1;
1881}
1882
1883__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1884{
1885 struct map_descriptor *desc;
1886 struct pattern *pat;
1887 struct sample smp;
1888
1889 MAY_LJMP(check_args(L, 2, "lookup"));
1890 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001891 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001892 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001893 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001894 }
1895 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001896 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001897 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001898 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 +01001899 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001900 }
1901
1902 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001903 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001904 if (str)
1905 lua_pushstring(L, "");
1906 else
1907 lua_pushnil(L);
1908 return 1;
1909 }
1910
1911 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001912 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001913 return 1;
1914}
1915
1916__LJMP static int hlua_map_lookup(struct lua_State *L)
1917{
1918 return _hlua_map_lookup(L, 0);
1919}
1920
1921__LJMP static int hlua_map_slookup(struct lua_State *L)
1922{
1923 return _hlua_map_lookup(L, 1);
1924}
1925
1926/*
1927 *
1928 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001929 * Class Socket
1930 *
1931 *
1932 */
1933
1934__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1935{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001936 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001937}
1938
1939/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001940 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 * received.
1942 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001943static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001944{
Willy Tarreau5321da92022-05-06 11:57:34 +02001945 struct hlua_csk_ctx *ctx = appctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02001946 struct conn_stream *cs = appctx_cs(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947
Willy Tarreau5321da92022-05-06 11:57:34 +02001948 if (ctx->die) {
Christopher Fauletda098e62022-03-31 17:44:45 +02001949 cs_shutw(cs);
1950 cs_shutr(cs);
Christopher Faulet908628c2022-03-25 16:43:49 +01001951 cs_ic(cs)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001952 notification_wake(&ctx->wake_on_read);
1953 notification_wake(&ctx->wake_on_write);
Christopher Faulet908628c2022-03-25 16:43:49 +01001954 stream_shutdown(__cs_strm(cs), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001955 }
1956
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001957 /* If we can't write, wakeup the pending write signals. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001958 if (channel_output_closed(cs_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001959 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001960
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001961 /* If we can't read, wakeup the pending read signals. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001962 if (channel_input_closed(cs_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001963 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001964
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001965 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001966 * to be notified whenever the connection completes.
1967 */
Christopher Faulet62e75742022-03-31 09:16:34 +02001968 if (cs_opposite(cs)->state < CS_ST_EST) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001969 cs_cant_get(cs);
1970 cs_rx_conn_blk(cs);
1971 cs_rx_endp_more(cs);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001972 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001973 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974
1975 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001976 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001977
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001978 /* Wake the tasks which wants to write if the buffer have available space. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001979 if (channel_may_recv(cs_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001980 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001981
1982 /* Wake the tasks which wants to read if the buffer contains data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001983 if (!channel_is_empty(cs_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001984 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001985
1986 /* Some data were injected in the buffer, notify the stream
1987 * interface.
1988 */
Christopher Faulet908628c2022-03-25 16:43:49 +01001989 if (!channel_is_empty(cs_ic(cs)))
Christopher Faulet13045f02022-04-01 14:23:38 +02001990 cs_update(cs);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001991
1992 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001993 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001994 */
Willy Tarreau5321da92022-05-06 11:57:34 +02001995 if (notification_registered(&ctx->wake_on_write))
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001996 cs_rx_endp_more(cs);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997}
1998
Willy Tarreau87b09662015-04-03 00:22:06 +02001999/* This function is called when the "struct stream" is destroyed.
2000 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002001 * Wake all the pending signals.
2002 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002003static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002004{
Willy Tarreau5321da92022-05-06 11:57:34 +02002005 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002006 struct xref *peer;
2007
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002008 /* Remove my link in the original object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002009 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002010 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02002011 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012
2013 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002014 notification_wake(&ctx->wake_on_read);
2015 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002016}
2017
2018/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002019 * uses this object. If the stream does not exists, just quit.
2020 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002021 * pending signal can rest in the read and write lists. destroy
2022 * it.
2023 */
2024__LJMP static int hlua_socket_gc(lua_State *L)
2025{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002026 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002027 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002028 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002029
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002030 MAY_LJMP(check_args(L, 1, "__gc"));
2031
2032 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002033 peer = xref_get_peer_and_lock(&socket->xref);
2034 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002036
2037 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002038
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002039 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002040 ctx->die = 1;
2041 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002042
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002043 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002044 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045 return 0;
2046}
2047
2048/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002049 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002050 */
sada05ed3302018-05-11 11:48:18 -07002051__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002053 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002054 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002055 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002056 struct hlua *hlua;
2057
2058 /* Get hlua struct, or NULL if we execute from main lua state */
2059 hlua = hlua_gethlua(L);
2060 if (!hlua)
2061 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002062
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002063 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002064
2065 /* Check if we run on the same thread than the xreator thread.
2066 * We cannot access to the socket if the thread is different.
2067 */
2068 if (socket->tid != tid)
2069 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2070
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002071 peer = xref_get_peer_and_lock(&socket->xref);
2072 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002073 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002074
2075 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002076 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002077
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002078 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002079 ctx->die = 1;
2080 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002081
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002082 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002083 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002084 return 0;
2085}
2086
sada05ed3302018-05-11 11:48:18 -07002087/* The close function calls close_helper.
2088 */
2089__LJMP static int hlua_socket_close(lua_State *L)
2090{
2091 MAY_LJMP(check_args(L, 1, "close"));
2092 return hlua_socket_close_helper(L);
2093}
2094
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095/* This Lua function assumes that the stack contain three parameters.
2096 * 1 - USERDATA containing a struct socket
2097 * 2 - INTEGER with values of the macro defined below
2098 * If the integer is -1, we must read at most one line.
2099 * If the integer is -2, we ust read all the data until the
2100 * end of the stream.
2101 * If the integer is positive value, we must read a number of
2102 * bytes corresponding to this value.
2103 */
2104#define HLSR_READ_LINE (-1)
2105#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002106__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107{
2108 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2109 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002110 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002111 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002113 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002114 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002115 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002116 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002117 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002118 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002119 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002120 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002121 struct stream *s;
2122 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002123 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002124
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002125 /* Get hlua struct, or NULL if we execute from main lua state */
2126 hlua = hlua_gethlua(L);
2127
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002128 /* Check if this lua stack is schedulable. */
2129 if (!hlua || !hlua->task)
2130 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2131 "'frontend', 'backend' or 'task'"));
2132
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002133 /* Check if we run on the same thread than the xreator thread.
2134 * We cannot access to the socket if the thread is different.
2135 */
2136 if (socket->tid != tid)
2137 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2138
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002139 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002140 peer = xref_get_peer_and_lock(&socket->xref);
2141 if (!peer)
2142 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002143
2144 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2145 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002146 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002147
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002148 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002151 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152 if (nblk < 0) /* Connection close. */
2153 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002154 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002155 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002156
2157 /* remove final \r\n. */
2158 if (nblk == 1) {
2159 if (blk1[len1-1] == '\n') {
2160 len1--;
2161 skip_at_end++;
2162 if (blk1[len1-1] == '\r') {
2163 len1--;
2164 skip_at_end++;
2165 }
2166 }
2167 }
2168 else {
2169 if (blk2[len2-1] == '\n') {
2170 len2--;
2171 skip_at_end++;
2172 if (blk2[len2-1] == '\r') {
2173 len2--;
2174 skip_at_end++;
2175 }
2176 }
2177 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178 }
2179
2180 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002182 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183 if (nblk < 0) /* Connection close. */
2184 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002185 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 goto connection_empty;
2187 }
2188
2189 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002190 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002191 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002192 if (nblk < 0) /* Connection close. */
2193 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002194 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 goto connection_empty;
2196
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002197 missing_bytes = wanted - socket->b.n;
2198 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002200 len1 = missing_bytes;
2201 } if (nblk == 2 && len1 + len2 > missing_bytes)
2202 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002203 }
2204
2205 len = len1;
2206
2207 luaL_addlstring(&socket->b, blk1, len1);
2208 if (nblk == 2) {
2209 len += len2;
2210 luaL_addlstring(&socket->b, blk2, len2);
2211 }
2212
2213 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002214 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215
2216 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002217 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002218
2219 /* If the pattern reclaim to read all the data
2220 * in the connection, got out.
2221 */
2222 if (wanted == HLSR_READ_ALL)
2223 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002224 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002225 goto connection_empty;
2226
2227 /* Return result. */
2228 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002229 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 return 1;
2231
2232connection_closed:
2233
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002234 xref_unlock(&socket->xref, peer);
2235
2236no_peer:
2237
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 /* If the buffer containds data. */
2239 if (socket->b.n > 0) {
2240 luaL_pushresult(&socket->b);
2241 return 1;
2242 }
2243 lua_pushnil(L);
2244 lua_pushstring(L, "connection closed.");
2245 return 2;
2246
2247connection_empty:
2248
Willy Tarreau5321da92022-05-06 11:57:34 +02002249 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002250 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002252 }
2253 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002254 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255 return 0;
2256}
2257
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002258/* This Lua function gets two parameters. The first one can be string
2259 * or a number. If the string is "*l", the user requires one line. If
2260 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261 * If the value is a number, the user require a number of bytes equal
2262 * to the value. The default value is "*l" (a line).
2263 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002264 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265 * integer takes this values:
2266 * -1 : read a line
2267 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002268 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002269 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002270 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 * concatenated with the read data.
2272 */
2273__LJMP static int hlua_socket_receive(struct lua_State *L)
2274{
2275 int wanted = HLSR_READ_LINE;
2276 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002277 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278 char *error;
2279 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002280 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281
2282 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2283 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2284
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002285 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002287 /* Check if we run on the same thread than the xreator thread.
2288 * We cannot access to the socket if the thread is different.
2289 */
2290 if (socket->tid != tid)
2291 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2292
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 /* check for pattern. */
2294 if (lua_gettop(L) >= 2) {
2295 type = lua_type(L, 2);
2296 if (type == LUA_TSTRING) {
2297 pattern = lua_tostring(L, 2);
2298 if (strcmp(pattern, "*a") == 0)
2299 wanted = HLSR_READ_ALL;
2300 else if (strcmp(pattern, "*l") == 0)
2301 wanted = HLSR_READ_LINE;
2302 else {
2303 wanted = strtoll(pattern, &error, 10);
2304 if (*error != '\0')
2305 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2306 }
2307 }
2308 else if (type == LUA_TNUMBER) {
2309 wanted = lua_tointeger(L, 2);
2310 if (wanted < 0)
2311 WILL_LJMP(luaL_error(L, "Unsupported size."));
2312 }
2313 }
2314
2315 /* Set pattern. */
2316 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002317
2318 /* Check if we would replace the top by itself. */
2319 if (lua_gettop(L) != 2)
2320 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321
Christopher Fauletc31b2002021-05-03 10:11:13 +02002322 /* Save index of the top of the stack because since buffers are used, it
2323 * may change
2324 */
2325 lastarg = lua_gettop(L);
2326
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002327 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 luaL_buffinit(L, &socket->b);
2329
2330 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002331 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332 if (lua_type(L, 3) != LUA_TSTRING)
2333 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2334 pattern = lua_tolstring(L, 3, &len);
2335 luaL_addlstring(&socket->b, pattern, len);
2336 }
2337
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002338 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339}
2340
2341/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002342 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002344static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345{
2346 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002347 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002348 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 struct appctx *appctx;
2350 size_t buf_len;
2351 const char *buf;
2352 int len;
2353 int send_len;
2354 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002355 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002356 struct stream *s;
Christopher Faulet908628c2022-03-25 16:43:49 +01002357 struct conn_stream *cs;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002359 /* Get hlua struct, or NULL if we execute from main lua state */
2360 hlua = hlua_gethlua(L);
2361
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362 /* Check if this lua stack is schedulable. */
2363 if (!hlua || !hlua->task)
2364 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2365 "'frontend', 'backend' or 'task'"));
2366
2367 /* Get object */
2368 socket = MAY_LJMP(hlua_checksocket(L, 1));
2369 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002370 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002372 /* Check if we run on the same thread than the xreator thread.
2373 * We cannot access to the socket if the thread is different.
2374 */
2375 if (socket->tid != tid)
2376 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2377
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002378 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002379 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002380 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002381 lua_pushinteger(L, -1);
2382 return 1;
2383 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002384
2385 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2386 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002387 cs = appctx_cs(appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01002388 s = __cs_strm(cs);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002389
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002390 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002391 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002392 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002393 lua_pushinteger(L, -1);
2394 return 1;
2395 }
2396
2397 /* Update the input buffer data. */
2398 buf += sent;
2399 send_len = buf_len - sent;
2400
2401 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002402 if (sent >= buf_len) {
2403 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002404 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002405 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002406
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002407 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002408 * the request buffer if its not required.
2409 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002410 if (s->req.buf.size == 0) {
Christopher Faulet8f45eec2022-04-01 17:19:36 +02002411 if (!cs_alloc_ibuf(cs, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002412 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002413 }
2414
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002415 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002416 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002417 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002418 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002419 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002420
2421 /* send data */
2422 if (len < send_len)
2423 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002424 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002425
2426 /* "Not enough space" (-1), "Buffer too little to contain
2427 * the data" (-2) are not expected because the available length
2428 * is tested.
2429 * Other unknown error are also not expected.
2430 */
2431 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002432 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002433 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002434
sada05ed3302018-05-11 11:48:18 -07002435 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002436 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002437 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002438 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439 return 1;
2440 }
2441
2442 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002443 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002444
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002445 s->req.rex = TICK_ETERNITY;
2446 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447
2448 /* Update length sent. */
2449 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002450 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002451
2452 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002453 if (sent + len >= buf_len) {
2454 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002455 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002456 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002457
2458hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002459 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002460 xref_unlock(&socket->xref, peer);
2461 WILL_LJMP(luaL_error(L, "out of memory"));
2462 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002463 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002464 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465 return 0;
2466}
2467
2468/* This function initiate the send of data. It just check the input
2469 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002470 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002471 * "hlua_socket_write_yield" that can yield.
2472 *
2473 * The Lua function gets between 3 and 4 parameters. The first one is
2474 * the associated object. The second is a string buffer. The third is
2475 * a facultative integer that represents where is the buffer position
2476 * of the start of the data that can send. The first byte is the
2477 * position "1". The default value is "1". The fourth argument is a
2478 * facultative integer that represents where is the buffer position
2479 * of the end of the data that can send. The default is the last byte.
2480 */
2481static int hlua_socket_send(struct lua_State *L)
2482{
2483 int i;
2484 int j;
2485 const char *buf;
2486 size_t buf_len;
2487
2488 /* Check number of arguments. */
2489 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2490 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2491
2492 /* Get the string. */
2493 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2494
2495 /* Get and check j. */
2496 if (lua_gettop(L) == 4) {
2497 j = MAY_LJMP(luaL_checkinteger(L, 4));
2498 if (j < 0)
2499 j = buf_len + j + 1;
2500 if (j > buf_len)
2501 j = buf_len + 1;
2502 lua_pop(L, 1);
2503 }
2504 else
2505 j = buf_len;
2506
2507 /* Get and check i. */
2508 if (lua_gettop(L) == 3) {
2509 i = MAY_LJMP(luaL_checkinteger(L, 3));
2510 if (i < 0)
2511 i = buf_len + i + 1;
2512 if (i > buf_len)
2513 i = buf_len + 1;
2514 lua_pop(L, 1);
2515 } else
2516 i = 1;
2517
2518 /* Check bth i and j. */
2519 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002520 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002521 return 1;
2522 }
2523 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002524 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 return 1;
2526 }
2527 if (i == 0)
2528 i = 1;
2529 if (j == 0)
2530 j = 1;
2531
2532 /* Pop the string. */
2533 lua_pop(L, 1);
2534
2535 /* Update the buffer length. */
2536 buf += i - 1;
2537 buf_len = j - i + 1;
2538 lua_pushlstring(L, buf, buf_len);
2539
2540 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002541 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002543 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544}
2545
Willy Tarreau22b0a682015-06-17 19:43:49 +02002546#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002547__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002548{
2549 static char buffer[SOCKET_INFO_MAX_LEN];
2550 int ret;
2551 int len;
2552 char *p;
2553
2554 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2555 if (ret <= 0) {
2556 lua_pushnil(L);
2557 return 1;
2558 }
2559
2560 if (ret == AF_UNIX) {
2561 lua_pushstring(L, buffer+1);
2562 return 1;
2563 }
2564 else if (ret == AF_INET6) {
2565 buffer[0] = '[';
2566 len = strlen(buffer);
2567 buffer[len] = ']';
2568 len++;
2569 buffer[len] = ':';
2570 len++;
2571 p = buffer;
2572 }
2573 else if (ret == AF_INET) {
2574 p = buffer + 1;
2575 len = strlen(p);
2576 p[len] = ':';
2577 len++;
2578 }
2579 else {
2580 lua_pushnil(L);
2581 return 1;
2582 }
2583
2584 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2585 lua_pushnil(L);
2586 return 1;
2587 }
2588
2589 lua_pushstring(L, p);
2590 return 1;
2591}
2592
2593/* Returns information about the peer of the connection. */
2594__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2595{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002596 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002597 struct xref *peer;
2598 struct appctx *appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002599 struct conn_stream *cs;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002600 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002601 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002602
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002603 MAY_LJMP(check_args(L, 1, "getpeername"));
2604
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002605 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002606
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002607 /* Check if we run on the same thread than the xreator thread.
2608 * We cannot access to the socket if the thread is different.
2609 */
2610 if (socket->tid != tid)
2611 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2612
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002613 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002614 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002615 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002616 lua_pushnil(L);
2617 return 1;
2618 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002619
2620 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002621 cs = appctx_cs(appctx);
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002622 dst = cs_dst(cs_opposite(cs));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002623 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002624 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002625 lua_pushnil(L);
2626 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002627 }
2628
Christopher Faulet16f16af2021-10-27 09:34:56 +02002629 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002630 xref_unlock(&socket->xref, peer);
2631 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632}
2633
2634/* Returns information about my connection side. */
2635static int hlua_socket_getsockname(struct lua_State *L)
2636{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002637 struct hlua_socket *socket;
2638 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002639 struct appctx *appctx;
2640 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002641 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002642 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002643
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644 MAY_LJMP(check_args(L, 1, "getsockname"));
2645
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002646 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002648 /* Check if we run on the same thread than the xreator thread.
2649 * We cannot access to the socket if the thread is different.
2650 */
2651 if (socket->tid != tid)
2652 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2653
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002654 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002655 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002656 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002657 lua_pushnil(L);
2658 return 1;
2659 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002660
2661 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002662 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002663
Christopher Faulet95a61e82021-12-22 14:22:03 +01002664 conn = cs_conn(s->csb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002665 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002666 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002667 lua_pushnil(L);
2668 return 1;
2669 }
2670
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002671 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002672 xref_unlock(&socket->xref, peer);
2673 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674}
2675
2676/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002677static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002678 .obj_type = OBJ_TYPE_APPLET,
2679 .name = "<LUA_TCP>",
2680 .fct = hlua_socket_handler,
2681 .release = hlua_socket_release,
2682};
2683
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002684__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002685{
2686 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002687 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002688 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002689 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002690 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002691 struct stream *s;
2692
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002693 /* Get hlua struct, or NULL if we execute from main lua state */
2694 hlua = hlua_gethlua(L);
2695 if (!hlua)
2696 return 0;
2697
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002698 /* Check if we run on the same thread than the xreator thread.
2699 * We cannot access to the socket if the thread is different.
2700 */
2701 if (socket->tid != tid)
2702 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2703
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002704 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002705 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002706 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002707 lua_pushnil(L);
2708 lua_pushstring(L, "Can't connect");
2709 return 2;
2710 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002711
2712 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2713 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002714 s = appctx_strm(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002715
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002716 /* Check if we run on the same thread than the xreator thread.
2717 * We cannot access to the socket if the thread is different.
2718 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002719 if (socket->tid != tid) {
2720 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002721 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002722 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002723
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002724 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002725 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002726 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002727 lua_pushnil(L);
2728 lua_pushstring(L, "Can't connect");
2729 return 2;
2730 }
2731
Christopher Faulet693b23b2022-02-28 09:09:05 +01002732 appctx = __cs_appctx(s->csf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733
2734 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002735 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002736 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002737 lua_pushinteger(L, 1);
2738 return 1;
2739 }
2740
Willy Tarreau5321da92022-05-06 11:57:34 +02002741 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002742 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002743 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002744 }
2745 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002746 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002747 return 0;
2748}
2749
2750/* This function fail or initite the connection. */
2751__LJMP static int hlua_socket_connect(struct lua_State *L)
2752{
2753 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002754 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002755 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002756 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002757 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002758 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002759 int low, high;
2760 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002761 struct xref *peer;
Christopher Faulet908628c2022-03-25 16:43:49 +01002762 struct conn_stream *cs;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002763 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002764
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002765 if (lua_gettop(L) < 2)
2766 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002767
2768 /* Get args. */
2769 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002770
2771 /* Check if we run on the same thread than the xreator thread.
2772 * We cannot access to the socket if the thread is different.
2773 */
2774 if (socket->tid != tid)
2775 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2776
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002777 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002778 if (lua_gettop(L) >= 3) {
2779 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002780 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002781
Tim Duesterhus6edab862018-01-06 19:04:45 +01002782 /* Force the ip to end with a colon, to support IPv6 addresses
2783 * that are not enclosed within square brackets.
2784 */
2785 if (port > 0) {
2786 luaL_buffinit(L, &b);
2787 luaL_addstring(&b, ip);
2788 luaL_addchar(&b, ':');
2789 luaL_pushresult(&b);
2790 ip = lua_tolstring(L, lua_gettop(L), NULL);
2791 }
2792 }
2793
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002794 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002795 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002796 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002797 lua_pushnil(L);
2798 return 1;
2799 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002800
2801 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002802 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 +02002803 if (!addr) {
2804 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002805 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002806 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002807
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002808 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002809 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002810 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002811 if (port == -1) {
2812 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002813 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002814 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002815 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2816 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002817 if (port == -1) {
2818 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002819 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002820 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002821 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002822 }
2823 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002824
Willy Tarreau5321da92022-05-06 11:57:34 +02002825 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2826 appctx = csk_ctx->appctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002827 cs = appctx_cs(appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01002828 s = __cs_strm(cs);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002829
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002830 if (!sockaddr_alloc(&cs_opposite(cs)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002831 xref_unlock(&socket->xref, peer);
2832 WILL_LJMP(luaL_error(L, "connect: internal error"));
2833 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002834
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002835 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002836 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002837 if (!hlua)
2838 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002839
2840 /* inform the stream that we want to be notified whenever the
2841 * connection completes.
2842 */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002843 cs_cant_get(s->csf);
2844 cs_rx_endp_more(s->csf);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002845 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002846
Willy Tarreauf31af932020-01-14 09:59:38 +01002847 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002848
Willy Tarreau5321da92022-05-06 11:57:34 +02002849 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002850 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002851 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002852 }
2853 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002854
2855 task_wakeup(s->task, TASK_WOKEN_INIT);
2856 /* Return yield waiting for connection. */
2857
Willy Tarreau9635e032018-10-16 17:52:55 +02002858 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002859
2860 return 0;
2861}
2862
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002863#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002864__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2865{
2866 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002867 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002868 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002869
2870 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2871 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002872
2873 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002874 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002875 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002876 lua_pushnil(L);
2877 return 1;
2878 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002879
Willy Tarreau0698c802022-05-11 14:09:57 +02002880 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002881
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002882 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002883 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002884 return MAY_LJMP(hlua_socket_connect(L));
2885}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002886#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002887
2888__LJMP static int hlua_socket_setoption(struct lua_State *L)
2889{
2890 return 0;
2891}
2892
2893__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2894{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002895 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002896 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002897 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002898 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002899 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002900
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002901 MAY_LJMP(check_args(L, 2, "settimeout"));
2902
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002903 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002904
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002905 /* convert the timeout to millis */
2906 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002907
Thierry Fournier17a921b2018-03-08 09:59:02 +01002908 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002909 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002910 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2911
Mark Lakes56cc1252018-03-27 09:48:06 +02002912 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002913 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002914
2915 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002916 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002917 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002918
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002919 /* Check if we run on the same thread than the xreator thread.
2920 * We cannot access to the socket if the thread is different.
2921 */
2922 if (socket->tid != tid)
2923 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2924
Mark Lakes56cc1252018-03-27 09:48:06 +02002925 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002926 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002927 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002928 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2929 WILL_LJMP(lua_error(L));
2930 return 0;
2931 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002932
Willy Tarreau0698c802022-05-11 14:09:57 +02002933 s = appctx_strm(container_of(peer, struct hlua_csk_ctx, xref)->appctx);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002934
Cyril Bonté7bb63452018-08-17 23:51:02 +02002935 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002936 s->req.rto = tmout;
2937 s->req.wto = tmout;
2938 s->res.rto = tmout;
2939 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002940 s->req.rex = tick_add_ifset(now_ms, tmout);
2941 s->req.wex = tick_add_ifset(now_ms, tmout);
2942 s->res.rex = tick_add_ifset(now_ms, tmout);
2943 s->res.wex = tick_add_ifset(now_ms, tmout);
2944
2945 s->task->expire = tick_add_ifset(now_ms, tmout);
2946 task_queue(s->task);
2947
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002948 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002949
Thierry Fourniere9636f12018-03-08 09:54:32 +01002950 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002951 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002952}
2953
2954__LJMP static int hlua_socket_new(lua_State *L)
2955{
2956 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002957 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002958 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002959 struct session *sess;
Christopher Faulet13a35e52021-12-20 15:34:16 +01002960 struct conn_stream *cs;
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002961 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002962
2963 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002964 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002965 hlua_pusherror(L, "socket: full stack");
2966 goto out_fail_conf;
2967 }
2968
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002969 /* Create the object: obj[0] = userdata. */
2970 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002971 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002972 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002973 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002974 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002975
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002976 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002977 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002978 hlua_pusherror(L, "socket: uninitialized pools.");
2979 goto out_fail_conf;
2980 }
2981
Willy Tarreau87b09662015-04-03 00:22:06 +02002982 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002983 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2984 lua_setmetatable(L, -2);
2985
Willy Tarreaud420a972015-04-06 00:39:18 +02002986 /* Create the applet context */
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +01002987 appctx = appctx_new(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002988 if (!appctx) {
2989 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002990 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002991 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002992
Willy Tarreau5321da92022-05-06 11:57:34 +02002993 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
2994 ctx->connected = 0;
2995 ctx->appctx = appctx;
2996 ctx->die = 0;
2997 LIST_INIT(&ctx->wake_on_write);
2998 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002999
Willy Tarreaud420a972015-04-06 00:39:18 +02003000 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01003001 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02003002 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003003 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet13a35e52021-12-20 15:34:16 +01003004 goto out_fail_appctx;
3005 }
3006
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +01003007 cs = cs_new_from_applet(appctx->endp, sess, &BUF_NULL);
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003008 if (!cs) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003009 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet2479e5f2022-01-19 14:50:11 +01003010 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003011 }
3012
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003013 s = DISGUISE(cs_strm(cs));
Christopher Faulet2479e5f2022-01-19 14:50:11 +01003014
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003015 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003016 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003017
Christopher Faulet6b0a0fb2022-04-04 11:29:28 +02003018 /* Configure "right" conn-stream. this "si" is used to connect
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003019 * and retrieve data from the server. The connection is initialized
3020 * with the "struct server".
3021 */
Christopher Faulet62e75742022-03-31 09:16:34 +02003022 cs_set_state(s->csb, CS_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003023
3024 /* Force destination server. */
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003025 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
3026 s->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003027
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003028 return 1;
3029
Willy Tarreaud420a972015-04-06 00:39:18 +02003030 out_fail_sess:
Christopher Faulet13a35e52021-12-20 15:34:16 +01003031 session_free(sess);
3032 out_fail_appctx:
Willy Tarreaud420a972015-04-06 00:39:18 +02003033 appctx_free(appctx);
3034 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003035 WILL_LJMP(lua_error(L));
3036 return 0;
3037}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003038
3039/*
3040 *
3041 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003042 * Class Channel
3043 *
3044 *
3045 */
3046
3047/* Returns the struct hlua_channel join to the class channel in the
3048 * stack entry "ud" or throws an argument error.
3049 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003050__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003051{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003052 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003053}
3054
Willy Tarreau47860ed2015-03-10 14:07:50 +01003055/* Pushes the channel onto the top of the stack. If the stask does not have a
3056 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003058static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003059{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003060 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003061 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003062 return 0;
3063
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003064 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003065 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003066 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003067
3068 /* Pop a class sesison metatable and affect it to the userdata. */
3069 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3070 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003071 return 1;
3072}
3073
Christopher Faulet9f55a502020-02-25 15:21:02 +01003074/* Helper function returning a filter attached to a channel at the position <ud>
3075 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003076 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003077 * initialized.
3078 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003079static 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 +01003080{
3081 struct filter *filter = NULL;
3082
3083 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3084 struct hlua_flt_ctx *flt_ctx;
3085
3086 filter = lua_touserdata (L, -1);
3087 flt_ctx = filter->ctx;
3088 if (hlua_filter_from_payload(filter)) {
3089 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3090 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3091 }
3092 }
3093
3094 lua_pop(L, 1);
3095 return filter;
3096}
3097
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003098/* Copies <len> bytes of data present in the channel's buffer, starting at the
3099* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003100* responsibility to ensure <len> and <offset> are valid. It always return the
3101* length of the built string. <len> may be 0, in this case, an empty string is
3102* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003103*/
3104static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003105{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003106 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003107 luaL_Buffer b;
3108
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003109 block1 = len;
3110 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3111 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3112 block2 = len - block1;
3113
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003114 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003115 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3116 if (block2)
3117 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003118 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003119 return len;
3120}
3121
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003122/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3123 * function returns -1 if data cannot be copied. Otherwise, it returns the
3124 * number of bytes copied.
3125 */
3126static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3127{
3128 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003129
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003130 /* Nothing to do, just return */
3131 if (unlikely(istlen(str) == 0))
3132 goto end;
3133
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003134 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003135 ret = -1;
3136 goto end;
3137 }
3138 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3139
3140 end:
3141 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003142}
3143
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003144/* Removes <len> bytes of data at the absolute position <offset>.
3145 */
3146static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3147{
3148 size_t end = offset + len;
3149
3150 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3151 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3152 b_data(&chn->buf) - end, -len);
3153 b_sub(&chn->buf, len);
3154}
3155
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003156/* Copies input data in the channel's buffer. It is possible to set a specific
3157 * offset (0 by default) and a length (all remaining input data starting for the
3158 * offset by default). If there is not enough input data and more data can be
3159 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003160 *
3161 * From an action, All input data are considered. For a filter, the offset and
3162 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003163 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003164__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003165{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003166 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003167 struct filter *filter;
3168 size_t input, output;
3169 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003170
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003171 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003172
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003173 output = co_data(chn);
3174 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003175
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003176 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3177 if (filter && !hlua_filter_from_payload(filter))
3178 WILL_LJMP(lua_error(L));
3179
3180 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003181 if (lua_gettop(L) > 1) {
3182 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3183 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003184 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003185 offset += output;
3186 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003187 lua_pushfstring(L, "offset out of range.");
3188 WILL_LJMP(lua_error(L));
3189 }
3190 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003191 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003192 if (lua_gettop(L) == 3) {
3193 len = MAY_LJMP(luaL_checkinteger(L, 3));
3194 if (!len)
3195 goto dup;
3196 if (len == -1)
3197 len = global.tune.bufsize;
3198 if (len < 0) {
3199 lua_pushfstring(L, "length out of range.");
3200 WILL_LJMP(lua_error(L));
3201 }
3202 }
3203
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003204 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003205 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3206 /* Yield waiting for more data, as requested */
3207 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3208 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003209 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210 }
3211
3212 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003213 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003214 return 1;
3215}
3216
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003217/* Copies the first line (including the trailing LF) of input data in the
3218 * channel's buffer. It is possible to set a specific offset (0 by default) and
3219 * a length (all remaining input data starting for the offset by default). If
3220 * there is not enough input data and more data can be received, the function
3221 * yields. If a length is explicitly specified, no more data are
3222 * copied. Otherwise, if no LF is found and more data can be received, this
3223 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003224 *
3225 * From an action, All input data are considered. For a filter, the offset and
3226 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003227 */
3228__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003229{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003230 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003231 struct filter *filter;
3232 size_t l, input, output;
3233 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003234
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003235 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003236 output = co_data(chn);
3237 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003238
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003239 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3240 if (filter && !hlua_filter_from_payload(filter))
3241 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003242
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003243 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003244 if (lua_gettop(L) > 1) {
3245 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3246 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003247 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003248 offset += output;
3249 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003250 lua_pushfstring(L, "offset out of range.");
3251 WILL_LJMP(lua_error(L));
3252 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003253 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003254
3255 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003256 if (lua_gettop(L) == 3) {
3257 len = MAY_LJMP(luaL_checkinteger(L, 3));
3258 if (!len)
3259 goto dup;
3260 if (len == -1)
3261 len = global.tune.bufsize;
3262 if (len < 0) {
3263 lua_pushfstring(L, "length out of range.");
3264 WILL_LJMP(lua_error(L));
3265 }
3266 }
3267
3268 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003269 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003270 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003271 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003272 len = l+1;
3273 goto dup;
3274 }
3275 }
3276
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003277 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003278 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3279 /* Yield waiting for more data */
3280 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3281 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003282 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003283 }
3284
3285 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003286 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003287 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003288}
3289
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003290/* [ DEPRECATED ]
3291 *
3292 * Duplicate all input data foud in the channel's buffer. The data are not
3293 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003294 *
3295 * From an action, All input data are considered. For a filter, the offset and
3296 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003297 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003298__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003299{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003300 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003301 struct filter *filter;
3302 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003303
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003304 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003305 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003306 if (IS_HTX_STRM(chn_strm(chn))) {
3307 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3308 WILL_LJMP(lua_error(L));
3309 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003310
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003311 offset = co_data(chn);
3312 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003313
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003314 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3315 if (filter && !hlua_filter_from_payload(filter))
3316 WILL_LJMP(lua_error(L));
3317
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003318 if (!ci_data(chn) && channel_input_closed(chn)) {
3319 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003320 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003321 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003322
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003323 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003324 return 1;
3325}
3326
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003327/* [ DEPRECATED ]
3328 *
3329 * Get all input data foud in the channel's buffer. The data are removed from
3330 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3331 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003332 *
3333 * From an action, All input data are considered. For a filter, the offset and
3334 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003335 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003336__LJMP static int hlua_channel_get(lua_State *L)
3337{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003338 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003339 struct filter *filter;
3340 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003341 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003342
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003343 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003344 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3345 if (IS_HTX_STRM(chn_strm(chn))) {
3346 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3347 WILL_LJMP(lua_error(L));
3348 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003349
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003350 offset = co_data(chn);
3351 len = ci_data(chn);
3352
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003353 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3354 if (filter && !hlua_filter_from_payload(filter))
3355 WILL_LJMP(lua_error(L));
3356
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003357 if (!ci_data(chn) && channel_input_closed(chn)) {
3358 lua_pushnil(L);
3359 return 1;
3360 }
3361
3362 ret = _hlua_channel_dup(chn, L, offset, len);
3363 _hlua_channel_delete(chn, offset, ret);
3364 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003365}
3366
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003367/* This functions consumes and returns one line. If the channel is closed,
3368 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003369 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003370 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003371 *
3372 * From an action, All input data are considered. For a filter, the offset and
3373 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003374 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003375__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003376{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003377 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003378 struct filter *filter;
3379 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003380 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003381
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003382 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003383
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003384 offset = co_data(chn);
3385 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003386
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003387 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3388 if (filter && !hlua_filter_from_payload(filter))
3389 WILL_LJMP(lua_error(L));
3390
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003391 if (!ci_data(chn) && channel_input_closed(chn)) {
3392 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003393 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003394 }
3395
3396 for (l = 0; l < len; l++) {
3397 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3398 len = l+1;
3399 goto dup;
3400 }
3401 }
3402
3403 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3404 /* Yield waiting for more data */
3405 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3406 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003407
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003408 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003409 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003410 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003411 return 1;
3412}
3413
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003414/* [ DEPRECATED ]
3415 *
3416 * Check arguments for the function "hlua_channel_getline_yield".
3417 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003418__LJMP static int hlua_channel_getline(lua_State *L)
3419{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003420 struct channel *chn;
3421
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003422 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003423 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3424 if (IS_HTX_STRM(chn_strm(chn))) {
3425 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3426 WILL_LJMP(lua_error(L));
3427 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003428 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3429}
3430
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003431/* Retrieves a given amount of input data at the given offset. By default all
3432 * available input data are returned. The offset may be negactive to start from
3433 * the end of input data. The length may be -1 to set it to the maximum buffer
3434 * size.
3435 */
3436__LJMP static int hlua_channel_get_data(lua_State *L)
3437{
3438 struct channel *chn;
3439
3440 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3441 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3442 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3443 if (IS_HTX_STRM(chn_strm(chn))) {
3444 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3445 WILL_LJMP(lua_error(L));
3446 }
3447 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3448}
3449
3450/* Retrieves a given amount of input data at the given offset. By default all
3451 * available input data are returned. The offset may be negactive to start from
3452 * the end of input data. The length may be -1 to set it to the maximum buffer
3453 * size.
3454 */
3455__LJMP static int hlua_channel_get_line(lua_State *L)
3456{
3457 struct channel *chn;
3458
3459 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3460 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3461 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3462 if (IS_HTX_STRM(chn_strm(chn))) {
3463 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3464 WILL_LJMP(lua_error(L));
3465 }
3466 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3467}
3468
3469/* Appends a string into the input side of channel. It returns the length of the
3470 * written string, or -1 if the channel is closed or if the buffer size is too
3471 * little for the data. 0 may be returned if nothing is copied. This function
3472 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003473 *
3474 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003475 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003476__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003477{
Christopher Faulet23976d92021-08-06 09:59:49 +02003478 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003479 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003480 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003481 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003482 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003483
3484 MAY_LJMP(check_args(L, 2, "append"));
3485 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003486 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003487 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003488 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003489 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003490 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003491
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003492 offset = co_data(chn);
3493 len = ci_data(chn);
3494
3495 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3496 if (filter && !hlua_filter_from_payload(filter))
3497 WILL_LJMP(lua_error(L));
3498
3499 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3500 if (ret > 0 && filter) {
3501 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3502
3503 flt_update_offsets(filter, chn, ret);
3504 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3505 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003506 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003507 return 1;
3508}
3509
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003510/* Prepends a string into the input side of channel. It returns the length of the
3511 * written string, or -1 if the channel is closed or if the buffer size is too
3512 * little for the data. 0 may be returned if nothing is copied. This function
3513 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003514 *
3515 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003516 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003517__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003518{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003519 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003520 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003521 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003522 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003523 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003524
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003525 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003526 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003527 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3528 if (IS_HTX_STRM(chn_strm(chn))) {
3529 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3530 WILL_LJMP(lua_error(L));
3531 }
3532
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003533 offset = co_data(chn);
3534 len = ci_data(chn);
3535
3536 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3537 if (filter && !hlua_filter_from_payload(filter))
3538 WILL_LJMP(lua_error(L));
3539
3540 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3541 if (ret > 0 && filter) {
3542 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3543
3544 flt_update_offsets(filter, chn, ret);
3545 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3546 }
3547
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003548 lua_pushinteger(L, ret);
3549 return 1;
3550}
3551
3552/* Inserts a given amount of input data at the given offset by a string
3553 * content. By default the string is appended at the end of input data. It
3554 * returns the length of the written string, or -1 if the channel is closed or
3555 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003556 *
3557 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003558 */
3559__LJMP static int hlua_channel_insert_data(lua_State *L)
3560{
3561 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003562 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003563 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003564 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003565 int ret, offset;
3566
3567 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3568 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3569 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3570 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003571
3572 output = co_data(chn);
3573 input = ci_data(chn);
3574
3575 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3576 if (filter && !hlua_filter_from_payload(filter))
3577 WILL_LJMP(lua_error(L));
3578
3579 offset = input + output;
3580 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003581 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003582 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003583 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003584 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003585 if (offset < output || offset > output + input) {
3586 lua_pushfstring(L, "offset out of range.");
3587 WILL_LJMP(lua_error(L));
3588 }
3589 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003590 if (IS_HTX_STRM(chn_strm(chn))) {
3591 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3592 WILL_LJMP(lua_error(L));
3593 }
3594
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003595 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3596 if (ret > 0 && filter) {
3597 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003598
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003599 flt_update_offsets(filter, chn, ret);
3600 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003601 }
3602
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003603 lua_pushinteger(L, ret);
3604 return 1;
3605}
3606/* Replaces a given amount of input data at the given offset by a string
3607 * content. By default all remaining data are removed (offset = 0 and len =
3608 * -1). It returns the length of the written string, or -1 if the channel is
3609 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003610 *
3611 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003612 */
3613__LJMP static int hlua_channel_set_data(lua_State *L)
3614{
3615 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003616 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003617 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003618 size_t sz, input, output;
3619 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003620
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003621 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3622 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3623 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3624 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003625
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003626 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003627 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003628 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003629 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003630
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003631 output = co_data(chn);
3632 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003633
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003634 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3635 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003636 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003637
3638 offset = output;
3639 if (lua_gettop(L) > 2) {
3640 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3641 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003642 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003643 offset += output;
3644 if (offset < output || offset > input + output) {
3645 lua_pushfstring(L, "offset out of range.");
3646 WILL_LJMP(lua_error(L));
3647 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003648 }
3649
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003650 len = output + input - offset;
3651 if (lua_gettop(L) == 4) {
3652 len = MAY_LJMP(luaL_checkinteger(L, 4));
3653 if (!len)
3654 goto set;
3655 if (len == -1)
3656 len = output + input - offset;
3657 if (len < 0 || offset + len > output + input) {
3658 lua_pushfstring(L, "length out of range.");
3659 WILL_LJMP(lua_error(L));
3660 }
3661 }
3662
3663 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003664 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003665 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003666 lua_pushinteger(L, -1);
3667 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003668 _hlua_channel_delete(chn, offset, len);
3669 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3670 if (filter) {
3671 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3672
3673 len -= (ret > 0 ? ret : 0);
3674 flt_update_offsets(filter, chn, -len);
3675 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3676 }
3677
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003678 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003679 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003680 return 1;
3681}
3682
3683/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003684 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003685 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003686 *
3687 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003688 */
3689__LJMP static int hlua_channel_del_data(lua_State *L)
3690{
3691 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003692 struct filter *filter;
3693 size_t input, output;
3694 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003695
3696 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3697 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3698 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003699
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003700 if (IS_HTX_STRM(chn_strm(chn))) {
3701 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3702 WILL_LJMP(lua_error(L));
3703 }
3704
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003705 output = co_data(chn);
3706 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003707
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003708 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3709 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003710 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003711
3712 offset = output;
Boyang Lie0c54352022-05-10 17:47:23 +00003713 if (lua_gettop(L) > 1) {
3714 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003715 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003716 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003717 offset += output;
3718 if (offset < output || offset > input + output) {
3719 lua_pushfstring(L, "offset out of range.");
3720 WILL_LJMP(lua_error(L));
3721 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003722 }
3723
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003724 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00003725 if (lua_gettop(L) == 3) {
3726 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003727 if (!len)
3728 goto end;
3729 if (len == -1)
3730 len = output + input - offset;
3731 if (len < 0 || offset + len > output + input) {
3732 lua_pushfstring(L, "length out of range.");
3733 WILL_LJMP(lua_error(L));
3734 }
3735 }
3736
3737 _hlua_channel_delete(chn, offset, len);
3738 if (filter) {
3739 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3740
3741 flt_update_offsets(filter, chn, -len);
3742 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3743 }
3744
3745 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003746 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003747 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003748}
3749
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003750/* Append data in the output side of the buffer. This data is immediately
3751 * sent. The function returns the amount of data written. If the buffer
3752 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003753 * if the channel is closed.
3754 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003755__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003756{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003757 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003759 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003760 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003761 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003762 struct hlua *hlua;
3763
3764 /* Get hlua struct, or NULL if we execute from main lua state */
3765 hlua = hlua_gethlua(L);
3766 if (!hlua) {
3767 lua_pushnil(L);
3768 return 1;
3769 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003770
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003771 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3772 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3773 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003774
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003775 offset = co_data(chn);
3776 len = ci_data(chn);
3777
3778 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3779 if (filter && !hlua_filter_from_payload(filter))
3780 WILL_LJMP(lua_error(L));
3781
3782
Willy Tarreau47860ed2015-03-10 14:07:50 +01003783 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003784 lua_pushinteger(L, -1);
3785 return 1;
3786 }
3787
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003788 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003789 if (len > sz -l) {
3790 if (filter) {
3791 lua_pushinteger(L, -1);
3792 return 1;
3793 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003794 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003795 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003796
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003797 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003798 if (ret == -1) {
3799 lua_pop(L, 1);
3800 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003801 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003802 }
3803 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003804 if (filter) {
3805 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3806
3807
3808 flt_update_offsets(filter, chn, ret);
3809 FLT_OFF(filter, chn) += ret;
3810 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3811 }
3812 else
3813 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003814
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003815 l += ret;
3816 lua_pop(L, 1);
3817 lua_pushinteger(L, l);
3818 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003819
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003820 if (l < sz) {
3821 /* Yield only if the channel's output is not empty.
3822 * Otherwise it means we cannot add more data. */
3823 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003824 return 1;
3825
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003826 /* If we are waiting for space in the response buffer, we
3827 * must set the flag WAKERESWR. This flag required the task
3828 * wake up if any activity is detected on the response buffer.
3829 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003830 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003831 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003832 else
3833 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003834 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003835 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003836
3837 return 1;
3838}
3839
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003840/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003841 * yield the LUA process, and resume it without checking the
3842 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003843 *
3844 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003845 */
3846__LJMP static int hlua_channel_send(lua_State *L)
3847{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003848 struct channel *chn;
3849
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003850 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003851 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3852 if (IS_HTX_STRM(chn_strm(chn))) {
3853 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3854 WILL_LJMP(lua_error(L));
3855 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003856 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003857 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003858}
3859
3860/* This function forward and amount of butes. The data pass from
3861 * the input side of the buffer to the output side, and can be
3862 * forwarded. This function never fails.
3863 *
3864 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003865 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003866 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003867__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003868{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003869 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003870 struct filter *filter;
3871 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003872 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003873 struct hlua *hlua;
3874
3875 /* Get hlua struct, or NULL if we execute from main lua state */
3876 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003877 if (!hlua) {
3878 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003879 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003880 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003881
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003882 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003883 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003884 l = MAY_LJMP(luaL_checkinteger(L, -1));
3885
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003886 offset = co_data(chn);
3887 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003888
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003889 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3890 if (filter && !hlua_filter_from_payload(filter))
3891 WILL_LJMP(lua_error(L));
3892
3893 max = fwd - l;
3894 if (max > len)
3895 max = len;
3896
3897 if (filter) {
3898 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3899
3900 FLT_OFF(filter, chn) += max;
3901 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3902 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3903 }
3904 else
3905 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003906
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003907 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003908 lua_pop(L, 1);
3909 lua_pushinteger(L, l);
3910
3911 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003912 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003913 /* The the input channel or the output channel are closed, we
3914 * must return the amount of data forwarded.
3915 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003916 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003917 return 1;
3918
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003919 /* If we are waiting for space data in the response buffer, we
3920 * must set the flag WAKERESWR. This flag required the task
3921 * wake up if any activity is detected on the response buffer.
3922 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003923 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003924 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003925 else
3926 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003927
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003928 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003929 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003930 }
3931
3932 return 1;
3933}
3934
3935/* Just check the input and prepare the stack for the previous
3936 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003937 *
3938 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003939 */
3940__LJMP static int hlua_channel_forward(lua_State *L)
3941{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003942 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003943
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003944 MAY_LJMP(check_args(L, 2, "forward"));
3945 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3946 if (IS_HTX_STRM(chn_strm(chn))) {
3947 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3948 WILL_LJMP(lua_error(L));
3949 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003950 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003951 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003952}
3953
3954/* Just returns the number of bytes available in the input
3955 * side of the buffer. This function never fails.
3956 */
3957__LJMP static int hlua_channel_get_in_len(lua_State *L)
3958{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003959 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003960 struct filter *filter;
3961 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003962
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003963 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003964 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003965
3966 output = co_data(chn);
3967 input = ci_data(chn);
3968 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3969 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3970 lua_pushinteger(L, input);
3971 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003972 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003973
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003974 lua_pushinteger(L, htx->data - co_data(chn));
3975 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003976 return 1;
3977}
3978
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003979/* Returns true if the channel is full. */
3980__LJMP static int hlua_channel_is_full(lua_State *L)
3981{
3982 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003983
3984 MAY_LJMP(check_args(L, 1, "is_full"));
3985 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003986 /* ignore the reserve, we are not on a producer side (ie in an
3987 * applet).
3988 */
3989 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003990 return 1;
3991}
3992
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003993/* Returns true if the channel may still receive data. */
3994__LJMP static int hlua_channel_may_recv(lua_State *L)
3995{
3996 struct channel *chn;
3997
3998 MAY_LJMP(check_args(L, 1, "may_recv"));
3999 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4000 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
4001 return 1;
4002}
4003
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01004004/* Returns true if the channel is the response channel. */
4005__LJMP static int hlua_channel_is_resp(lua_State *L)
4006{
4007 struct channel *chn;
4008
4009 MAY_LJMP(check_args(L, 1, "is_resp"));
4010 chn = MAY_LJMP(hlua_checkchannel(L, 1));
4011
4012 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4013 return 1;
4014}
4015
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004016/* Just returns the number of bytes available in the output
4017 * side of the buffer. This function never fails.
4018 */
4019__LJMP static int hlua_channel_get_out_len(lua_State *L)
4020{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004021 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004022 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004023
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004024 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004025 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004026
4027 output = co_data(chn);
4028 input = ci_data(chn);
4029 hlua_channel_filter(L, 1, chn, &output, &input);
4030
4031 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004032 return 1;
4033}
4034
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004035/*
4036 *
4037 *
4038 * Class Fetches
4039 *
4040 *
4041 */
4042
4043/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004044 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004045 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004046__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004047{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004048 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004049}
4050
4051/* This function creates and push in the stack a fetch object according
4052 * with a current TXN.
4053 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004054static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004055{
Willy Tarreau7073c472015-04-06 11:15:40 +02004056 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004057
4058 /* Check stack size. */
4059 if (!lua_checkstack(L, 3))
4060 return 0;
4061
4062 /* Create the object: obj[0] = userdata.
4063 * Note that the base of the Fetches object is the
4064 * transaction object.
4065 */
4066 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004067 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004068 lua_rawseti(L, -2, 0);
4069
Willy Tarreau7073c472015-04-06 11:15:40 +02004070 hsmp->s = txn->s;
4071 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004072 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004073 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004074
4075 /* Pop a class sesison metatable and affect it to the userdata. */
4076 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4077 lua_setmetatable(L, -2);
4078
4079 return 1;
4080}
4081
4082/* This function is an LUA binding. It is called with each sample-fetch.
4083 * It uses closure argument to store the associated sample-fetch. It
4084 * returns only one argument or throws an error. An error is thrown
4085 * only if an error is encountered during the argument parsing. If
4086 * the "sample-fetch" function fails, nil is returned.
4087 */
4088__LJMP static int hlua_run_sample_fetch(lua_State *L)
4089{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004090 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004091 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004092 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004093 int i;
4094 struct sample smp;
4095
4096 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004097 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004098
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004099 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004100 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004101
Thierry FOURNIERca988662015-12-20 18:43:03 +01004102 /* Check execution authorization. */
4103 if (f->use & SMP_USE_HTTP_ANY &&
4104 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4105 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4106 "is not available in Lua services", f->kw);
4107 WILL_LJMP(lua_error(L));
4108 }
4109
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004110 /* Get extra arguments. */
4111 for (i = 0; i < lua_gettop(L) - 1; i++) {
4112 if (i >= ARGM_NBARGS)
4113 break;
4114 hlua_lua2arg(L, i + 2, &args[i]);
4115 }
4116 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004117 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004118
4119 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004120 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004121
4122 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004123 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004124 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004125 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004126 }
4127
4128 /* Initialise the sample. */
4129 memset(&smp, 0, sizeof(smp));
4130
4131 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004132 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004133 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004134 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004135 lua_pushstring(L, "");
4136 else
4137 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004138 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004139 }
4140
4141 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004142 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004143 hlua_smp2lua_str(L, &smp);
4144 else
4145 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004146
4147 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004148 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004149 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004150
4151 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004152 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004153 WILL_LJMP(lua_error(L));
4154 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004155}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004156
4157/*
4158 *
4159 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004160 * Class Converters
4161 *
4162 *
4163 */
4164
4165/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004166 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004167 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004168__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004169{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004170 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004171}
4172
4173/* This function creates and push in the stack a Converters object
4174 * according with a current TXN.
4175 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004176static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004177{
Willy Tarreau7073c472015-04-06 11:15:40 +02004178 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004179
4180 /* Check stack size. */
4181 if (!lua_checkstack(L, 3))
4182 return 0;
4183
4184 /* Create the object: obj[0] = userdata.
4185 * Note that the base of the Converters object is the
4186 * same than the TXN object.
4187 */
4188 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004189 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004190 lua_rawseti(L, -2, 0);
4191
Willy Tarreau7073c472015-04-06 11:15:40 +02004192 hsmp->s = txn->s;
4193 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004194 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004195 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004196
Willy Tarreau87b09662015-04-03 00:22:06 +02004197 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004198 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4199 lua_setmetatable(L, -2);
4200
4201 return 1;
4202}
4203
4204/* This function is an LUA binding. It is called with each converter.
4205 * It uses closure argument to store the associated converter. It
4206 * returns only one argument or throws an error. An error is thrown
4207 * only if an error is encountered during the argument parsing. If
4208 * the converter function function fails, nil is returned.
4209 */
4210__LJMP static int hlua_run_sample_conv(lua_State *L)
4211{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004212 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004213 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004214 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004215 int i;
4216 struct sample smp;
4217
4218 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004219 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004220
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004221 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004222 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004223
4224 /* Get extra arguments. */
4225 for (i = 0; i < lua_gettop(L) - 2; i++) {
4226 if (i >= ARGM_NBARGS)
4227 break;
4228 hlua_lua2arg(L, i + 3, &args[i]);
4229 }
4230 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004231 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004232
4233 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004234 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004235
4236 /* Run the special args checker. */
4237 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4238 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004239 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004240 }
4241
4242 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004243 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004244 if (!hlua_lua2smp(L, 2, &smp)) {
4245 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004246 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004247 }
4248
Willy Tarreau1777ea62016-03-10 16:15:46 +01004249 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4250
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004251 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004252 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004253 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004254 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004255 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004256 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004257 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4258 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004259 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004260 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004261 }
4262
4263 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004264 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004265 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004266 lua_pushstring(L, "");
4267 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004268 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004269 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004270 }
4271
4272 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004273 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004274 hlua_smp2lua_str(L, &smp);
4275 else
4276 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004277 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004278 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004279 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004280
4281 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004282 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004283 WILL_LJMP(lua_error(L));
4284 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004285}
4286
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004287/*
4288 *
4289 *
4290 * Class AppletTCP
4291 *
4292 *
4293 */
4294
4295/* Returns a struct hlua_txn if the stack entry "ud" is
4296 * a class stream, otherwise it throws an error.
4297 */
4298__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4299{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004300 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004301}
4302
4303/* This function creates and push in the stack an Applet object
4304 * according with a current TXN.
4305 */
4306static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4307{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004308 struct hlua_appctx *luactx;
Willy Tarreau0698c802022-05-11 14:09:57 +02004309 struct stream *s = appctx_strm(ctx);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004310 struct proxy *p;
4311
4312 ALREADY_CHECKED(s);
4313 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004314
4315 /* Check stack size. */
4316 if (!lua_checkstack(L, 3))
4317 return 0;
4318
4319 /* Create the object: obj[0] = userdata.
4320 * Note that the base of the Converters object is the
4321 * same than the TXN object.
4322 */
4323 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004324 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004325 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004326 luactx->appctx = ctx;
4327 luactx->htxn.s = s;
4328 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004329
4330 /* Create the "f" field that contains a list of fetches. */
4331 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004332 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004333 return 0;
4334 lua_settable(L, -3);
4335
4336 /* Create the "sf" field that contains a list of stringsafe fetches. */
4337 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004338 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004339 return 0;
4340 lua_settable(L, -3);
4341
4342 /* Create the "c" field that contains a list of converters. */
4343 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004344 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004345 return 0;
4346 lua_settable(L, -3);
4347
4348 /* Create the "sc" field that contains a list of stringsafe converters. */
4349 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004350 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004351 return 0;
4352 lua_settable(L, -3);
4353
4354 /* Pop a class stream metatable and affect it to the table. */
4355 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4356 lua_setmetatable(L, -2);
4357
4358 return 1;
4359}
4360
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004361__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4362{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004363 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004364 struct stream *s;
4365 const char *name;
4366 size_t len;
4367 struct sample smp;
4368
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004369 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4370 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004371
4372 /* It is useles to retrieve the stream, but this function
4373 * runs only in a stream context.
4374 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004375 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004376 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004377 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004378
4379 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004380 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004381 hlua_lua2smp(L, 3, &smp);
4382
4383 /* Store the sample in a variable. */
4384 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004385
4386 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4387 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4388 else
4389 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4390
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004391 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004392}
4393
4394__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4395{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004396 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004397 struct stream *s;
4398 const char *name;
4399 size_t len;
4400 struct sample smp;
4401
4402 MAY_LJMP(check_args(L, 2, "unset_var"));
4403
4404 /* It is useles to retrieve the stream, but this function
4405 * runs only in a stream context.
4406 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004407 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004408 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004409 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004410
4411 /* Unset the variable. */
4412 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004413 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4414 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004415}
4416
4417__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4418{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004419 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004420 struct stream *s;
4421 const char *name;
4422 size_t len;
4423 struct sample smp;
4424
4425 MAY_LJMP(check_args(L, 2, "get_var"));
4426
4427 /* It is useles to retrieve the stream, but this function
4428 * runs only in a stream context.
4429 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004430 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004431 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004432 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004433
4434 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004435 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004436 lua_pushnil(L);
4437 return 1;
4438 }
4439
4440 return hlua_smp2lua(L, &smp);
4441}
4442
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004443__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4444{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004445 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4446 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004447 struct hlua *hlua;
4448
4449 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004450 if (!s->hlua)
4451 return 0;
4452 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004453
4454 MAY_LJMP(check_args(L, 2, "set_priv"));
4455
4456 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004457 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004458
4459 /* Get and store new value. */
4460 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4461 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4462
4463 return 0;
4464}
4465
4466__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4467{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004468 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4469 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004470 struct hlua *hlua;
4471
4472 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004473 if (!s->hlua) {
4474 lua_pushnil(L);
4475 return 1;
4476 }
4477 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004478
4479 /* Push configuration index in the stack. */
4480 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4481
4482 return 1;
4483}
4484
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004485/* If expected data not yet available, it returns a yield. This function
4486 * consumes the data in the buffer. It returns a string containing the
4487 * data. This string can be empty.
4488 */
4489__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4490{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004491 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02004492 struct conn_stream *cs = appctx_cs(luactx->appctx);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004493 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004494 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004495 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004496 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004497 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004498
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004499 /* Read the maximum amount of data available. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004500 ret = co_getline_nc(cs_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004501
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004502 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004503 if (ret == 0) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004504 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004505 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004506 }
4507
4508 /* End of data: commit the total strings and return. */
4509 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004510 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004511 return 1;
4512 }
4513
4514 /* Ensure that the block 2 length is usable. */
4515 if (ret == 1)
4516 len2 = 0;
4517
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004518 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004519 luaL_addlstring(&luactx->b, blk1, len1);
4520 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004521
4522 /* Consume input channel output buffer data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004523 co_skip(cs_oc(cs), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004524 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004525 return 1;
4526}
4527
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004528/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004529__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4530{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004531 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004532
4533 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004534 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004535
4536 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4537}
4538
4539/* If expected data not yet available, it returns a yield. This function
4540 * consumes the data in the buffer. It returns a string containing the
4541 * data. This string can be empty.
4542 */
4543__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4544{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004545 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02004546 struct conn_stream *cs = appctx_cs(luactx->appctx);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004547 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004548 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004549 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004550 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004551 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004552 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004554 /* Read the maximum amount of data available. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004555 ret = co_getblk_nc(cs_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004556
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004557 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004558 if (ret == 0) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004559 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004560 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004561 }
4562
4563 /* End of data: commit the total strings and return. */
4564 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004565 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004566 return 1;
4567 }
4568
4569 /* Ensure that the block 2 length is usable. */
4570 if (ret == 1)
4571 len2 = 0;
4572
4573 if (len == -1) {
4574
4575 /* If len == -1, catenate all the data avalaile and
4576 * yield because we want to get all the data until
4577 * the end of data stream.
4578 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004579 luaL_addlstring(&luactx->b, blk1, len1);
4580 luaL_addlstring(&luactx->b, blk2, len2);
Christopher Faulet908628c2022-03-25 16:43:49 +01004581 co_skip(cs_oc(cs), len1 + len2);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004582 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004583 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004584
4585 } else {
4586
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004587 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004588 if (len1 > len)
4589 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004590 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004591 len -= len1;
4592
4593 /* Copy the second block. */
4594 if (len2 > len)
4595 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004596 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004597 len -= len2;
4598
4599 /* Consume input channel output buffer data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004600 co_skip(cs_oc(cs), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004601
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004602 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004603 if (len > 0) {
4604 lua_pushinteger(L, len);
4605 lua_replace(L, 2);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004606 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004607 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004608 }
4609
4610 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004611 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004612 return 1;
4613 }
4614
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004615 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004616 hlua_pusherror(L, "Lua: internal error");
4617 WILL_LJMP(lua_error(L));
4618 return 0;
4619}
4620
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004621/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004622__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4623{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004624 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004625 int len = -1;
4626
4627 if (lua_gettop(L) > 2)
4628 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4629 if (lua_gettop(L) >= 2) {
4630 len = MAY_LJMP(luaL_checkinteger(L, 2));
4631 lua_pop(L, 1);
4632 }
4633
4634 /* Confirm or set the required length */
4635 lua_pushinteger(L, len);
4636
4637 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004638 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004639
4640 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4641}
4642
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004643/* Append data in the output side of the buffer. This data is immediately
4644 * sent. The function returns the amount of data written. If the buffer
4645 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004646 * if the channel is closed.
4647 */
4648__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4649{
4650 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004651 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004652 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4653 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau0698c802022-05-11 14:09:57 +02004654 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01004655 struct channel *chn = cs_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004656 int max;
4657
4658 /* Get the max amount of data which can write as input in the channel. */
4659 max = channel_recv_max(chn);
4660 if (max > (len - l))
4661 max = len - l;
4662
4663 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004664 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004665
4666 /* update counters. */
4667 l += max;
4668 lua_pop(L, 1);
4669 lua_pushinteger(L, l);
4670
4671 /* If some data is not send, declares the situation to the
4672 * applet, and returns a yield.
4673 */
4674 if (l < len) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004675 cs_rx_room_blk(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004676 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004677 }
4678
4679 return 1;
4680}
4681
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004682/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004683 * yield the LUA process, and resume it without checking the
4684 * input arguments.
4685 */
4686__LJMP static int hlua_applet_tcp_send(lua_State *L)
4687{
4688 MAY_LJMP(check_args(L, 2, "send"));
4689 lua_pushinteger(L, 0);
4690
4691 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4692}
4693
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004694/*
4695 *
4696 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004697 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004698 *
4699 *
4700 */
4701
4702/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004703 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004704 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004705__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004706{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004707 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004708}
4709
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004710/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004711 * according with a current TXN.
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004712 * It relies on the caller to have already reserved the room in ctx->svcctx
4713 * for the local storage of hlua_http_ctx.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004714 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004715static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004716{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004717 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004718 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004719 struct hlua_txn htxn;
Willy Tarreau0698c802022-05-11 14:09:57 +02004720 struct stream *s = appctx_strm(ctx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004721 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004722 struct htx *htx;
4723 struct htx_blk *blk;
4724 struct htx_sl *sl;
4725 struct ist path;
4726 unsigned long long len = 0;
4727 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004728 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004729
4730 /* Check stack size. */
4731 if (!lua_checkstack(L, 3))
4732 return 0;
4733
4734 /* Create the object: obj[0] = userdata.
4735 * Note that the base of the Converters object is the
4736 * same than the TXN object.
4737 */
4738 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004739 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004740 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004741 luactx->appctx = ctx;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02004742 http_ctx->status = 200; /* Default status code returned. */
4743 http_ctx->reason = NULL; /* Use default reason based on status */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004744 luactx->htxn.s = s;
4745 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004746
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004747 /* Create the "f" field that contains a list of fetches. */
4748 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004749 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004750 return 0;
4751 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004752
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004753 /* Create the "sf" field that contains a list of stringsafe fetches. */
4754 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004755 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004756 return 0;
4757 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004758
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004759 /* Create the "c" field that contains a list of converters. */
4760 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004761 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004762 return 0;
4763 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004764
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004765 /* Create the "sc" field that contains a list of stringsafe converters. */
4766 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004767 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004768 return 0;
4769 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004770
Christopher Fauleta2097962019-07-15 16:25:33 +02004771 htx = htxbuf(&s->req.buf);
4772 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004773 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004774 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004775
Christopher Fauleta2097962019-07-15 16:25:33 +02004776 /* Stores the request method. */
4777 lua_pushstring(L, "method");
4778 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4779 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004780
Christopher Fauleta2097962019-07-15 16:25:33 +02004781 /* Stores the http version. */
4782 lua_pushstring(L, "version");
4783 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4784 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004785
Christopher Fauleta2097962019-07-15 16:25:33 +02004786 /* creates an array of headers. hlua_http_get_headers() crates and push
4787 * the array on the top of the stack.
4788 */
4789 lua_pushstring(L, "headers");
4790 htxn.s = s;
4791 htxn.p = px;
4792 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004793 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004794 return 0;
4795 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004796
Amaury Denoyellec453f952021-07-06 11:40:12 +02004797 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4798 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004799 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004800 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004801
Christopher Fauleta2097962019-07-15 16:25:33 +02004802 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004803 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004804 q = p;
4805 while (q < end && *q != '?')
4806 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004807
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004808 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004809 lua_pushstring(L, "path");
4810 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004811 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004812
Christopher Fauleta2097962019-07-15 16:25:33 +02004813 /* Stores the query string. */
4814 lua_pushstring(L, "qs");
4815 if (*q == '?')
4816 q++;
4817 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004818 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004819 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004820
Christopher Fauleta2097962019-07-15 16:25:33 +02004821 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4822 struct htx_blk *blk = htx_get_blk(htx, pos);
4823 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004824
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004825 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004826 break;
4827 if (type == HTX_BLK_DATA)
4828 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004829 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004830 if (htx->extra != ULLONG_MAX)
4831 len += htx->extra;
4832
4833 /* Stores the request path. */
4834 lua_pushstring(L, "length");
4835 lua_pushinteger(L, len);
4836 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004837
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004838 /* Create an empty array of HTTP request headers. */
4839 lua_pushstring(L, "response");
4840 lua_newtable(L);
4841 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004842
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004843 /* Pop a class stream metatable and affect it to the table. */
4844 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4845 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004846
4847 return 1;
4848}
4849
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004850__LJMP static int hlua_applet_http_set_var(lua_State *L)
4851{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004852 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004853 struct stream *s;
4854 const char *name;
4855 size_t len;
4856 struct sample smp;
4857
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004858 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4859 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004860
4861 /* It is useles to retrieve the stream, but this function
4862 * runs only in a stream context.
4863 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004864 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004865 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004866 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004867
4868 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004869 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004870 hlua_lua2smp(L, 3, &smp);
4871
4872 /* Store the sample in a variable. */
4873 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004874
4875 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4876 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4877 else
4878 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4879
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004880 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004881}
4882
4883__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4884{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004885 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004886 struct stream *s;
4887 const char *name;
4888 size_t len;
4889 struct sample smp;
4890
4891 MAY_LJMP(check_args(L, 2, "unset_var"));
4892
4893 /* It is useles to retrieve the stream, but this function
4894 * runs only in a stream context.
4895 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004896 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004897 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004898 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004899
4900 /* Unset the variable. */
4901 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004902 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4903 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004904}
4905
4906__LJMP static int hlua_applet_http_get_var(lua_State *L)
4907{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004908 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004909 struct stream *s;
4910 const char *name;
4911 size_t len;
4912 struct sample smp;
4913
4914 MAY_LJMP(check_args(L, 2, "get_var"));
4915
4916 /* It is useles to retrieve the stream, but this function
4917 * runs only in a stream context.
4918 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004919 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004920 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004921 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004922
4923 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004924 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004925 lua_pushnil(L);
4926 return 1;
4927 }
4928
4929 return hlua_smp2lua(L, &smp);
4930}
4931
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004932__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4933{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004934 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4935 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004936 struct hlua *hlua;
4937
4938 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004939 if (!s->hlua)
4940 return 0;
4941 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004942
4943 MAY_LJMP(check_args(L, 2, "set_priv"));
4944
4945 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004946 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004947
4948 /* Get and store new value. */
4949 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4950 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4951
4952 return 0;
4953}
4954
4955__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4956{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004957 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4958 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004959 struct hlua *hlua;
4960
4961 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004962 if (!s->hlua) {
4963 lua_pushnil(L);
4964 return 1;
4965 }
4966 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004967
4968 /* Push configuration index in the stack. */
4969 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4970
4971 return 1;
4972}
4973
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004974/* If expected data not yet available, it returns a yield. This function
4975 * consumes the data in the buffer. It returns a string containing the
4976 * data. This string can be empty.
4977 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004978__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004979{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004980 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02004981 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01004982 struct channel *req = cs_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004983 struct htx *htx;
4984 struct htx_blk *blk;
4985 size_t count;
4986 int stop = 0;
4987
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004988 htx = htx_from_buf(&req->buf);
4989 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004990 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004991
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004992 while (count && !stop && blk) {
4993 enum htx_blk_type type = htx_get_blk_type(blk);
4994 uint32_t sz = htx_get_blksz(blk);
4995 struct ist v;
4996 uint32_t vlen;
4997 char *nl;
4998
4999 vlen = sz;
5000 if (vlen > count) {
5001 if (type != HTX_BLK_DATA)
5002 break;
5003 vlen = count;
5004 }
5005
5006 switch (type) {
5007 case HTX_BLK_UNUSED:
5008 break;
5009
5010 case HTX_BLK_DATA:
5011 v = htx_get_blk_value(htx, blk);
5012 v.len = vlen;
5013 nl = istchr(v, '\n');
5014 if (nl != NULL) {
5015 stop = 1;
5016 vlen = nl - v.ptr + 1;
5017 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005018 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005019 break;
5020
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005021 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005022 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005023 stop = 1;
5024 break;
5025
5026 default:
5027 break;
5028 }
5029
Willy Tarreau84240042022-02-28 16:51:23 +01005030 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005031 count -= vlen;
5032 if (sz == vlen)
5033 blk = htx_remove_blk(htx, blk);
5034 else {
5035 htx_cut_data_blk(htx, blk, vlen);
5036 break;
5037 }
5038 }
5039
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005040 /* The message was fully consumed and no more data are expected
5041 * (EOM flag set).
5042 */
5043 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5044 stop = 1;
5045
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005046 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005047 if (!stop) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005048 cs_cant_get(cs);
Christopher Fauleta2097962019-07-15 16:25:33 +02005049 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005050 }
5051
5052 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005053 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005054 return 1;
5055}
5056
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005057
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005058/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005059__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005060{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005061 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005062
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005063 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005064 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005065
Christopher Fauleta2097962019-07-15 16:25:33 +02005066 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005067}
5068
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005069/* If expected data not yet available, it returns a yield. This function
5070 * consumes the data in the buffer. It returns a string containing the
5071 * data. This string can be empty.
5072 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005073__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005074{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005075 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02005076 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01005077 struct channel *req = cs_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005078 struct htx *htx;
5079 struct htx_blk *blk;
5080 size_t count;
5081 int len;
5082
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005083 htx = htx_from_buf(&req->buf);
5084 len = MAY_LJMP(luaL_checkinteger(L, 2));
5085 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005086 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005087 while (count && len && blk) {
5088 enum htx_blk_type type = htx_get_blk_type(blk);
5089 uint32_t sz = htx_get_blksz(blk);
5090 struct ist v;
5091 uint32_t vlen;
5092
5093 vlen = sz;
5094 if (len > 0 && vlen > len)
5095 vlen = len;
5096 if (vlen > count) {
5097 if (type != HTX_BLK_DATA)
5098 break;
5099 vlen = count;
5100 }
5101
5102 switch (type) {
5103 case HTX_BLK_UNUSED:
5104 break;
5105
5106 case HTX_BLK_DATA:
5107 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005108 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005109 break;
5110
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005111 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005112 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005113 len = 0;
5114 break;
5115
5116 default:
5117 break;
5118 }
5119
Willy Tarreau84240042022-02-28 16:51:23 +01005120 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005121 count -= vlen;
5122 if (len > 0)
5123 len -= vlen;
5124 if (sz == vlen)
5125 blk = htx_remove_blk(htx, blk);
5126 else {
5127 htx_cut_data_blk(htx, blk, vlen);
5128 break;
5129 }
5130 }
5131
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005132 /* The message was fully consumed and no more data are expected
5133 * (EOM flag set).
5134 */
5135 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5136 len = 0;
5137
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005138 htx_to_buf(htx, &req->buf);
5139
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005140 /* If we are no other data available, yield waiting for new data. */
5141 if (len) {
5142 if (len > 0) {
5143 lua_pushinteger(L, len);
5144 lua_replace(L, 2);
5145 }
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005146 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02005147 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005148 }
5149
5150 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005151 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005152 return 1;
5153}
5154
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005155/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005156__LJMP static int hlua_applet_http_recv(lua_State *L)
5157{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005158 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005159 int len = -1;
5160
5161 /* Check arguments. */
5162 if (lua_gettop(L) > 2)
5163 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5164 if (lua_gettop(L) >= 2) {
5165 len = MAY_LJMP(luaL_checkinteger(L, 2));
5166 lua_pop(L, 1);
5167 }
5168
Christopher Fauleta2097962019-07-15 16:25:33 +02005169 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005170
Christopher Fauleta2097962019-07-15 16:25:33 +02005171 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005172 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005173
Christopher Fauleta2097962019-07-15 16:25:33 +02005174 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005175}
5176
5177/* Append data in the output side of the buffer. This data is immediately
5178 * sent. The function returns the amount of data written. If the buffer
5179 * cannot contain the data, the function yields. The function returns -1
5180 * if the channel is closed.
5181 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005182__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005183{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005184 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02005185 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01005186 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005187 struct htx *htx = htx_from_buf(&res->buf);
5188 const char *data;
5189 size_t len;
5190 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5191 int max;
5192
Christopher Faulet9060fc02019-07-03 11:39:30 +02005193 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005194 if (!max)
5195 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005196
5197 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5198
5199 /* Get the max amount of data which can write as input in the channel. */
5200 if (max > (len - l))
5201 max = len - l;
5202
5203 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005204 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005205 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005206
5207 /* update counters. */
5208 l += max;
5209 lua_pop(L, 1);
5210 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005211
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005212 /* If some data is not send, declares the situation to the
5213 * applet, and returns a yield.
5214 */
5215 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005216 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005217 htx_to_buf(htx, &res->buf);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005218 cs_rx_room_blk(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02005219 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005220 }
5221
Christopher Fauleta2097962019-07-15 16:25:33 +02005222 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005223 return 1;
5224}
5225
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005226/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005227 * yield the LUA process, and resume it without checking the
5228 * input arguments.
5229 */
5230__LJMP static int hlua_applet_http_send(lua_State *L)
5231{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005232 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005233 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005234
5235 /* We want to send some data. Headers must be sent. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005236 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005237 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5238 WILL_LJMP(lua_error(L));
5239 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005240
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005241 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005242 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005243
Christopher Fauleta2097962019-07-15 16:25:33 +02005244 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005245}
5246
5247__LJMP static int hlua_applet_http_addheader(lua_State *L)
5248{
5249 const char *name;
5250 int ret;
5251
5252 MAY_LJMP(hlua_checkapplet_http(L, 1));
5253 name = MAY_LJMP(luaL_checkstring(L, 2));
5254 MAY_LJMP(luaL_checkstring(L, 3));
5255
5256 /* Push in the stack the "response" entry. */
5257 ret = lua_getfield(L, 1, "response");
5258 if (ret != LUA_TTABLE) {
5259 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5260 "is expected as an array. %s found", lua_typename(L, ret));
5261 WILL_LJMP(lua_error(L));
5262 }
5263
5264 /* check if the header is already registered if it is not
5265 * the case, register it.
5266 */
5267 ret = lua_getfield(L, -1, name);
5268 if (ret == LUA_TNIL) {
5269
5270 /* Entry not found. */
5271 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5272
5273 /* Insert the new header name in the array in the top of the stack.
5274 * It left the new array in the top of the stack.
5275 */
5276 lua_newtable(L);
5277 lua_pushvalue(L, 2);
5278 lua_pushvalue(L, -2);
5279 lua_settable(L, -4);
5280
5281 } else if (ret != LUA_TTABLE) {
5282
5283 /* corruption error. */
5284 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5285 "is expected as an array. %s found", name, lua_typename(L, ret));
5286 WILL_LJMP(lua_error(L));
5287 }
5288
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005289 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005290 * the header value as new entry.
5291 */
5292 lua_pushvalue(L, 3);
5293 ret = lua_rawlen(L, -2);
5294 lua_rawseti(L, -2, ret + 1);
5295 lua_pushboolean(L, 1);
5296 return 1;
5297}
5298
5299__LJMP static int hlua_applet_http_status(lua_State *L)
5300{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005301 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005302 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005303 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005304 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005305
5306 if (status < 100 || status > 599) {
5307 lua_pushboolean(L, 0);
5308 return 1;
5309 }
5310
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005311 http_ctx->status = status;
5312 http_ctx->reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005313 lua_pushboolean(L, 1);
5314 return 1;
5315}
5316
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005317
Christopher Fauleta2097962019-07-15 16:25:33 +02005318__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005319{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005320 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005321 struct hlua_http_ctx *http_ctx = luactx->appctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02005322 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01005323 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005324 struct htx *htx;
5325 struct htx_sl *sl;
5326 struct h1m h1m;
5327 const char *status, *reason;
5328 const char *name, *value;
5329 size_t nlen, vlen;
5330 unsigned int flags;
5331
5332 /* Send the message at once. */
5333 htx = htx_from_buf(&res->buf);
5334 h1m_init_res(&h1m);
5335
5336 /* Use the same http version than the request. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005337 status = ultoa_r(http_ctx->status, trash.area, trash.size);
5338 reason = http_ctx->reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005339 if (reason == NULL)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005340 reason = http_get_reason(http_ctx->status);
5341 if (http_ctx->flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5343 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5344 }
5345 else {
5346 flags = HTX_SL_F_IS_RESP;
5347 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5348 }
5349 if (!sl) {
5350 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005351 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005352 WILL_LJMP(lua_error(L));
5353 }
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005354 sl->info.res.status = http_ctx->status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005355
5356 /* Get the array associated to the field "response" in the object AppletHTTP. */
5357 lua_pushvalue(L, 0);
5358 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5359 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005360 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005361 WILL_LJMP(lua_error(L));
5362 }
5363
5364 /* Browse the list of headers. */
5365 lua_pushnil(L);
5366 while(lua_next(L, -2) != 0) {
5367 /* We expect a string as -2. */
5368 if (lua_type(L, -2) != LUA_TSTRING) {
5369 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005370 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005371 lua_typename(L, lua_type(L, -2)));
5372 WILL_LJMP(lua_error(L));
5373 }
5374 name = lua_tolstring(L, -2, &nlen);
5375
5376 /* We expect an array as -1. */
5377 if (lua_type(L, -1) != LUA_TTABLE) {
5378 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 +02005379 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005380 name,
5381 lua_typename(L, lua_type(L, -1)));
5382 WILL_LJMP(lua_error(L));
5383 }
5384
5385 /* Browse the table who is on the top of the stack. */
5386 lua_pushnil(L);
5387 while(lua_next(L, -2) != 0) {
5388 int id;
5389
5390 /* We expect a number as -2. */
5391 if (lua_type(L, -2) != LUA_TNUMBER) {
5392 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 +02005393 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005394 name,
5395 lua_typename(L, lua_type(L, -2)));
5396 WILL_LJMP(lua_error(L));
5397 }
5398 id = lua_tointeger(L, -2);
5399
5400 /* We expect a string as -2. */
5401 if (lua_type(L, -1) != LUA_TSTRING) {
5402 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 +02005403 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005404 name, id,
5405 lua_typename(L, lua_type(L, -1)));
5406 WILL_LJMP(lua_error(L));
5407 }
5408 value = lua_tolstring(L, -1, &vlen);
5409
5410 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005411 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5412 int ret;
5413
5414 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5415 if (ret < 0) {
5416 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5417 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5418 name);
5419 WILL_LJMP(lua_error(L));
5420 }
5421 else if (ret == 0)
5422 goto next; /* Skip it */
5423 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005424 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5425 struct ist v = ist2(value, vlen);
5426 int ret;
5427
5428 ret = h1_parse_cont_len_header(&h1m, &v);
5429 if (ret < 0) {
5430 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005431 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005432 name);
5433 WILL_LJMP(lua_error(L));
5434 }
5435 else if (ret == 0)
5436 goto next; /* Skip it */
5437 }
5438
5439 /* Add a new header */
5440 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5441 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005442 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005443 name);
5444 WILL_LJMP(lua_error(L));
5445 }
5446 next:
5447 /* Remove the array from the stack, and get next element with a remaining string. */
5448 lua_pop(L, 1);
5449 }
5450
5451 /* Remove the array from the stack, and get next element with a remaining string. */
5452 lua_pop(L, 1);
5453 }
5454
5455 if (h1m.flags & H1_MF_CHNK)
5456 h1m.flags &= ~H1_MF_CLEN;
5457 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5458 h1m.flags |= H1_MF_XFER_LEN;
5459
5460 /* Uset HTX start-line flags */
5461 if (h1m.flags & H1_MF_XFER_ENC)
5462 flags |= HTX_SL_F_XFER_ENC;
5463 if (h1m.flags & H1_MF_XFER_LEN) {
5464 flags |= HTX_SL_F_XFER_LEN;
5465 if (h1m.flags & H1_MF_CHNK)
5466 flags |= HTX_SL_F_CHNK;
5467 else if (h1m.flags & H1_MF_CLEN)
5468 flags |= HTX_SL_F_CLEN;
5469 if (h1m.body_len == 0)
5470 flags |= HTX_SL_F_BODYLESS;
5471 }
5472 sl->flags |= flags;
5473
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005474 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005475 * and the status code implies the presence of a message body, we must
5476 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005477 * for the keepalive compliance. If the applet announces a transfer-encoding
5478 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005479 */
5480 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005481 http_ctx->status >= 200 && http_ctx->status != 204 && http_ctx->status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005482 /* Add a new header */
5483 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5484 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5485 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005486 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005487 WILL_LJMP(lua_error(L));
5488 }
5489 }
5490
5491 /* Finalize headers. */
5492 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5493 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005494 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005495 WILL_LJMP(lua_error(L));
5496 }
5497
5498 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5499 b_reset(&res->buf);
5500 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5501 WILL_LJMP(lua_error(L));
5502 }
5503
5504 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005505 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005506
5507 /* Headers sent, set the flag. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02005508 http_ctx->flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005509 return 0;
5510
5511}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005512/* We will build the status line and the headers of the HTTP response.
5513 * We will try send at once if its not possible, we give back the hand
5514 * waiting for more room.
5515 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005516__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005517{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005518 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Willy Tarreau0698c802022-05-11 14:09:57 +02005519 struct conn_stream *cs = appctx_cs(luactx->appctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01005520 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005521
5522 if (co_data(res)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005523 cs_rx_room_blk(cs);
Christopher Fauleta2097962019-07-15 16:25:33 +02005524 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005525 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005526 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005527}
5528
5529
Christopher Fauleta2097962019-07-15 16:25:33 +02005530__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005531{
Christopher Fauleta2097962019-07-15 16:25:33 +02005532 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005533}
5534
Christopher Fauleta2097962019-07-15 16:25:33 +02005535/*
5536 *
5537 *
5538 * Class HTTP
5539 *
5540 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005541 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005542
5543/* Returns a struct hlua_txn if the stack entry "ud" is
5544 * a class stream, otherwise it throws an error.
5545 */
5546__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005547{
Christopher Fauleta2097962019-07-15 16:25:33 +02005548 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5549}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005550
Christopher Fauleta2097962019-07-15 16:25:33 +02005551/* This function creates and push in the stack a HTTP object
5552 * according with a current TXN.
5553 */
5554static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5555{
5556 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005557
Christopher Fauleta2097962019-07-15 16:25:33 +02005558 /* Check stack size. */
5559 if (!lua_checkstack(L, 3))
5560 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005561
Christopher Fauleta2097962019-07-15 16:25:33 +02005562 /* Create the object: obj[0] = userdata.
5563 * Note that the base of the Converters object is the
5564 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005565 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005566 lua_newtable(L);
5567 htxn = lua_newuserdata(L, sizeof(*htxn));
5568 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005569
5570 htxn->s = txn->s;
5571 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005572 htxn->dir = txn->dir;
5573 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005574
5575 /* Pop a class stream metatable and affect it to the table. */
5576 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5577 lua_setmetatable(L, -2);
5578
5579 return 1;
5580}
5581
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005582/* This function creates and returns an array containing the status-line
5583 * elements. This function does not fails.
5584 */
5585__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5586{
5587 /* Create the table. */
5588 lua_newtable(L);
5589
5590 if (sl->flags & HTX_SL_F_IS_RESP) {
5591 lua_pushstring(L, "version");
5592 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5593 lua_settable(L, -3);
5594 lua_pushstring(L, "code");
5595 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5596 lua_settable(L, -3);
5597 lua_pushstring(L, "reason");
5598 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5599 lua_settable(L, -3);
5600 }
5601 else {
5602 lua_pushstring(L, "method");
5603 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5604 lua_settable(L, -3);
5605 lua_pushstring(L, "uri");
5606 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5607 lua_settable(L, -3);
5608 lua_pushstring(L, "version");
5609 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5610 lua_settable(L, -3);
5611 }
5612 return 1;
5613}
5614
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005615/* This function creates ans returns an array of HTTP headers.
5616 * This function does not fails. It is used as wrapper with the
5617 * 2 following functions.
5618 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005619__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005620{
Christopher Fauleta2097962019-07-15 16:25:33 +02005621 struct htx *htx;
5622 int32_t pos;
5623
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005624 /* Create the table. */
5625 lua_newtable(L);
5626
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005627
Christopher Fauleta2097962019-07-15 16:25:33 +02005628 htx = htxbuf(&msg->chn->buf);
5629 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5630 struct htx_blk *blk = htx_get_blk(htx, pos);
5631 enum htx_blk_type type = htx_get_blk_type(blk);
5632 struct ist n, v;
5633 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005634
Christopher Fauleta2097962019-07-15 16:25:33 +02005635 if (type == HTX_BLK_HDR) {
5636 n = htx_get_blk_name(htx,blk);
5637 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005638 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005639 else if (type == HTX_BLK_EOH)
5640 break;
5641 else
5642 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005643
Christopher Fauleta2097962019-07-15 16:25:33 +02005644 /* Check for existing entry:
5645 * assume that the table is on the top of the stack, and
5646 * push the key in the stack, the function lua_gettable()
5647 * perform the lookup.
5648 */
5649 lua_pushlstring(L, n.ptr, n.len);
5650 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005651
Christopher Fauleta2097962019-07-15 16:25:33 +02005652 switch (lua_type(L, -1)) {
5653 case LUA_TNIL:
5654 /* Table not found, create it. */
5655 lua_pop(L, 1); /* remove the nil value. */
5656 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5657 lua_newtable(L); /* create and push empty table. */
5658 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5659 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5660 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005661 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005662
Christopher Fauleta2097962019-07-15 16:25:33 +02005663 case LUA_TTABLE:
5664 /* Entry found: push the value in the table. */
5665 len = lua_rawlen(L, -1);
5666 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5667 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5668 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5669 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005670
Christopher Fauleta2097962019-07-15 16:25:33 +02005671 default:
5672 /* Other cases are errors. */
5673 hlua_pusherror(L, "internal error during the parsing of headers.");
5674 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005675 }
5676 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005677 return 1;
5678}
5679
5680__LJMP static int hlua_http_req_get_headers(lua_State *L)
5681{
5682 struct hlua_txn *htxn;
5683
5684 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5685 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5686
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005687 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005688 WILL_LJMP(lua_error(L));
5689
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005690 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005691}
5692
5693__LJMP static int hlua_http_res_get_headers(lua_State *L)
5694{
5695 struct hlua_txn *htxn;
5696
5697 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5698 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5699
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005700 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005701 WILL_LJMP(lua_error(L));
5702
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005703 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005704}
5705
5706/* This function replace full header, or just a value in
5707 * the request or in the response. It is a wrapper fir the
5708 * 4 following functions.
5709 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005710__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005711{
5712 size_t name_len;
5713 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5714 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5715 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005716 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005717 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005718
Dragan Dosen26743032019-04-30 15:54:36 +02005719 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005720 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5721
Christopher Fauleta2097962019-07-15 16:25:33 +02005722 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005723 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005724 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005725 return 0;
5726}
5727
5728__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5729{
5730 struct hlua_txn *htxn;
5731
5732 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5733 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5734
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005735 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005736 WILL_LJMP(lua_error(L));
5737
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005738 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005739}
5740
5741__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5742{
5743 struct hlua_txn *htxn;
5744
5745 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5746 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5747
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005748 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005749 WILL_LJMP(lua_error(L));
5750
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005751 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005752}
5753
5754__LJMP static int hlua_http_req_rep_val(lua_State *L)
5755{
5756 struct hlua_txn *htxn;
5757
5758 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5759 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5760
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005761 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005762 WILL_LJMP(lua_error(L));
5763
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005764 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005765}
5766
5767__LJMP static int hlua_http_res_rep_val(lua_State *L)
5768{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005769 struct hlua_txn *htxn;
5770
5771 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5772 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5773
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005774 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005775 WILL_LJMP(lua_error(L));
5776
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005777 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005778}
5779
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005780/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005781 * It is a wrapper for the 2 following functions.
5782 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005783__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005784{
5785 size_t len;
5786 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005787 struct htx *htx = htxbuf(&msg->chn->buf);
5788 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005789
Christopher Fauleta2097962019-07-15 16:25:33 +02005790 ctx.blk = NULL;
5791 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5792 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005793 return 0;
5794}
5795
5796__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5797{
5798 struct hlua_txn *htxn;
5799
5800 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5801 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5802
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005803 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005804 WILL_LJMP(lua_error(L));
5805
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005806 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005807}
5808
5809__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5810{
5811 struct hlua_txn *htxn;
5812
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005813 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005814 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5815
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005816 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005817 WILL_LJMP(lua_error(L));
5818
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005819 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005820}
5821
5822/* This function adds an header. It is a wrapper used by
5823 * the 2 following functions.
5824 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005825__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005826{
5827 size_t name_len;
5828 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5829 size_t value_len;
5830 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005831 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005832
Christopher Fauleta2097962019-07-15 16:25:33 +02005833 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5834 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005835 return 0;
5836}
5837
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005838__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5839{
5840 struct hlua_txn *htxn;
5841
5842 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5843 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5844
5845 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5846 WILL_LJMP(lua_error(L));
5847
5848 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5849}
5850
5851__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5852{
5853 struct hlua_txn *htxn;
5854
5855 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5856 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5857
5858 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5859 WILL_LJMP(lua_error(L));
5860
5861 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5862}
5863
5864static int hlua_http_req_set_hdr(lua_State *L)
5865{
5866 struct hlua_txn *htxn;
5867
5868 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5869 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5870
5871 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5872 WILL_LJMP(lua_error(L));
5873
5874 hlua_http_del_hdr(L, &htxn->s->txn->req);
5875 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5876}
5877
5878static int hlua_http_res_set_hdr(lua_State *L)
5879{
5880 struct hlua_txn *htxn;
5881
5882 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5883 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5884
5885 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5886 WILL_LJMP(lua_error(L));
5887
5888 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5889 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5890}
5891
5892/* This function set the method. */
5893static int hlua_http_req_set_meth(lua_State *L)
5894{
5895 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5896 size_t name_len;
5897 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5898
5899 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5900 WILL_LJMP(lua_error(L));
5901
5902 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5903 return 1;
5904}
5905
5906/* This function set the method. */
5907static int hlua_http_req_set_path(lua_State *L)
5908{
5909 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5910 size_t name_len;
5911 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5912
5913 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5914 WILL_LJMP(lua_error(L));
5915
5916 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5917 return 1;
5918}
5919
5920/* This function set the query-string. */
5921static int hlua_http_req_set_query(lua_State *L)
5922{
5923 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5924 size_t name_len;
5925 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5926
5927 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5928 WILL_LJMP(lua_error(L));
5929
5930 /* Check length. */
5931 if (name_len > trash.size - 1) {
5932 lua_pushboolean(L, 0);
5933 return 1;
5934 }
5935
5936 /* Add the mark question as prefix. */
5937 chunk_reset(&trash);
5938 trash.area[trash.data++] = '?';
5939 memcpy(trash.area + trash.data, name, name_len);
5940 trash.data += name_len;
5941
5942 lua_pushboolean(L,
5943 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5944 return 1;
5945}
5946
5947/* This function set the uri. */
5948static int hlua_http_req_set_uri(lua_State *L)
5949{
5950 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5951 size_t name_len;
5952 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5953
5954 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5955 WILL_LJMP(lua_error(L));
5956
5957 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5958 return 1;
5959}
5960
5961/* This function set the response code & optionally reason. */
5962static int hlua_http_res_set_status(lua_State *L)
5963{
5964 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5965 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5966 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5967 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5968
5969 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5970 WILL_LJMP(lua_error(L));
5971
5972 http_res_set_status(code, reason, htxn->s);
5973 return 0;
5974}
5975
5976/*
5977 *
5978 *
5979 * Class HTTPMessage
5980 *
5981 *
5982 */
5983
5984/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5985 * otherwise it throws an error.
5986 */
5987__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5988{
5989 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5990}
5991
5992/* Creates and pushes on the stack a HTTP object according with a current TXN.
5993 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005994static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005995{
5996 /* Check stack size. */
5997 if (!lua_checkstack(L, 3))
5998 return 0;
5999
6000 lua_newtable(L);
6001 lua_pushlightuserdata(L, msg);
6002 lua_rawseti(L, -2, 0);
6003
6004 /* Create the "channel" field that contains the request channel object. */
6005 lua_pushstring(L, "channel");
6006 if (!hlua_channel_new(L, msg->chn))
6007 return 0;
6008 lua_rawset(L, -3);
6009
6010 /* Pop a class stream metatable and affect it to the table. */
6011 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
6012 lua_setmetatable(L, -2);
6013
6014 return 1;
6015}
6016
6017/* Helper function returning a filter attached to the HTTP message at the
6018 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006019 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006020 * filled with output and input length respectively.
6021 */
6022static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6023{
6024 struct channel *chn = msg->chn;
6025 struct htx *htx = htxbuf(&chn->buf);
6026 struct filter *filter = NULL;
6027
6028 *offset = co_data(msg->chn);
6029 *len = htx->data - co_data(msg->chn);
6030
6031 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6032 filter = lua_touserdata (L, -1);
6033 if (msg->msg_state >= HTTP_MSG_DATA) {
6034 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6035
6036 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6037 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6038 }
6039 }
6040
6041 lua_pop(L, 1);
6042 return filter;
6043}
6044
6045/* Returns true if the channel attached to the HTTP message is the response
6046 * channel.
6047 */
6048__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6049{
6050 struct http_msg *msg;
6051
6052 MAY_LJMP(check_args(L, 1, "is_resp"));
6053 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6054
6055 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6056 return 1;
6057}
6058
6059/* Returns an array containing the elements status-line of the HTTP message. It relies
6060 * on hlua_http_get_stline().
6061 */
6062__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6063{
6064 struct http_msg *msg;
6065 struct htx *htx;
6066 struct htx_sl *sl;
6067
6068 MAY_LJMP(check_args(L, 1, "get_stline"));
6069 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6070
6071 if (msg->msg_state > HTTP_MSG_BODY)
6072 WILL_LJMP(lua_error(L));
6073
6074 htx = htxbuf(&msg->chn->buf);
6075 sl = http_get_stline(htx);
6076 if (!sl)
6077 return 0;
6078 return hlua_http_get_stline(L, sl);
6079}
6080
6081/* Returns an array containing all headers of the HTTP message. it relies on
6082 * hlua_http_get_headers().
6083 */
6084__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6085{
6086 struct http_msg *msg;
6087
6088 MAY_LJMP(check_args(L, 1, "get_headers"));
6089 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6090
6091 if (msg->msg_state > HTTP_MSG_BODY)
6092 WILL_LJMP(lua_error(L));
6093
6094 return hlua_http_get_headers(L, msg);
6095}
6096
6097/* Deletes all occurrences of an header in the HTTP message matching on its
6098 * name. It relies on hlua_http_del_hdr().
6099 */
6100__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6101{
6102 struct http_msg *msg;
6103
6104 MAY_LJMP(check_args(L, 2, "del_header"));
6105 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6106
6107 if (msg->msg_state > HTTP_MSG_BODY)
6108 WILL_LJMP(lua_error(L));
6109
6110 return hlua_http_del_hdr(L, msg);
6111}
6112
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006113/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006114 * message given its name against a regex and replaces it if it matches. It
6115 * relies on hlua_http_rep_hdr().
6116 */
6117__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6118{
6119 struct http_msg *msg;
6120
6121 MAY_LJMP(check_args(L, 4, "rep_header"));
6122 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6123
6124 if (msg->msg_state > HTTP_MSG_BODY)
6125 WILL_LJMP(lua_error(L));
6126
6127 return hlua_http_rep_hdr(L, msg, 1);
6128}
6129
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006130/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006131 * message given its name against a regex and replaces it if it matches. It
6132 * relies on hlua_http_rep_hdr().
6133 */
6134__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6135{
6136 struct http_msg *msg;
6137
6138 MAY_LJMP(check_args(L, 4, "rep_value"));
6139 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6140
6141 if (msg->msg_state > HTTP_MSG_BODY)
6142 WILL_LJMP(lua_error(L));
6143
6144 return hlua_http_rep_hdr(L, msg, 0);
6145}
6146
6147/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6148__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6149{
6150 struct http_msg *msg;
6151
6152 MAY_LJMP(check_args(L, 3, "add_header"));
6153 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6154
6155 if (msg->msg_state > HTTP_MSG_BODY)
6156 WILL_LJMP(lua_error(L));
6157
6158 return hlua_http_add_hdr(L, msg);
6159}
6160
6161/* Add an header in the HTTP message removing existing headers with the same
6162 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6163 */
6164__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6165{
6166 struct http_msg *msg;
6167
6168 MAY_LJMP(check_args(L, 3, "set_header"));
6169 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6170
6171 if (msg->msg_state > HTTP_MSG_BODY)
6172 WILL_LJMP(lua_error(L));
6173
6174 hlua_http_del_hdr(L, msg);
6175 return hlua_http_add_hdr(L, msg);
6176}
6177
6178/* Rewrites the request method. It relies on http_req_replace_stline(). */
6179__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6180{
6181 struct stream *s;
6182 struct http_msg *msg;
6183 const char *name;
6184 size_t name_len;
6185
6186 MAY_LJMP(check_args(L, 2, "set_method"));
6187 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6188 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6189
6190 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6191 WILL_LJMP(lua_error(L));
6192
6193 s = chn_strm(msg->chn);
6194 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6195 return 1;
6196}
6197
6198/* Rewrites the request path. It relies on http_req_replace_stline(). */
6199__LJMP static int hlua_http_msg_set_path(lua_State *L)
6200{
6201 struct stream *s;
6202 struct http_msg *msg;
6203 const char *name;
6204 size_t name_len;
6205
6206 MAY_LJMP(check_args(L, 2, "set_path"));
6207 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6208 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6209
6210 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6211 WILL_LJMP(lua_error(L));
6212
6213 s = chn_strm(msg->chn);
6214 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6215 return 1;
6216}
6217
6218/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6219__LJMP static int hlua_http_msg_set_query(lua_State *L)
6220{
6221 struct stream *s;
6222 struct http_msg *msg;
6223 const char *name;
6224 size_t name_len;
6225
6226 MAY_LJMP(check_args(L, 2, "set_query"));
6227 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6228 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6229
6230 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6231 WILL_LJMP(lua_error(L));
6232
6233 /* Check length. */
6234 if (name_len > trash.size - 1) {
6235 lua_pushboolean(L, 0);
6236 return 1;
6237 }
6238
6239 /* Add the mark question as prefix. */
6240 chunk_reset(&trash);
6241 trash.area[trash.data++] = '?';
6242 memcpy(trash.area + trash.data, name, name_len);
6243 trash.data += name_len;
6244
6245 s = chn_strm(msg->chn);
6246 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6247 return 1;
6248}
6249
6250/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6251__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6252{
6253 struct stream *s;
6254 struct http_msg *msg;
6255 const char *name;
6256 size_t name_len;
6257
6258 MAY_LJMP(check_args(L, 2, "set_uri"));
6259 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6260 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6261
6262 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6263 WILL_LJMP(lua_error(L));
6264
6265 s = chn_strm(msg->chn);
6266 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6267 return 1;
6268}
6269
6270/* Rewrites the response status code. It relies on http_res_set_status(). */
6271__LJMP static int hlua_http_msg_set_status(lua_State *L)
6272{
6273 struct http_msg *msg;
6274 unsigned int code;
6275 const char *reason;
6276 size_t reason_len;
6277
6278 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6279 code = MAY_LJMP(luaL_checkinteger(L, 2));
6280 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6281
6282 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6283 WILL_LJMP(lua_error(L));
6284
6285 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6286 return 1;
6287}
6288
6289/* Returns true if the HTTP message is full. */
6290__LJMP static int hlua_http_msg_is_full(lua_State *L)
6291{
6292 struct http_msg *msg;
6293
6294 MAY_LJMP(check_args(L, 1, "is_full"));
6295 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6296 lua_pushboolean(L, channel_full(msg->chn, 0));
6297 return 1;
6298}
6299
6300/* Returns true if the HTTP message may still receive data. */
6301__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6302{
6303 struct http_msg *msg;
6304 struct htx *htx;
6305
6306 MAY_LJMP(check_args(L, 1, "may_recv"));
6307 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6308 htx = htxbuf(&msg->chn->buf);
6309 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6310 return 1;
6311}
6312
6313/* Returns true if the HTTP message EOM was received */
6314__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6315{
6316 struct http_msg *msg;
6317 struct htx *htx;
6318
6319 MAY_LJMP(check_args(L, 1, "may_recv"));
6320 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6321 htx = htxbuf(&msg->chn->buf);
6322 lua_pushboolean(L, !htx_expect_more(htx));
6323 return 1;
6324}
6325
6326/* Returns the number of bytes available in the input side of the HTTP
6327 * message. This function never fails.
6328 */
6329__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6330{
6331 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006332 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006333
6334 MAY_LJMP(check_args(L, 1, "input"));
6335 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006336 hlua_http_msg_filter(L, 1, msg, &output, &input);
6337 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006338 return 1;
6339}
6340
6341/* Returns the number of bytes available in the output side of the HTTP
6342 * message. This function never fails.
6343 */
6344__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6345{
6346 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006347 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006348
6349 MAY_LJMP(check_args(L, 1, "output"));
6350 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006351 hlua_http_msg_filter(L, 1, msg, &output, &input);
6352 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006353 return 1;
6354}
6355
6356/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6357 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006358 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006359 * block. This function is called during the payload filtering, so the headers
6360 * are already scheduled for output (from the filter point of view).
6361 */
6362static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6363{
6364 struct htx *htx = htxbuf(&msg->chn->buf);
6365 struct htx_blk *blk;
6366 struct htx_ret htxret;
6367 luaL_Buffer b;
6368 int ret = 0;
6369
6370 luaL_buffinit(L, &b);
6371 htxret = htx_find_offset(htx, offset);
6372 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6373 enum htx_blk_type type = htx_get_blk_type(blk);
6374 struct ist v;
6375
6376 switch (type) {
6377 case HTX_BLK_UNUSED:
6378 break;
6379
6380 case HTX_BLK_DATA:
6381 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006382 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006383 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006384
6385 luaL_addlstring(&b, v.ptr, v.len);
6386 ret += v.len;
6387 break;
6388
6389 default:
vishnu0af4bd72021-10-24 06:46:24 +05306390 if (!ret)
6391 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006392 goto end;
6393 }
6394 offset = 0;
6395 }
6396
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006397end:
vishnu0af4bd72021-10-24 06:46:24 +05306398 if (!ret && (htx->flags & HTX_FL_EOM))
6399 goto no_data;
6400 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006401 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306402
6403 no_data:
6404 /* Remove the empty string and push nil on the stack */
6405 lua_pop(L, 1);
6406 lua_pushnil(L);
6407 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006408}
6409
6410/* Copies the string <str> to the HTTP message <msg> at the offset
6411 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006412 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006413 * the filter context.
6414 */
6415static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6416{
6417 struct htx *htx = htx_from_buf(&msg->chn->buf);
6418 struct htx_ret htxret;
6419 int /*max, */ret = 0;
6420
6421 /* Nothing to do, just return */
6422 if (unlikely(istlen(str) == 0))
6423 goto end;
6424
6425 if (istlen(str) > htx_free_data_space(htx)) {
6426 ret = -1;
6427 goto end;
6428 }
6429
6430 htxret = htx_find_offset(htx, offset);
6431 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6432 if (!htx_add_last_data(htx, str))
6433 goto end;
6434 }
6435 else {
6436 struct ist v = htx_get_blk_value(htx, htxret.blk);
6437 v.ptr += htxret.ret;
6438 v.len = 0;
6439 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6440 goto end;
6441 }
6442 ret = str.len;
6443 if (ret) {
6444 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6445 flt_update_offsets(filter, msg->chn, ret);
6446 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6447 }
6448
6449 end:
6450 htx_to_buf(htx, &msg->chn->buf);
6451 return ret;
6452}
6453
6454/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6455 * position <offset>. It stops on the first non-DATA HTX block. This function is
6456 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006457 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006458 * update the filter context.
6459 */
6460static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6461{
6462 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6463 struct htx *htx = htx_from_buf(&msg->chn->buf);
6464 struct htx_blk *blk;
6465 struct htx_ret htxret;
6466 size_t ret = 0;
6467
6468 /* Be sure <len> is always the amount of DATA to remove */
6469 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6470 htx_truncate(htx, offset);
6471 ret = len;
6472 goto end;
6473 }
6474
6475 htxret = htx_find_offset(htx, offset);
6476 blk = htxret.blk;
6477 if (htxret.ret) {
6478 struct ist v;
6479
6480 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6481 goto end;
6482 v = htx_get_blk_value(htx, blk);
6483 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006484 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006485 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006486 len -= v.len;
6487 ret += v.len;
6488 }
6489
6490
6491 while (blk && len) {
6492 enum htx_blk_type type = htx_get_blk_type(blk);
6493 uint32_t sz = htx_get_blksz(blk);
6494
6495 switch (type) {
6496 case HTX_BLK_UNUSED:
6497 break;
6498
6499 case HTX_BLK_DATA:
6500 if (len < sz) {
6501 htx_cut_data_blk(htx, blk, len);
6502 ret += len;
6503 goto end;
6504 }
6505 break;
6506
6507 default:
6508 goto end;
6509 }
6510
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006511 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006512 len -= sz;
6513 ret += sz;
6514 blk = htx_remove_blk(htx, blk);
6515 }
6516
6517end:
6518 flt_update_offsets(filter, msg->chn, -ret);
6519 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6520 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6521 * to loose the EOM flag if the message is empty.
6522 */
6523}
6524
6525/* Copies input data found in an HTTP message. Unlike the channel function used
6526 * to duplicate raw data, this one can only be called inside a filter, from
6527 * http_payload callback. So it cannot yield. An exception is returned if it is
6528 * called from another callback. If nothing was copied, a nil value is pushed on
6529 * the stack.
6530 */
6531__LJMP static int hlua_http_msg_get_body(lua_State *L)
6532{
6533 struct http_msg *msg;
6534 struct filter *filter;
6535 size_t output, input;
6536 int offset, len;
6537
6538 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6539 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6540 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6541
6542 if (msg->msg_state < HTTP_MSG_DATA)
6543 WILL_LJMP(lua_error(L));
6544
6545 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6546 if (!filter || !hlua_filter_from_payload(filter))
6547 WILL_LJMP(lua_error(L));
6548
6549 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6550 lua_pushnil(L);
6551 return 1;
6552 }
6553
6554 offset = output;
6555 if (lua_gettop(L) > 1) {
6556 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6557 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006558 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006559 offset += output;
6560 if (offset < output || offset > input + output) {
6561 lua_pushfstring(L, "offset out of range.");
6562 WILL_LJMP(lua_error(L));
6563 }
6564 }
6565 len = output + input - offset;
6566 if (lua_gettop(L) == 3) {
6567 len = MAY_LJMP(luaL_checkinteger(L, 3));
6568 if (!len)
6569 goto dup;
6570 if (len == -1)
6571 len = global.tune.bufsize;
6572 if (len < 0) {
6573 lua_pushfstring(L, "length out of range.");
6574 WILL_LJMP(lua_error(L));
6575 }
6576 }
6577
6578 dup:
6579 _hlua_http_msg_dup(msg, L, offset, len);
6580 return 1;
6581}
6582
6583/* Appends a string to the HTTP message, after all existing DATA blocks but
6584 * before the trailers, if any. It returns the amount of data written or -1 if
6585 * nothing was copied. Unlike the channel function used to append data, this one
6586 * can only be called inside a filter, from http_payload callback. So it cannot
6587 * yield. An exception is returned if it is called from another callback.
6588 */
6589__LJMP static int hlua_http_msg_append(lua_State *L)
6590{
6591 struct http_msg *msg;
6592 struct filter *filter;
6593 const char *str;
6594 size_t offset, len, sz;
6595 int ret;
6596
6597 MAY_LJMP(check_args(L, 2, "append"));
6598 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6599
6600 if (msg->msg_state < HTTP_MSG_DATA)
6601 WILL_LJMP(lua_error(L));
6602
6603 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6604 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6605 if (!filter || !hlua_filter_from_payload(filter))
6606 WILL_LJMP(lua_error(L));
6607
6608 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6609 lua_pushinteger(L, ret);
6610 return 1;
6611}
6612
6613/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6614 * returns the amount of data written or -1 if nothing was copied. Unlike the
6615 * channel function used to prepend data, this one can only be called inside a
6616 * filter, from http_payload callback. So it cannot yield. An exception is
6617 * returned if it is called from another callback.
6618 */
6619__LJMP static int hlua_http_msg_prepend(lua_State *L)
6620{
6621 struct http_msg *msg;
6622 struct filter *filter;
6623 const char *str;
6624 size_t offset, len, sz;
6625 int ret;
6626
6627 MAY_LJMP(check_args(L, 2, "prepend"));
6628 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006629
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006630 if (msg->msg_state < HTTP_MSG_DATA)
6631 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006632
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006633 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6634 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6635 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006636 WILL_LJMP(lua_error(L));
6637
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006638 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6639 lua_pushinteger(L, ret);
6640 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006641}
6642
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006643/* Inserts a string to the HTTP message at a given offset. By default the string
6644 * is appended at the end of DATA blocks. It returns the amount of data written
6645 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6646 * this one can only be called inside a filter, from http_payload callback. So
6647 * it cannot yield. An exception is returned if it is called from another
6648 * callback.
6649 */
6650__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006651{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006652 struct http_msg *msg;
6653 struct filter *filter;
6654 const char *str;
6655 size_t input, output, sz;
6656 int offset;
6657 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006658
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006659 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6660 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6661 MAY_LJMP(check_args(L, 2, "insert"));
6662 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006663
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006664 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006665 WILL_LJMP(lua_error(L));
6666
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006667 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6668 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6669 if (!filter || !hlua_filter_from_payload(filter))
6670 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006671
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006672 offset = input + output;
6673 if (lua_gettop(L) > 2) {
6674 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6675 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006676 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006677 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006678 if (offset < output || offset > output + input) {
6679 lua_pushfstring(L, "offset out of range.");
6680 WILL_LJMP(lua_error(L));
6681 }
6682 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006683
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006684 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6685 lua_pushinteger(L, ret);
6686 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006687}
6688
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006689/* Removes a given amount of data from the HTTP message at a given offset. By
6690 * default all DATA blocks are removed. It returns the amount of data
6691 * removed. Unlike the channel function used to remove data, this one can only
6692 * be called inside a filter, from http_payload callback. So it cannot yield. An
6693 * exception is returned if it is called from another callback.
6694 */
6695__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006696{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006697 struct http_msg *msg;
6698 struct filter *filter;
6699 size_t input, output;
6700 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006701
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006702 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
Boyang Lie0c54352022-05-10 17:47:23 +00006703 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006704 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006705
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006706 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006707 WILL_LJMP(lua_error(L));
6708
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006709 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6710 if (!filter || !hlua_filter_from_payload(filter))
6711 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006712
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006713 offset = input + output;
Boyang Lie0c54352022-05-10 17:47:23 +00006714 if (lua_gettop(L) > 1) {
6715 offset = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006716 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006717 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006718 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006719 if (offset < output || offset > output + input) {
6720 lua_pushfstring(L, "offset out of range.");
6721 WILL_LJMP(lua_error(L));
6722 }
6723 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006724
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006725 len = output + input - offset;
Boyang Lie0c54352022-05-10 17:47:23 +00006726 if (lua_gettop(L) == 3) {
6727 len = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006728 if (!len)
6729 goto end;
6730 if (len == -1)
6731 len = output + input - offset;
6732 if (len < 0 || offset + len > output + input) {
6733 lua_pushfstring(L, "length out of range.");
6734 WILL_LJMP(lua_error(L));
6735 }
6736 }
6737
6738 _hlua_http_msg_delete(msg, filter, offset, len);
6739
6740 end:
6741 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006742 return 1;
6743}
6744
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006745/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 * all remaining data are removed, accordingly to the filter context. It returns
6747 * the amount of data written or -1 if nothing was copied. Unlike the channel
6748 * function used to replace data, this one can only be called inside a filter,
6749 * from http_payload callback. So it cannot yield. An exception is returned if
6750 * it is called from another callback.
6751 */
6752__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006753{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006754 struct http_msg *msg;
6755 struct filter *filter;
6756 struct htx *htx;
6757 const char *str;
6758 size_t input, output, sz;
6759 int offset, len;
6760 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006761
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006762 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6763 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6764 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6765
6766 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006767 WILL_LJMP(lua_error(L));
6768
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006769 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6770 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6771 if (!filter || !hlua_filter_from_payload(filter))
6772 WILL_LJMP(lua_error(L));
6773
6774 offset = output;
6775 if (lua_gettop(L) > 2) {
6776 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6777 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006778 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006779 offset += output;
6780 if (offset < output || offset > input + output) {
6781 lua_pushfstring(L, "offset out of range.");
6782 WILL_LJMP(lua_error(L));
6783 }
6784 }
6785
6786 len = output + input - offset;
6787 if (lua_gettop(L) == 4) {
6788 len = MAY_LJMP(luaL_checkinteger(L, 4));
6789 if (!len)
6790 goto set;
6791 if (len == -1)
6792 len = output + input - offset;
6793 if (len < 0 || offset + len > output + input) {
6794 lua_pushfstring(L, "length out of range.");
6795 WILL_LJMP(lua_error(L));
6796 }
6797 }
6798
6799 set:
6800 /* Be sure we can copied the string once input data will be removed. */
6801 htx = htx_from_buf(&msg->chn->buf);
6802 if (sz > htx_free_data_space(htx) + len)
6803 lua_pushinteger(L, -1);
6804 else {
6805 _hlua_http_msg_delete(msg, filter, offset, len);
6806 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6807 lua_pushinteger(L, ret);
6808 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006809 return 1;
6810}
6811
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006812/* Prepends data into an HTTP message and forward it, from the filter point of
6813 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6814 * the channel function used to send data, this one can only be called inside a
6815 * filter, from http_payload callback. So it cannot yield. An exception is
6816 * returned if it is called from another callback.
6817 */
6818__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006819{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006820 struct http_msg *msg;
6821 struct filter *filter;
6822 struct htx *htx;
6823 const char *str;
6824 size_t offset, len, sz;
6825 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006826
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006827 MAY_LJMP(check_args(L, 2, "send"));
6828 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6829
6830 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006831 WILL_LJMP(lua_error(L));
6832
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006833 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6834 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6835 if (!filter || !hlua_filter_from_payload(filter))
6836 WILL_LJMP(lua_error(L));
6837
6838 /* Return an error if the channel's output is closed */
6839 if (unlikely(channel_output_closed(msg->chn))) {
6840 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006841 return 1;
6842 }
6843
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006844 htx = htx_from_buf(&msg->chn->buf);
6845 if (sz > htx_free_data_space(htx)) {
6846 lua_pushinteger(L, -1);
6847 return 1;
6848 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006849
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006850 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6851 if (ret > 0) {
6852 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6853
6854 FLT_OFF(filter, msg->chn) += ret;
6855 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6856 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6857 }
6858
6859 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006860 return 1;
6861}
6862
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006863/* Forwards a given amount of bytes. It return -1 if the channel's output is
6864 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6865 * channel function used to forward data, this one can only be called inside a
6866 * filter, from http_payload callback. So it cannot yield. An exception is
6867 * returned if it is called from another callback. All other functions deal with
6868 * DATA block, this one not.
6869*/
6870__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006871{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006872 struct http_msg *msg;
6873 struct filter *filter;
6874 size_t offset, len;
6875 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006876
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006877 MAY_LJMP(check_args(L, 2, "forward"));
6878 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6879
6880 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006881 WILL_LJMP(lua_error(L));
6882
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006883 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6884 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6885 if (!filter || !hlua_filter_from_payload(filter))
6886 WILL_LJMP(lua_error(L));
6887
6888 /* Nothing to do, just return */
6889 if (!fwd)
6890 goto end;
6891
6892 /* Return an error if the channel's output is closed */
6893 if (unlikely(channel_output_closed(msg->chn))) {
6894 ret = -1;
6895 goto end;
6896 }
6897
6898 ret = fwd;
6899 if (ret > len)
6900 ret = len;
6901
6902 if (ret) {
6903 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6904
6905 FLT_OFF(filter, msg->chn) += ret;
6906 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6907 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6908 }
6909
6910 end:
6911 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006912 return 1;
6913}
6914
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006915/* Set EOM flag on the HTX message.
6916 *
6917 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6918 * really know how to do without this feature.
6919 */
6920__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006921{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006922 struct http_msg *msg;
6923 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006924
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006925 MAY_LJMP(check_args(L, 1, "set_eom"));
6926 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6927 htx = htxbuf(&msg->chn->buf);
6928 htx->flags |= HTX_FL_EOM;
6929 return 0;
6930}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006931
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006932/* Unset EOM flag on the HTX message.
6933 *
6934 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6935 * really know how to do without this feature.
6936 */
6937__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6938{
6939 struct http_msg *msg;
6940 struct htx *htx;
6941
6942 MAY_LJMP(check_args(L, 1, "set_eom"));
6943 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6944 htx = htxbuf(&msg->chn->buf);
6945 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006946 return 0;
6947}
6948
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006949/*
6950 *
6951 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006952 * Class HTTPClient
6953 *
6954 *
6955 */
6956__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6957{
6958 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6959}
6960
William Lallemandf77f1de2021-09-28 19:10:38 +02006961
6962/* stops the httpclient and ask it to kill itself */
6963__LJMP static int hlua_httpclient_gc(lua_State *L)
6964{
6965 struct hlua_httpclient *hlua_hc;
6966
6967 MAY_LJMP(check_args(L, 1, "__gc"));
6968
6969 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6970
6971 httpclient_stop_and_destroy(hlua_hc->hc);
6972
6973 hlua_hc->hc = NULL;
6974
6975
6976 return 0;
6977}
6978
6979
William Lallemand3956c4e2021-09-21 16:25:15 +02006980__LJMP static int hlua_httpclient_new(lua_State *L)
6981{
6982 struct hlua_httpclient *hlua_hc;
6983 struct hlua *hlua;
6984
6985 /* Get hlua struct, or NULL if we execute from main lua state */
6986 hlua = hlua_gethlua(L);
6987 if (!hlua)
6988 return 0;
6989
6990 /* Check stack size. */
6991 if (!lua_checkstack(L, 3)) {
6992 hlua_pusherror(L, "httpclient: full stack");
6993 goto err;
6994 }
6995 /* Create the object: obj[0] = userdata. */
6996 lua_newtable(L);
6997 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6998 lua_rawseti(L, -2, 0);
6999 memset(hlua_hc, 0, sizeof(*hlua_hc));
7000
7001 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
7002 if (!hlua_hc->hc)
7003 goto err;
7004
7005 /* Pop a class stream metatable and affect it to the userdata. */
7006 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
7007 lua_setmetatable(L, -2);
7008
7009 return 1;
7010
7011 err:
7012 WILL_LJMP(lua_error(L));
7013 return 0;
7014}
7015
7016
7017/*
7018 * Callback of the httpclient, this callback wakes the lua task up, once the
7019 * httpclient receives some data
7020 *
7021 */
7022
William Lallemandbd5739e2021-10-28 15:41:38 +02007023static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007024{
7025 struct hlua *hlua = hc->caller;
7026
7027 if (!hlua || !hlua->task)
7028 return;
7029
7030 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7031}
7032
7033/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007034 * Fill the lua stack with headers from the httpclient response
7035 * This works the same way as the hlua_http_get_headers() function
7036 */
7037__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7038{
7039 struct http_hdr *hdr;
7040
7041 lua_newtable(L);
7042
William Lallemandef574b22021-10-05 16:19:31 +02007043 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007044 struct ist n, v;
7045 int len;
7046
7047 n = hdr->n;
7048 v = hdr->v;
7049
7050 /* Check for existing entry:
7051 * assume that the table is on the top of the stack, and
7052 * push the key in the stack, the function lua_gettable()
7053 * perform the lookup.
7054 */
7055
7056 lua_pushlstring(L, n.ptr, n.len);
7057 lua_gettable(L, -2);
7058
7059 switch (lua_type(L, -1)) {
7060 case LUA_TNIL:
7061 /* Table not found, create it. */
7062 lua_pop(L, 1); /* remove the nil value. */
7063 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7064 lua_newtable(L); /* create and push empty table. */
7065 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7066 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7067 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7068 break;
7069
7070 case LUA_TTABLE:
7071 /* Entry found: push the value in the table. */
7072 len = lua_rawlen(L, -1);
7073 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7074 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7075 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7076 break;
7077
7078 default:
7079 /* Other cases are errors. */
7080 hlua_pusherror(L, "internal error during the parsing of headers.");
7081 WILL_LJMP(lua_error(L));
7082 }
7083 }
7084 return 1;
7085}
7086
7087/*
William Lallemand746e6f32021-10-06 10:57:44 +02007088 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7089 *
7090 * Caller must free the result
7091 */
7092struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7093{
7094 struct http_hdr hdrs[global.tune.max_http_hdr];
7095 struct http_hdr *result = NULL;
7096 uint32_t hdr_num = 0;
7097
7098 lua_pushnil(L);
7099 while (lua_next(L, -2) != 0) {
7100 struct ist name, value;
7101 const char *n, *v;
7102 size_t nlen, vlen;
7103
7104 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7105 /* Skip element if the key is not a string or if the value is not a table */
7106 goto next_hdr;
7107 }
7108
7109 n = lua_tolstring(L, -2, &nlen);
7110 name = ist2(n, nlen);
7111
7112 /* Loop on header's values */
7113 lua_pushnil(L);
7114 while (lua_next(L, -2)) {
7115 if (!lua_isstring(L, -1)) {
7116 /* Skip the value if it is not a string */
7117 goto next_value;
7118 }
7119
7120 v = lua_tolstring(L, -1, &vlen);
7121 value = ist2(v, vlen);
7122 name = ist2(n, nlen);
7123
7124 hdrs[hdr_num].n = istdup(name);
7125 hdrs[hdr_num].v = istdup(value);
7126
7127 hdr_num++;
7128
7129 next_value:
7130 lua_pop(L, 1);
7131 }
7132
7133 next_hdr:
7134 lua_pop(L, 1);
7135
7136 }
7137
7138 if (hdr_num) {
7139 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007140 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007141 if (!result)
7142 goto skip_headers;
7143 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7144
7145 result[hdr_num].n = IST_NULL;
7146 result[hdr_num].v = IST_NULL;
7147 }
7148
7149skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007150
7151 return result;
7152}
7153
7154
William Lallemandbd5739e2021-10-28 15:41:38 +02007155/*
7156 * For each yield, checks if there is some data in the httpclient and push them
7157 * in the lua buffer, once the httpclient finished its job, push the result on
7158 * the stack
7159 */
7160__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7161{
7162 struct buffer *tr;
7163 int res;
7164 struct hlua *hlua = hlua_gethlua(L);
7165 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7166
7167
7168 tr = get_trash_chunk();
7169
7170 res = httpclient_res_xfer(hlua_hc->hc, tr);
7171 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7172
7173 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7174
7175 luaL_pushresult(&hlua_hc->b);
7176 lua_settable(L, -3);
7177
7178 lua_pushstring(L, "status");
7179 lua_pushinteger(L, hlua_hc->hc->res.status);
7180 lua_settable(L, -3);
7181
7182
7183 lua_pushstring(L, "reason");
7184 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7185 lua_settable(L, -3);
7186
7187 lua_pushstring(L, "headers");
7188 hlua_httpclient_get_headers(L, hlua_hc);
7189 lua_settable(L, -3);
7190
7191 return 1;
7192 }
7193
7194 if (httpclient_data(hlua_hc->hc))
7195 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7196
7197 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7198
7199 return 0;
7200}
7201
7202/*
7203 * Call this when trying to stream a body during a request
7204 */
7205__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7206{
7207 struct hlua *hlua;
7208 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7209 const char *body_str = NULL;
7210 int ret;
7211 int end = 0;
7212 size_t buf_len;
7213 size_t to_send = 0;
7214
7215 hlua = hlua_gethlua(L);
7216
7217 if (!hlua || !hlua->task)
7218 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7219 "'frontend', 'backend' or 'task'"));
7220
7221 ret = lua_getfield(L, -1, "body");
7222 if (ret != LUA_TSTRING)
7223 goto rcv;
7224
7225 body_str = lua_tolstring(L, -1, &buf_len);
7226 lua_pop(L, 1);
7227
Christopher Fauletfc591292022-01-12 14:46:03 +01007228 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007229
7230 if ((hlua_hc->sent + to_send) >= buf_len)
7231 end = 1;
7232
7233 /* the end flag is always set since we are using the whole remaining size */
7234 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7235
7236 if (buf_len > hlua_hc->sent) {
7237 /* still need to process the buffer */
7238 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7239 } else {
7240 goto rcv;
7241 /* we sent the whole request buffer we can recv */
7242 }
7243 return 0;
7244
7245rcv:
7246
7247 /* we return a "res" object */
7248 lua_newtable(L);
7249
William Lallemandbd5739e2021-10-28 15:41:38 +02007250 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007251 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007252
William Lallemand933fe392021-11-04 09:45:58 +01007253 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007254 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7255
7256 return 1;
7257}
William Lallemand746e6f32021-10-06 10:57:44 +02007258
William Lallemand3956c4e2021-09-21 16:25:15 +02007259/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007260 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007261 */
7262
William Lallemanddc2cc902021-10-26 11:43:26 +02007263__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007264{
7265 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007266 struct http_hdr *hdrs = NULL;
7267 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007268 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007269 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007270 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007271 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007272 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007273
7274 hlua = hlua_gethlua(L);
7275
7276 if (!hlua || !hlua->task)
7277 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7278 "'frontend', 'backend' or 'task'"));
7279
William Lallemand746e6f32021-10-06 10:57:44 +02007280 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7281 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7282
William Lallemand4f4f2b72022-02-17 20:00:23 +01007283 hlua_hc = hlua_checkhttpclient(L, 1);
7284
William Lallemand7177a952022-03-03 15:33:12 +01007285 lua_pushnil(L); /* first key */
7286 while (lua_next(L, 2)) {
7287 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7288 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7289 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007290
William Lallemand7177a952022-03-03 15:33:12 +01007291 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7292 if (lua_type(L, -1) != LUA_TSTRING)
7293 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7294 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007295
William Lallemand7177a952022-03-03 15:33:12 +01007296 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7297 if (lua_type(L, -1) != LUA_TNUMBER)
7298 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7299 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007300
William Lallemand7177a952022-03-03 15:33:12 +01007301 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7302 if (lua_type(L, -1) != LUA_TTABLE)
7303 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7304 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007305
William Lallemand7177a952022-03-03 15:33:12 +01007306 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7307 if (lua_type(L, -1) != LUA_TSTRING)
7308 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7309 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007310
William Lallemand7177a952022-03-03 15:33:12 +01007311 } else {
7312 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7313 }
7314 /* removes 'value'; keeps 'key' for next iteration */
7315 lua_pop(L, 1);
7316 }
William Lallemanddec25c32021-10-25 19:48:37 +02007317
William Lallemand746e6f32021-10-06 10:57:44 +02007318 if (!url_str) {
7319 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7320 return 0;
7321 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007322
William Lallemand10a37362022-03-02 16:18:26 +01007323 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007324
7325 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007326 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007327
7328 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007329 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7330 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7331 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007332 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007333
William Lallemandbd5739e2021-10-28 15:41:38 +02007334 /* a body is available, it will use the request callback */
7335 if (body_str) {
7336 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7337 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007338
William Lallemandbd5739e2021-10-28 15:41:38 +02007339 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007340
William Lallemand746e6f32021-10-06 10:57:44 +02007341 /* free the temporary headers array */
7342 hdrs_i = hdrs;
7343 while (hdrs_i && isttest(hdrs_i->n)) {
7344 istfree(&hdrs_i->n);
7345 istfree(&hdrs_i->v);
7346 hdrs_i++;
7347 }
7348 ha_free(&hdrs);
7349
7350
William Lallemand6137a9e2021-10-26 15:01:53 +02007351 if (ret != ERR_NONE) {
7352 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7353 return 0;
7354 }
7355
William Lallemandc2d3db42022-04-26 11:46:13 +02007356 if (!httpclient_start(hlua_hc->hc))
7357 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007358
William Lallemandbd5739e2021-10-28 15:41:38 +02007359 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007360
William Lallemand3956c4e2021-09-21 16:25:15 +02007361 return 0;
7362}
7363
7364/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007365 * Sends an HTTP HEAD request and wait for a response
7366 *
7367 * httpclient:head(url, headers, payload)
7368 */
7369__LJMP static int hlua_httpclient_head(lua_State *L)
7370{
7371 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7372}
7373
7374/*
7375 * Send an HTTP GET request and wait for a response
7376 *
7377 * httpclient:get(url, headers, payload)
7378 */
7379__LJMP static int hlua_httpclient_get(lua_State *L)
7380{
7381 return hlua_httpclient_send(L, HTTP_METH_GET);
7382
7383}
7384
7385/*
7386 * Sends an HTTP PUT request and wait for a response
7387 *
7388 * httpclient:put(url, headers, payload)
7389 */
7390__LJMP static int hlua_httpclient_put(lua_State *L)
7391{
7392 return hlua_httpclient_send(L, HTTP_METH_PUT);
7393}
7394
7395/*
7396 * Send an HTTP POST request and wait for a response
7397 *
7398 * httpclient:post(url, headers, payload)
7399 */
7400__LJMP static int hlua_httpclient_post(lua_State *L)
7401{
7402 return hlua_httpclient_send(L, HTTP_METH_POST);
7403}
7404
7405
7406/*
7407 * Sends an HTTP DELETE request and wait for a response
7408 *
7409 * httpclient:delete(url, headers, payload)
7410 */
7411__LJMP static int hlua_httpclient_delete(lua_State *L)
7412{
7413 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7414}
7415
7416/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007417 *
7418 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007419 * Class TXN
7420 *
7421 *
7422 */
7423
7424/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007425 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007426 */
7427__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7428{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007429 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007430}
7431
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007432__LJMP static int hlua_set_var(lua_State *L)
7433{
7434 struct hlua_txn *htxn;
7435 const char *name;
7436 size_t len;
7437 struct sample smp;
7438
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007439 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7440 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007441
7442 /* It is useles to retrieve the stream, but this function
7443 * runs only in a stream context.
7444 */
7445 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7446 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7447
7448 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007449 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007450 hlua_lua2smp(L, 3, &smp);
7451
7452 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007453 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007454
7455 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7456 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7457 else
7458 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7459
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007460 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007461}
7462
Christopher Faulet85d79c92016-11-09 16:54:56 +01007463__LJMP static int hlua_unset_var(lua_State *L)
7464{
7465 struct hlua_txn *htxn;
7466 const char *name;
7467 size_t len;
7468 struct sample smp;
7469
7470 MAY_LJMP(check_args(L, 2, "unset_var"));
7471
7472 /* It is useles to retrieve the stream, but this function
7473 * runs only in a stream context.
7474 */
7475 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7476 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7477
7478 /* Unset the variable. */
7479 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007480 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7481 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007482}
7483
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007484__LJMP static int hlua_get_var(lua_State *L)
7485{
7486 struct hlua_txn *htxn;
7487 const char *name;
7488 size_t len;
7489 struct sample smp;
7490
7491 MAY_LJMP(check_args(L, 2, "get_var"));
7492
7493 /* It is useles to retrieve the stream, but this function
7494 * runs only in a stream context.
7495 */
7496 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7497 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7498
Willy Tarreau7560dd42016-03-10 16:28:58 +01007499 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007500 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007501 lua_pushnil(L);
7502 return 1;
7503 }
7504
7505 return hlua_smp2lua(L, &smp);
7506}
7507
Willy Tarreau59551662015-03-10 14:23:13 +01007508__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007509{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007510 struct hlua *hlua;
7511
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007512 MAY_LJMP(check_args(L, 2, "set_priv"));
7513
Willy Tarreau87b09662015-04-03 00:22:06 +02007514 /* It is useles to retrieve the stream, but this function
7515 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007516 */
7517 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007518
7519 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007520 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007521 if (!hlua)
7522 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007523
7524 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007525 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007526
7527 /* Get and store new value. */
7528 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7529 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7530
7531 return 0;
7532}
7533
Willy Tarreau59551662015-03-10 14:23:13 +01007534__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007535{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007536 struct hlua *hlua;
7537
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007538 MAY_LJMP(check_args(L, 1, "get_priv"));
7539
Willy Tarreau87b09662015-04-03 00:22:06 +02007540 /* It is useles to retrieve the stream, but this function
7541 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007542 */
7543 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007544
7545 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007546 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007547 if (!hlua) {
7548 lua_pushnil(L);
7549 return 1;
7550 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007551
7552 /* Push configuration index in the stack. */
7553 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7554
7555 return 1;
7556}
7557
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007558/* Create stack entry containing a class TXN. This function
7559 * return 0 if the stack does not contains free slots,
7560 * otherwise it returns 1.
7561 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007562static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007563{
Willy Tarreaude491382015-04-06 11:04:28 +02007564 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007565
7566 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007567 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007568 return 0;
7569
7570 /* NOTE: The allocation never fails. The failure
7571 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007572 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007573 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007574 /* Create the object: obj[0] = userdata. */
7575 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007576 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007577 lua_rawseti(L, -2, 0);
7578
Willy Tarreaude491382015-04-06 11:04:28 +02007579 htxn->s = s;
7580 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007581 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007582 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007583
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007584 /* Create the "f" field that contains a list of fetches. */
7585 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007586 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007587 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007588 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007589
7590 /* Create the "sf" field that contains a list of stringsafe fetches. */
7591 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007592 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007593 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007594 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007595
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007596 /* Create the "c" field that contains a list of converters. */
7597 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007598 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007599 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007600 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007601
7602 /* Create the "sc" field that contains a list of stringsafe converters. */
7603 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007604 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007605 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007606 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007607
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007608 /* Create the "req" field that contains the request channel object. */
7609 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007610 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007611 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007612 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007613
7614 /* Create the "res" field that contains the response channel object. */
7615 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007616 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007617 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007618 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007619
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007620 /* Creates the HTTP object is the current proxy allows http. */
7621 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007622 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007623 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007624 return 0;
7625 }
7626 else
7627 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007628 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007629
Christopher Faulet78c35472020-02-26 17:14:08 +01007630 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7631 /* HTTPMessage object are created when a lua TXN is created from
7632 * a filter context only
7633 */
7634
7635 /* Creates the HTTP-Request object is the current proxy allows http. */
7636 lua_pushstring(L, "http_req");
7637 if (p->mode == PR_MODE_HTTP) {
7638 if (!hlua_http_msg_new(L, &s->txn->req))
7639 return 0;
7640 }
7641 else
7642 lua_pushnil(L);
7643 lua_rawset(L, -3);
7644
7645 /* Creates the HTTP-Response object is the current proxy allows http. */
7646 lua_pushstring(L, "http_res");
7647 if (p->mode == PR_MODE_HTTP) {
7648 if (!hlua_http_msg_new(L, &s->txn->rsp))
7649 return 0;
7650 }
7651 else
7652 lua_pushnil(L);
7653 lua_rawset(L, -3);
7654 }
7655
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007656 /* Pop a class sesison metatable and affect it to the userdata. */
7657 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7658 lua_setmetatable(L, -2);
7659
7660 return 1;
7661}
7662
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007663__LJMP static int hlua_txn_deflog(lua_State *L)
7664{
7665 const char *msg;
7666 struct hlua_txn *htxn;
7667
7668 MAY_LJMP(check_args(L, 2, "deflog"));
7669 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7670 msg = MAY_LJMP(luaL_checkstring(L, 2));
7671
7672 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7673 return 0;
7674}
7675
7676__LJMP static int hlua_txn_log(lua_State *L)
7677{
7678 int level;
7679 const char *msg;
7680 struct hlua_txn *htxn;
7681
7682 MAY_LJMP(check_args(L, 3, "log"));
7683 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7684 level = MAY_LJMP(luaL_checkinteger(L, 2));
7685 msg = MAY_LJMP(luaL_checkstring(L, 3));
7686
7687 if (level < 0 || level >= NB_LOG_LEVELS)
7688 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7689
7690 hlua_sendlog(htxn->s->be, level, msg);
7691 return 0;
7692}
7693
7694__LJMP static int hlua_txn_log_debug(lua_State *L)
7695{
7696 const char *msg;
7697 struct hlua_txn *htxn;
7698
7699 MAY_LJMP(check_args(L, 2, "Debug"));
7700 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7701 msg = MAY_LJMP(luaL_checkstring(L, 2));
7702 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7703 return 0;
7704}
7705
7706__LJMP static int hlua_txn_log_info(lua_State *L)
7707{
7708 const char *msg;
7709 struct hlua_txn *htxn;
7710
7711 MAY_LJMP(check_args(L, 2, "Info"));
7712 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7713 msg = MAY_LJMP(luaL_checkstring(L, 2));
7714 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7715 return 0;
7716}
7717
7718__LJMP static int hlua_txn_log_warning(lua_State *L)
7719{
7720 const char *msg;
7721 struct hlua_txn *htxn;
7722
7723 MAY_LJMP(check_args(L, 2, "Warning"));
7724 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7725 msg = MAY_LJMP(luaL_checkstring(L, 2));
7726 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7727 return 0;
7728}
7729
7730__LJMP static int hlua_txn_log_alert(lua_State *L)
7731{
7732 const char *msg;
7733 struct hlua_txn *htxn;
7734
7735 MAY_LJMP(check_args(L, 2, "Alert"));
7736 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7737 msg = MAY_LJMP(luaL_checkstring(L, 2));
7738 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7739 return 0;
7740}
7741
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007742__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7743{
7744 struct hlua_txn *htxn;
7745 int ll;
7746
7747 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7748 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7749 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7750
7751 if (ll < 0 || ll > 7)
7752 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7753
7754 htxn->s->logs.level = ll;
7755 return 0;
7756}
7757
7758__LJMP static int hlua_txn_set_tos(lua_State *L)
7759{
7760 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007761 int tos;
7762
7763 MAY_LJMP(check_args(L, 2, "set_tos"));
7764 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7765 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7766
Willy Tarreau1a18b542018-12-11 16:37:42 +01007767 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007768 return 0;
7769}
7770
7771__LJMP static int hlua_txn_set_mark(lua_State *L)
7772{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007773 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007774 int mark;
7775
7776 MAY_LJMP(check_args(L, 2, "set_mark"));
7777 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7778 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7779
Lukas Tribus579e3e32019-08-11 18:03:45 +02007780 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007781 return 0;
7782}
7783
Patrick Hemmer268a7072018-05-11 12:52:31 -04007784__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7785{
7786 struct hlua_txn *htxn;
7787
7788 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7789 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7790 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7791 return 0;
7792}
7793
7794__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7795{
7796 struct hlua_txn *htxn;
7797
7798 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7799 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7800 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7801 return 0;
7802}
7803
Christopher Faulet700d9e82020-01-31 12:21:52 +01007804/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007805 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007806 * message and terminate the transaction. It returns 1 on success and 0 on
7807 * error. The Reply must be on top of the stack.
7808 */
7809__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7810{
7811 struct htx *htx;
7812 struct htx_sl *sl;
7813 struct h1m h1m;
7814 const char *status, *reason, *body;
7815 size_t status_len, reason_len, body_len;
7816 int ret, code, flags;
7817
7818 code = 200;
7819 status = "200";
7820 status_len = 3;
7821 ret = lua_getfield(L, -1, "status");
7822 if (ret == LUA_TNUMBER) {
7823 code = lua_tointeger(L, -1);
7824 status = lua_tolstring(L, -1, &status_len);
7825 }
7826 lua_pop(L, 1);
7827
7828 reason = http_get_reason(code);
7829 reason_len = strlen(reason);
7830 ret = lua_getfield(L, -1, "reason");
7831 if (ret == LUA_TSTRING)
7832 reason = lua_tolstring(L, -1, &reason_len);
7833 lua_pop(L, 1);
7834
7835 body = NULL;
7836 body_len = 0;
7837 ret = lua_getfield(L, -1, "body");
7838 if (ret == LUA_TSTRING)
7839 body = lua_tolstring(L, -1, &body_len);
7840 lua_pop(L, 1);
7841
7842 /* Prepare the response before inserting the headers */
7843 h1m_init_res(&h1m);
7844 htx = htx_from_buf(&s->res.buf);
7845 channel_htx_truncate(&s->res, htx);
7846 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7847 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7848 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7849 ist2(status, status_len), ist2(reason, reason_len));
7850 }
7851 else {
7852 flags = HTX_SL_F_IS_RESP;
7853 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7854 ist2(status, status_len), ist2(reason, reason_len));
7855 }
7856 if (!sl)
7857 goto fail;
7858 sl->info.res.status = code;
7859
7860 /* Push in the stack the "headers" entry. */
7861 ret = lua_getfield(L, -1, "headers");
7862 if (ret != LUA_TTABLE)
7863 goto skip_headers;
7864
7865 lua_pushnil(L);
7866 while (lua_next(L, -2) != 0) {
7867 struct ist name, value;
7868 const char *n, *v;
7869 size_t nlen, vlen;
7870
7871 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7872 /* Skip element if the key is not a string or if the value is not a table */
7873 goto next_hdr;
7874 }
7875
7876 n = lua_tolstring(L, -2, &nlen);
7877 name = ist2(n, nlen);
7878 if (isteqi(name, ist("content-length"))) {
7879 /* Always skip content-length header. It will be added
7880 * later with the correct len
7881 */
7882 goto next_hdr;
7883 }
7884
7885 /* Loop on header's values */
7886 lua_pushnil(L);
7887 while (lua_next(L, -2)) {
7888 if (!lua_isstring(L, -1)) {
7889 /* Skip the value if it is not a string */
7890 goto next_value;
7891 }
7892
7893 v = lua_tolstring(L, -1, &vlen);
7894 value = ist2(v, vlen);
7895
7896 if (isteqi(name, ist("transfer-encoding")))
7897 h1_parse_xfer_enc_header(&h1m, value);
7898 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7899 goto fail;
7900
7901 next_value:
7902 lua_pop(L, 1);
7903 }
7904
7905 next_hdr:
7906 lua_pop(L, 1);
7907 }
7908 skip_headers:
7909 lua_pop(L, 1);
7910
7911 /* Update h1m flags: CLEN is set if CHNK is not present */
7912 if (!(h1m.flags & H1_MF_CHNK)) {
7913 const char *clen = ultoa(body_len);
7914
7915 h1m.flags |= H1_MF_CLEN;
7916 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7917 goto fail;
7918 }
7919 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7920 h1m.flags |= H1_MF_XFER_LEN;
7921
7922 /* Update HTX start-line flags */
7923 if (h1m.flags & H1_MF_XFER_ENC)
7924 flags |= HTX_SL_F_XFER_ENC;
7925 if (h1m.flags & H1_MF_XFER_LEN) {
7926 flags |= HTX_SL_F_XFER_LEN;
7927 if (h1m.flags & H1_MF_CHNK)
7928 flags |= HTX_SL_F_CHNK;
7929 else if (h1m.flags & H1_MF_CLEN)
7930 flags |= HTX_SL_F_CLEN;
7931 if (h1m.body_len == 0)
7932 flags |= HTX_SL_F_BODYLESS;
7933 }
7934 sl->flags |= flags;
7935
7936
7937 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007938 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007939 goto fail;
7940
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007941 htx->flags |= HTX_FL_EOM;
7942
Christopher Faulet700d9e82020-01-31 12:21:52 +01007943 /* Now, forward the response and terminate the transaction */
7944 s->txn->status = code;
7945 htx_to_buf(htx, &s->res.buf);
7946 if (!http_forward_proxy_resp(s, 1))
7947 goto fail;
7948
7949 return 1;
7950
7951 fail:
7952 channel_htx_truncate(&s->res, htx);
7953 return 0;
7954}
7955
7956/* Terminate a transaction if called from a lua action. For TCP streams,
7957 * processing is just aborted. Nothing is returned to the client and all
7958 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7959 * is forwarded to the client before terminating the transaction. On success,
7960 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7961 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7962 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007963 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007964__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007965{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007966 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007967 struct stream *s;
7968 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007969
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007970 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007971
Christopher Faulet700d9e82020-01-31 12:21:52 +01007972 /* If the flags NOTERM is set, we cannot terminate the session, so we
7973 * just end the execution of the current lua code. */
7974 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007975 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007976
Christopher Faulet700d9e82020-01-31 12:21:52 +01007977 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007978 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007979 struct channel *req = &s->req;
7980 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007981
Christopher Faulet700d9e82020-01-31 12:21:52 +01007982 channel_auto_read(req);
7983 channel_abort(req);
7984 channel_auto_close(req);
7985 channel_erase(req);
7986
7987 res->wex = tick_add_ifset(now_ms, res->wto);
7988 channel_auto_read(res);
7989 channel_auto_close(res);
7990 channel_shutr_now(res);
7991
7992 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7993 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007994 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007995
Christopher Faulet700d9e82020-01-31 12:21:52 +01007996 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7997 /* No reply or invalid reply */
7998 s->txn->status = 0;
7999 http_reply_and_close(s, 0, NULL);
8000 }
8001 else {
8002 /* Remove extra args to have the reply on top of the stack */
8003 if (lua_gettop(L) > 2)
8004 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008005
Christopher Faulet700d9e82020-01-31 12:21:52 +01008006 if (!hlua_txn_forward_reply(L, s)) {
8007 if (!(s->flags & SF_ERR_MASK))
8008 s->flags |= SF_ERR_PRXCOND;
8009 lua_pushinteger(L, ACT_RET_ERR);
8010 WILL_LJMP(hlua_done(L));
8011 return 0; /* Never reached */
8012 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02008013 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008014
Christopher Faulet700d9e82020-01-31 12:21:52 +01008015 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8016 if (htxn->dir == SMP_OPT_DIR_REQ) {
8017 /* let's log the request time */
8018 s->logs.tv_request = now;
8019 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008020 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008021 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008022
Christopher Faulet700d9e82020-01-31 12:21:52 +01008023 done:
8024 if (!(s->flags & SF_ERR_MASK))
8025 s->flags |= SF_ERR_LOCAL;
8026 if (!(s->flags & SF_FINST_MASK))
8027 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008028
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008029 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8030 lua_pushinteger(L, -1);
8031 else
8032 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008033 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008034 return 0;
8035}
8036
Christopher Faulet700d9e82020-01-31 12:21:52 +01008037/*
8038 *
8039 *
8040 * Class REPLY
8041 *
8042 *
8043 */
8044
8045/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8046 * free slots, the function fails and returns 0;
8047 */
8048static int hlua_txn_reply_new(lua_State *L)
8049{
8050 struct hlua_txn *htxn;
8051 const char *reason, *body = NULL;
8052 int ret, status;
8053
8054 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008055 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008056 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8057 WILL_LJMP(lua_error(L));
8058 }
8059
8060 /* Default value */
8061 status = 200;
8062 reason = http_get_reason(status);
8063
8064 if (lua_istable(L, 2)) {
8065 /* load status and reason from the table argument at index 2 */
8066 ret = lua_getfield(L, 2, "status");
8067 if (ret == LUA_TNIL)
8068 goto reason;
8069 else if (ret != LUA_TNUMBER) {
8070 /* invalid status: ignore the reason */
8071 goto body;
8072 }
8073 status = lua_tointeger(L, -1);
8074
8075 reason:
8076 lua_pop(L, 1); /* restore the stack: remove status */
8077 ret = lua_getfield(L, 2, "reason");
8078 if (ret == LUA_TSTRING)
8079 reason = lua_tostring(L, -1);
8080
8081 body:
8082 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8083 ret = lua_getfield(L, 2, "body");
8084 if (ret == LUA_TSTRING)
8085 body = lua_tostring(L, -1);
8086 lua_pop(L, 1); /* restore the stack: remove body */
8087 }
8088
8089 /* Create the Reply table */
8090 lua_newtable(L);
8091
8092 /* Add status element */
8093 lua_pushstring(L, "status");
8094 lua_pushinteger(L, status);
8095 lua_settable(L, -3);
8096
8097 /* Add reason element */
8098 reason = http_get_reason(status);
8099 lua_pushstring(L, "reason");
8100 lua_pushstring(L, reason);
8101 lua_settable(L, -3);
8102
8103 /* Add body element, nil if undefined */
8104 lua_pushstring(L, "body");
8105 if (body)
8106 lua_pushstring(L, body);
8107 else
8108 lua_pushnil(L);
8109 lua_settable(L, -3);
8110
8111 /* Add headers element */
8112 lua_pushstring(L, "headers");
8113 lua_newtable(L);
8114
8115 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8116 if (lua_istable(L, 2)) {
8117 /* load headers from the table argument at index 2. If it is a table, copy it. */
8118 ret = lua_getfield(L, 2, "headers");
8119 if (ret == LUA_TTABLE) {
8120 /* stack: [ ... <headers:table>, <table> ] */
8121 lua_pushnil(L);
8122 while (lua_next(L, -2) != 0) {
8123 /* stack: [ ... <headers:table>, <table>, k, v] */
8124 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8125 /* invalid value type, skip it */
8126 lua_pop(L, 1);
8127 continue;
8128 }
8129
8130
8131 /* Duplicate the key and swap it with the value. */
8132 lua_pushvalue(L, -2);
8133 lua_insert(L, -2);
8134 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8135
8136 lua_newtable(L);
8137 lua_insert(L, -2);
8138 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8139
8140 if (lua_isstring(L, -1)) {
8141 /* push the value in the inner table */
8142 lua_rawseti(L, -2, 1);
8143 }
8144 else { /* table */
8145 lua_pushnil(L);
8146 while (lua_next(L, -2) != 0) {
8147 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8148 if (!lua_isstring(L, -1)) {
8149 /* invalid value type, skip it*/
8150 lua_pop(L, 1);
8151 continue;
8152 }
8153 /* push the value in the inner table */
8154 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8155 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8156 }
8157 lua_pop(L, 1);
8158 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8159 }
8160
8161 /* push (k,v) on the stack in the headers table:
8162 * stack: [ ... <headers:table>, <table>, k, k, v ]
8163 */
8164 lua_settable(L, -5);
8165 /* stack: [ ... <headers:table>, <table>, k ] */
8166 }
8167 }
8168 lua_pop(L, 1);
8169 }
8170 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8171 lua_settable(L, -3);
8172 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8173
8174 /* Pop a class sesison metatable and affect it to the userdata. */
8175 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8176 lua_setmetatable(L, -2);
8177 return 1;
8178}
8179
8180/* Set the reply status code, and optionally the reason. If no reason is
8181 * provided, the default one corresponding to the status code is used.
8182 */
8183__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8184{
8185 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8186 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8187
8188 /* First argument (self) must be a table */
8189 luaL_checktype(L, 1, LUA_TTABLE);
8190
8191 if (status < 100 || status > 599) {
8192 lua_pushboolean(L, 0);
8193 return 1;
8194 }
8195 if (!reason)
8196 reason = http_get_reason(status);
8197
8198 lua_pushinteger(L, status);
8199 lua_setfield(L, 1, "status");
8200
8201 lua_pushstring(L, reason);
8202 lua_setfield(L, 1, "reason");
8203
8204 lua_pushboolean(L, 1);
8205 return 1;
8206}
8207
8208/* Add a header into the reply object. Each header name is associated to an
8209 * array of values in the "headers" table. If the header name is not found, a
8210 * new entry is created.
8211 */
8212__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8213{
8214 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8215 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8216 int ret;
8217
8218 /* First argument (self) must be a table */
8219 luaL_checktype(L, 1, LUA_TTABLE);
8220
8221 /* Push in the stack the "headers" entry. */
8222 ret = lua_getfield(L, 1, "headers");
8223 if (ret != LUA_TTABLE) {
8224 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8225 WILL_LJMP(lua_error(L));
8226 }
8227
8228 /* check if the header is already registered. If not, register it. */
8229 ret = lua_getfield(L, -1, name);
8230 if (ret == LUA_TNIL) {
8231 /* Entry not found. */
8232 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8233
8234 /* Insert the new header name in the array in the top of the stack.
8235 * It left the new array in the top of the stack.
8236 */
8237 lua_newtable(L);
8238 lua_pushstring(L, name);
8239 lua_pushvalue(L, -2);
8240 lua_settable(L, -4);
8241 }
8242 else if (ret != LUA_TTABLE) {
8243 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8244 WILL_LJMP(lua_error(L));
8245 }
8246
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008247 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008248 * the header value as new entry.
8249 */
8250 lua_pushstring(L, value);
8251 ret = lua_rawlen(L, -2);
8252 lua_rawseti(L, -2, ret + 1);
8253
8254 lua_pushboolean(L, 1);
8255 return 1;
8256}
8257
8258/* Remove all occurrences of a given header name. */
8259__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8260{
8261 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8262 int ret;
8263
8264 /* First argument (self) must be a table */
8265 luaL_checktype(L, 1, LUA_TTABLE);
8266
8267 /* Push in the stack the "headers" entry. */
8268 ret = lua_getfield(L, 1, "headers");
8269 if (ret != LUA_TTABLE) {
8270 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8271 WILL_LJMP(lua_error(L));
8272 }
8273
8274 lua_pushstring(L, name);
8275 lua_pushnil(L);
8276 lua_settable(L, -3);
8277
8278 lua_pushboolean(L, 1);
8279 return 1;
8280}
8281
8282/* Set the reply's body. Overwrite any existing entry. */
8283__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8284{
8285 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8286
8287 /* First argument (self) must be a table */
8288 luaL_checktype(L, 1, LUA_TTABLE);
8289
8290 lua_pushstring(L, payload);
8291 lua_setfield(L, 1, "body");
8292
8293 lua_pushboolean(L, 1);
8294 return 1;
8295}
8296
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008297__LJMP static int hlua_log(lua_State *L)
8298{
8299 int level;
8300 const char *msg;
8301
8302 MAY_LJMP(check_args(L, 2, "log"));
8303 level = MAY_LJMP(luaL_checkinteger(L, 1));
8304 msg = MAY_LJMP(luaL_checkstring(L, 2));
8305
8306 if (level < 0 || level >= NB_LOG_LEVELS)
8307 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8308
8309 hlua_sendlog(NULL, level, msg);
8310 return 0;
8311}
8312
8313__LJMP static int hlua_log_debug(lua_State *L)
8314{
8315 const char *msg;
8316
8317 MAY_LJMP(check_args(L, 1, "debug"));
8318 msg = MAY_LJMP(luaL_checkstring(L, 1));
8319 hlua_sendlog(NULL, LOG_DEBUG, msg);
8320 return 0;
8321}
8322
8323__LJMP static int hlua_log_info(lua_State *L)
8324{
8325 const char *msg;
8326
8327 MAY_LJMP(check_args(L, 1, "info"));
8328 msg = MAY_LJMP(luaL_checkstring(L, 1));
8329 hlua_sendlog(NULL, LOG_INFO, msg);
8330 return 0;
8331}
8332
8333__LJMP static int hlua_log_warning(lua_State *L)
8334{
8335 const char *msg;
8336
8337 MAY_LJMP(check_args(L, 1, "warning"));
8338 msg = MAY_LJMP(luaL_checkstring(L, 1));
8339 hlua_sendlog(NULL, LOG_WARNING, msg);
8340 return 0;
8341}
8342
8343__LJMP static int hlua_log_alert(lua_State *L)
8344{
8345 const char *msg;
8346
8347 MAY_LJMP(check_args(L, 1, "alert"));
8348 msg = MAY_LJMP(luaL_checkstring(L, 1));
8349 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008350 return 0;
8351}
8352
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008353__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008354{
8355 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008356 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008357 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008358 return 0;
8359}
8360
8361__LJMP static int hlua_sleep(lua_State *L)
8362{
8363 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008364 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008365
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008366 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008367
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008368 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008369 wakeup_ms = tick_add(now_ms, delay);
8370 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008371
Willy Tarreau9635e032018-10-16 17:52:55 +02008372 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008373 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008374}
8375
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008376__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008377{
8378 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008379 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008380
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008381 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008382
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008383 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008384 wakeup_ms = tick_add(now_ms, delay);
8385 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008386
Willy Tarreau9635e032018-10-16 17:52:55 +02008387 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008388 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008389}
8390
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008391/* This functionis an LUA binding. it permits to give back
8392 * the hand at the HAProxy scheduler. It is used when the
8393 * LUA processing consumes a lot of time.
8394 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008395__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008396{
8397 return 0;
8398}
8399
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008400__LJMP static int hlua_yield(lua_State *L)
8401{
Willy Tarreau9635e032018-10-16 17:52:55 +02008402 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008403 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008404}
8405
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008406/* This function change the nice of the currently executed
8407 * task. It is used set low or high priority at the current
8408 * task.
8409 */
Willy Tarreau59551662015-03-10 14:23:13 +01008410__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008411{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008412 struct hlua *hlua;
8413 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008414
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008415 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008416 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008417
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008418 /* Get hlua struct, or NULL if we execute from main lua state */
8419 hlua = hlua_gethlua(L);
8420
8421 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008422 if (!hlua || !hlua->task)
8423 return 0;
8424
8425 if (nice < -1024)
8426 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008427 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008428 nice = 1024;
8429
8430 hlua->task->nice = nice;
8431 return 0;
8432}
8433
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008434/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008435 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8436 * return an E_AGAIN signal, the emmiter of this signal must set a
8437 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008438 *
8439 * Task wrapper are longjmp safe because the only one Lua code
8440 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008441 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008442struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008443{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008444 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008445 enum hlua_exec status;
8446
Christopher Faulet5bc99722018-04-25 10:34:45 +02008447 if (task->thread_mask == MAX_THREADS_MASK)
8448 task_set_affinity(task, tid_bit);
8449
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008450 /* If it is the first call to the task, we must initialize the
8451 * execution timeouts.
8452 */
8453 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008454 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008455
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008456 /* Execute the Lua code. */
8457 status = hlua_ctx_resume(hlua, 1);
8458
8459 switch (status) {
8460 /* finished or yield */
8461 case HLUA_E_OK:
8462 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008463 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008464 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008465 break;
8466
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008467 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008468 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008469 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008470 break;
8471
8472 /* finished with error. */
8473 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008474 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008475 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008476 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008477 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008478 break;
8479
8480 case HLUA_E_ERR:
8481 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008482 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008483 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008484 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008485 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008486 break;
8487 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008488 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008489}
8490
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008491/* This function is an LUA binding that register LUA function to be
8492 * executed after the HAProxy configuration parsing and before the
8493 * HAProxy scheduler starts. This function expect only one LUA
8494 * argument that is a function. This function returns nothing, but
8495 * throws if an error is encountered.
8496 */
8497__LJMP static int hlua_register_init(lua_State *L)
8498{
8499 struct hlua_init_function *init;
8500 int ref;
8501
8502 MAY_LJMP(check_args(L, 1, "register_init"));
8503
8504 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8505
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008506 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008507 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008508 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008509
8510 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008511 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008512 return 0;
8513}
8514
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008515/* This functio is an LUA binding. It permits to register a task
8516 * executed in parallel of the main HAroxy activity. The task is
8517 * created and it is set in the HAProxy scheduler. It can be called
8518 * from the "init" section, "post init" or during the runtime.
8519 *
8520 * Lua prototype:
8521 *
8522 * <none> core.register_task(<function>)
8523 */
8524static int hlua_register_task(lua_State *L)
8525{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008526 struct hlua *hlua = NULL;
8527 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008528 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008529 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008530
8531 MAY_LJMP(check_args(L, 1, "register_task"));
8532
8533 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8534
Thierry Fournier75fc0292020-11-28 13:18:56 +01008535 /* Get the reference state. If the reference is NULL, L is the master
8536 * state, otherwise hlua->T is.
8537 */
8538 hlua = hlua_gethlua(L);
8539 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008540 /* we are in runtime processing */
8541 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008542 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008543 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008544 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008545
Willy Tarreaubafbe012017-11-24 17:34:44 +01008546 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008547 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008548 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008549 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008550
Thierry Fournier59f11be2020-11-29 00:37:41 +01008551 /* We are in the common lua state, execute the task anywhere,
8552 * otherwise, inherit the current thread identifier
8553 */
8554 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008555 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008556 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008557 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008558 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008559 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008560
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008561 task->context = hlua;
8562 task->process = hlua_process_task;
8563
Thierry Fournier021d9862020-11-28 23:42:03 +01008564 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008565 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008566
8567 /* Restore the function in the stack. */
8568 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8569 hlua->nargs = 0;
8570
8571 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008572 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008573
8574 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008575
8576 alloc_error:
8577 task_destroy(task);
8578 hlua_ctx_destroy(hlua);
8579 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8580 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008581}
8582
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008583/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8584 * doesn't allow "yield" functions because the HAProxy engine cannot
8585 * resume converters.
8586 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008587static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008588{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008589 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008590 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008591 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008592
Willy Tarreaube508f12016-03-10 11:47:01 +01008593 if (!stream)
8594 return 0;
8595
Willy Tarreau87b09662015-04-03 00:22:06 +02008596 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008597 * Lua context can be not initialized. This behavior
8598 * permits to save performances because a systematic
8599 * Lua initialization cause 5% performances loss.
8600 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008601 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008602 struct hlua *hlua;
8603
8604 hlua = pool_alloc(pool_head_hlua);
8605 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008606 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8607 return 0;
8608 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008609 HLUA_INIT(hlua);
8610 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008611 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008612 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8613 return 0;
8614 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008615 }
8616
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008617 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008618 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008619
8620 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008621 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008622 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8623 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008624 else
8625 error = "critical error";
8626 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008627 return 0;
8628 }
8629
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008630 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008631 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008632 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008633 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008634 return 0;
8635 }
8636
8637 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008638 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008639
8640 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008641 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008642 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008643 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008644 return 0;
8645 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008646 hlua_smp2lua(stream->hlua->T, smp);
8647 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008648
8649 /* push keywords in the stack. */
8650 if (arg_p) {
8651 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008652 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008653 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008654 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008655 return 0;
8656 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008657 hlua_arg2lua(stream->hlua->T, arg_p);
8658 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008659 }
8660 }
8661
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008662 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008663 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008664
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008665 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008666 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008667 }
8668
8669 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008670 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008671 /* finished. */
8672 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008673 /* If the stack is empty, the function fails. */
8674 if (lua_gettop(stream->hlua->T) <= 0)
8675 return 0;
8676
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008677 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008678 hlua_lua2smp(stream->hlua->T, -1, smp);
8679 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008680 return 1;
8681
8682 /* yield. */
8683 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008684 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008685 return 0;
8686
8687 /* finished with error. */
8688 case HLUA_E_ERRMSG:
8689 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008690 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008691 fcn->name, lua_tostring(stream->hlua->T, -1));
8692 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008693 return 0;
8694
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008695 case HLUA_E_ETMOUT:
8696 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8697 return 0;
8698
8699 case HLUA_E_NOMEM:
8700 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8701 return 0;
8702
8703 case HLUA_E_YIELD:
8704 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8705 return 0;
8706
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008707 case HLUA_E_ERR:
8708 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008709 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008710 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008711
8712 default:
8713 return 0;
8714 }
8715}
8716
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008717/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8718 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008719 * resume sample-fetches. This function will be called by the sample
8720 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008721 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008722static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8723 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008724{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008725 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008726 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008727 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008728 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008729
Willy Tarreaube508f12016-03-10 11:47:01 +01008730 if (!stream)
8731 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008732
Willy Tarreau87b09662015-04-03 00:22:06 +02008733 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008734 * Lua context can be not initialized. This behavior
8735 * permits to save performances because a systematic
8736 * Lua initialization cause 5% performances loss.
8737 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008738 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008739 struct hlua *hlua;
8740
8741 hlua = pool_alloc(pool_head_hlua);
8742 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008743 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8744 return 0;
8745 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008746 hlua->T = NULL;
8747 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008748 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008749 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8750 return 0;
8751 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008752 }
8753
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008754 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008755 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008756
8757 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008758 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008759 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8760 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008761 else
8762 error = "critical error";
8763 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008764 return 0;
8765 }
8766
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008767 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008768 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008769 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008770 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008771 return 0;
8772 }
8773
8774 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008775 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008776
8777 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008778 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008779 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008780 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008781 return 0;
8782 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008783 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008784
8785 /* push keywords in the stack. */
8786 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8787 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008788 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008789 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008790 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008791 return 0;
8792 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008793 hlua_arg2lua(stream->hlua->T, arg_p);
8794 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008795 }
8796
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008797 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008798 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008799
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008800 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008801 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008802 }
8803
8804 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008805 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008806 /* finished. */
8807 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008808 /* If the stack is empty, the function fails. */
8809 if (lua_gettop(stream->hlua->T) <= 0)
8810 return 0;
8811
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008812 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008813 hlua_lua2smp(stream->hlua->T, -1, smp);
8814 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008815
8816 /* Set the end of execution flag. */
8817 smp->flags &= ~SMP_F_MAY_CHANGE;
8818 return 1;
8819
8820 /* yield. */
8821 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008822 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008823 return 0;
8824
8825 /* finished with error. */
8826 case HLUA_E_ERRMSG:
8827 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008828 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008829 fcn->name, lua_tostring(stream->hlua->T, -1));
8830 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008831 return 0;
8832
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008833 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008834 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8835 return 0;
8836
8837 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008838 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8839 return 0;
8840
8841 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008842 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8843 return 0;
8844
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008845 case HLUA_E_ERR:
8846 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008847 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008848 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008849
8850 default:
8851 return 0;
8852 }
8853}
8854
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008855/* This function is an LUA binding used for registering
8856 * "sample-conv" functions. It expects a converter name used
8857 * in the haproxy configuration file, and an LUA function.
8858 */
8859__LJMP static int hlua_register_converters(lua_State *L)
8860{
8861 struct sample_conv_kw_list *sck;
8862 const char *name;
8863 int ref;
8864 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008865 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008866 struct sample_conv *sc;
8867 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008868
8869 MAY_LJMP(check_args(L, 2, "register_converters"));
8870
8871 /* First argument : converter name. */
8872 name = MAY_LJMP(luaL_checkstring(L, 1));
8873
8874 /* Second argument : lua function. */
8875 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8876
Thierry Fournierf67442e2020-11-28 20:41:07 +01008877 /* Check if the converter is already registered */
8878 trash = get_trash_chunk();
8879 chunk_printf(trash, "lua.%s", name);
8880 sc = find_sample_conv(trash->area, trash->data);
8881 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008882 fcn = sc->private;
8883 if (fcn->function_ref[hlua_state_id] != -1) {
8884 ha_warning("Trying to register converter 'lua.%s' more than once. "
8885 "This will become a hard error in version 2.5.\n", name);
8886 }
8887 fcn->function_ref[hlua_state_id] = ref;
8888 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008889 }
8890
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008891 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008892 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008893 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008894 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008895 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008896 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008897 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008898
8899 /* Fill fcn. */
8900 fcn->name = strdup(name);
8901 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008902 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008903 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008904
8905 /* List head */
8906 sck->list.n = sck->list.p = NULL;
8907
8908 /* converter keyword. */
8909 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008910 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008911 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008912 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008913
8914 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8915 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008916 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 +01008917 sck->kw[0].val_args = NULL;
8918 sck->kw[0].in_type = SMP_T_STR;
8919 sck->kw[0].out_type = SMP_T_STR;
8920 sck->kw[0].private = fcn;
8921
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008922 /* Register this new converter */
8923 sample_register_convs(sck);
8924
8925 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008926
8927 alloc_error:
8928 release_hlua_function(fcn);
8929 ha_free(&sck);
8930 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8931 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008932}
8933
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008934/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008935 * "sample-fetch" functions. It expects a converter name used
8936 * in the haproxy configuration file, and an LUA function.
8937 */
8938__LJMP static int hlua_register_fetches(lua_State *L)
8939{
8940 const char *name;
8941 int ref;
8942 int len;
8943 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008944 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008945 struct sample_fetch *sf;
8946 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008947
8948 MAY_LJMP(check_args(L, 2, "register_fetches"));
8949
8950 /* First argument : sample-fetch name. */
8951 name = MAY_LJMP(luaL_checkstring(L, 1));
8952
8953 /* Second argument : lua function. */
8954 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8955
Thierry Fournierf67442e2020-11-28 20:41:07 +01008956 /* Check if the sample-fetch is already registered */
8957 trash = get_trash_chunk();
8958 chunk_printf(trash, "lua.%s", name);
8959 sf = find_sample_fetch(trash->area, trash->data);
8960 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008961 fcn = sf->private;
8962 if (fcn->function_ref[hlua_state_id] != -1) {
8963 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8964 "This will become a hard error in version 2.5.\n", name);
8965 }
8966 fcn->function_ref[hlua_state_id] = ref;
8967 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008968 }
8969
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008970 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008971 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008972 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008973 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008974 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008975 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008976 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008977
8978 /* Fill fcn. */
8979 fcn->name = strdup(name);
8980 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008981 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008982 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008983
8984 /* List head */
8985 sfk->list.n = sfk->list.p = NULL;
8986
8987 /* sample-fetch keyword. */
8988 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008989 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008990 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008991 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008992
8993 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8994 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008995 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 +01008996 sfk->kw[0].val_args = NULL;
8997 sfk->kw[0].out_type = SMP_T_STR;
8998 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8999 sfk->kw[0].val = 0;
9000 sfk->kw[0].private = fcn;
9001
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009002 /* Register this new fetch. */
9003 sample_register_fetches(sfk);
9004
9005 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02009006
9007 alloc_error:
9008 release_hlua_function(fcn);
9009 ha_free(&sfk);
9010 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9011 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01009012}
9013
Christopher Faulet501465d2020-02-26 14:54:16 +01009014/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009015 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009016__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009017{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009018 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009019 unsigned int delay;
9020 unsigned int wakeup_ms;
9021
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009022 /* Get hlua struct, or NULL if we execute from main lua state */
9023 hlua = hlua_gethlua(L);
9024 if (!hlua) {
9025 return 0;
9026 }
9027
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009028 MAY_LJMP(check_args(L, 1, "wake_time"));
9029
9030 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9031 wakeup_ms = tick_add(now_ms, delay);
9032 hlua->wake_time = wakeup_ms;
9033 return 0;
9034}
9035
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009036/* This function is a wrapper to execute each LUA function declared as an action
9037 * wrapper during the initialisation period. This function may return any
9038 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9039 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9040 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009041 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009042static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009043 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009044{
9045 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009046 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009047 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009048 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009049
9050 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009051 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9052 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9053 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9054 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009055 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009056 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009057 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009058 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009059
Willy Tarreau87b09662015-04-03 00:22:06 +02009060 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009061 * Lua context can be not initialized. This behavior
9062 * permits to save performances because a systematic
9063 * Lua initialization cause 5% performances loss.
9064 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009065 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009066 struct hlua *hlua;
9067
9068 hlua = pool_alloc(pool_head_hlua);
9069 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009070 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009071 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009072 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009073 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009074 HLUA_INIT(hlua);
9075 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009076 if (!hlua_ctx_init(s->hlua, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn), s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009077 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009078 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009079 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009080 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009081 }
9082
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009083 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009084 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009085
9086 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009087 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009088 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9089 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009090 else
9091 error = "critical error";
9092 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009093 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009094 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009095 }
9096
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009097 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009098 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009099 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009100 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009101 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009102 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009103 }
9104
9105 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009106 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009107
Willy Tarreau87b09662015-04-03 00:22:06 +02009108 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009109 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009110 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009111 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009112 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009113 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009114 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009115 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009116
9117 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009118 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009119 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009120 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009121 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009122 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009123 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009124 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009125 lua_pushstring(s->hlua->T, *arg);
9126 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009127 }
9128
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009129 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009130 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009131
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009132 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009133 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009134 }
9135
9136 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009137 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009138 /* finished. */
9139 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009140 /* Catch the return value */
9141 if (lua_gettop(s->hlua->T) > 0)
9142 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009143
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009144 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009145 if (act_ret == ACT_RET_YIELD) {
9146 if (flags & ACT_OPT_FINAL)
9147 goto err_yield;
9148
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009149 if (dir == SMP_OPT_DIR_REQ)
9150 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9151 s->hlua->wake_time);
9152 else
9153 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9154 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009155 }
9156 goto end;
9157
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009158 /* yield. */
9159 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009160 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009161 if (dir == SMP_OPT_DIR_REQ)
9162 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9163 s->hlua->wake_time);
9164 else
9165 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9166 s->hlua->wake_time);
9167
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009168 /* Some actions can be wake up when a "write" event
9169 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009170 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009171 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009172 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009173 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009174 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009175 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009176 act_ret = ACT_RET_YIELD;
9177 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009178
9179 /* finished with error. */
9180 case HLUA_E_ERRMSG:
9181 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009182 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009183 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009184 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009185 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009186
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009187 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009188 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009189 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009190
9191 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009192 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009193 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009194
9195 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009196 err_yield:
9197 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009198 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009199 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009200 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009201
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009202 case HLUA_E_ERR:
9203 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009204 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009205 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009206
9207 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009208 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009209 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009210
9211 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009212 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009213 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009214 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009215}
9216
Willy Tarreau144f84a2021-03-02 16:09:26 +01009217struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009218{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009219 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009220
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009221 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009222 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009223 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009224}
9225
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009226static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009227{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009228 struct hlua_tcp_ctx *tcp_ctx = applet_reserve_svcctx(ctx, sizeof(*tcp_ctx));
Willy Tarreau0698c802022-05-11 14:09:57 +02009229 struct conn_stream *cs = appctx_cs(ctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01009230 struct stream *strm = __cs_strm(cs);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009231 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009232 struct task *task;
9233 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009234 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009235
Willy Tarreaubafbe012017-11-24 17:34:44 +01009236 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009237 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009238 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009239 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009240 return 0;
9241 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009242 HLUA_INIT(hlua);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009243 tcp_ctx->hlua = hlua;
9244 tcp_ctx->flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009245
9246 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009247 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009248 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009249 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009250 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009251 return 0;
9252 }
9253 task->nice = 0;
9254 task->context = ctx;
9255 task->process = hlua_applet_wakeup;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009256 tcp_ctx->task = task;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009257
9258 /* In the execution wrappers linked with a stream, the
9259 * Lua context can be not initialized. This behavior
9260 * permits to save performances because a systematic
9261 * Lua initialization cause 5% performances loss.
9262 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009263 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009264 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009265 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009266 return 0;
9267 }
9268
9269 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009270 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009271
9272 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009273 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009274 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9275 error = lua_tostring(hlua->T, -1);
9276 else
9277 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009278 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009279 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009280 return 0;
9281 }
9282
9283 /* Check stack available size. */
9284 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009285 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009286 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009287 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009288 return 0;
9289 }
9290
9291 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009292 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009293
9294 /* Create and and push object stream in the stack. */
9295 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009296 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009297 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009298 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009299 return 0;
9300 }
9301 hlua->nargs = 1;
9302
9303 /* push keywords in the stack. */
9304 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9305 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009306 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009307 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009308 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009309 return 0;
9310 }
9311 lua_pushstring(hlua->T, *arg);
9312 hlua->nargs++;
9313 }
9314
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009315 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009316
9317 /* Wakeup the applet ASAP. */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009318 cs_cant_get(cs);
9319 cs_rx_endp_more(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009320
9321 return 1;
9322}
9323
Willy Tarreau60409db2019-08-21 14:14:50 +02009324void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009325{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009326 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02009327 struct conn_stream *cs = appctx_cs(ctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01009328 struct stream *strm = __cs_strm(cs);
9329 struct channel *res = cs_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009330 struct act_rule *rule = ctx->rule;
9331 struct proxy *px = strm->be;
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009332 struct hlua *hlua = tcp_ctx->hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009333
9334 /* The applet execution is already done. */
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009335 if (tcp_ctx->flags & APPLET_DONE) {
Olivier Houchard594c8c52018-08-28 14:41:31 +02009336 /* eat the whole request */
Christopher Faulet908628c2022-03-25 16:43:49 +01009337 co_skip(cs_oc(cs), co_data(cs_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009338 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009339 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009340
9341 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +02009342 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009343 return;
9344
9345 /* Execute the function. */
9346 switch (hlua_ctx_resume(hlua, 1)) {
9347 /* finished. */
9348 case HLUA_E_OK:
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009349 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009350
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009351 /* eat the whole request */
Christopher Faulet908628c2022-03-25 16:43:49 +01009352 co_skip(cs_oc(cs), co_data(cs_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009353 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009354 cs_shutr(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009355 return;
9356
9357 /* yield. */
9358 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009359 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009360 task_schedule(tcp_ctx->task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009361 return;
9362
9363 /* finished with error. */
9364 case HLUA_E_ERRMSG:
9365 /* Display log. */
9366 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009367 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009368 lua_pop(hlua->T, 1);
9369 goto error;
9370
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009371 case HLUA_E_ETMOUT:
9372 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009373 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009374 goto error;
9375
9376 case HLUA_E_NOMEM:
9377 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009378 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009379 goto error;
9380
9381 case HLUA_E_YIELD: /* unexpected */
9382 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009383 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009384 goto error;
9385
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009386 case HLUA_E_ERR:
9387 /* Display log. */
9388 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009389 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009390 goto error;
9391
9392 default:
9393 goto error;
9394 }
9395
9396error:
9397
9398 /* For all other cases, just close the stream. */
Christopher Fauletda098e62022-03-31 17:44:45 +02009399 cs_shutw(cs);
9400 cs_shutr(cs);
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009401 tcp_ctx->flags |= APPLET_DONE;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009402}
9403
9404static void hlua_applet_tcp_release(struct appctx *ctx)
9405{
Willy Tarreaue23f33b2022-05-06 14:07:13 +02009406 struct hlua_tcp_ctx *tcp_ctx = ctx->svcctx;
9407
9408 task_destroy(tcp_ctx->task);
9409 tcp_ctx->task = NULL;
9410 hlua_ctx_destroy(tcp_ctx->hlua);
9411 tcp_ctx->hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009412}
9413
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009414/* The function returns 1 if the initialisation is complete, 0 if
9415 * an errors occurs and -1 if more data are required for initializing
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009416 * the applet. It also reserves the appctx for an hlua_http_ctx.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009417 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009418static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009419{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009420 struct hlua_http_ctx *http_ctx = applet_reserve_svcctx(ctx, sizeof(*http_ctx));
Willy Tarreau0698c802022-05-11 14:09:57 +02009421 struct conn_stream *cs = appctx_cs(ctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01009422 struct stream *strm = __cs_strm(cs);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009423 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009424 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009425 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009426 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009427 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009428
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009429 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009430 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009431 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009432 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009433 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009434 return 0;
9435 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009436 HLUA_INIT(hlua);
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009437 http_ctx->hlua = hlua;
9438 http_ctx->left_bytes = -1;
9439 http_ctx->flags = 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009440
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009441 if (txn->req.flags & HTTP_MSGF_VER_11)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009442 http_ctx->flags |= APPLET_HTTP11;
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009443
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009444 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009445 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009446 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009447 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009448 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009449 return 0;
9450 }
9451 task->nice = 0;
9452 task->context = ctx;
9453 task->process = hlua_applet_wakeup;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009454 http_ctx->task = task;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009455
9456 /* In the execution wrappers linked with a stream, the
9457 * Lua context can be not initialized. This behavior
9458 * permits to save performances because a systematic
9459 * Lua initialization cause 5% performances loss.
9460 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009461 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009462 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009463 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009464 return 0;
9465 }
9466
9467 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009468 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009469
9470 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009471 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009472 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9473 error = lua_tostring(hlua->T, -1);
9474 else
9475 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009476 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009477 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009478 return 0;
9479 }
9480
9481 /* Check stack available size. */
9482 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009483 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009484 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009485 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009486 return 0;
9487 }
9488
9489 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009490 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009491
9492 /* Create and and push object stream in the stack. */
9493 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009494 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009495 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009496 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009497 return 0;
9498 }
9499 hlua->nargs = 1;
9500
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009501 /* push keywords in the stack. */
9502 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9503 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009504 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009505 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009506 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009507 return 0;
9508 }
9509 lua_pushstring(hlua->T, *arg);
9510 hlua->nargs++;
9511 }
9512
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009513 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009514
9515 /* Wakeup the applet when data is ready for read. */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009516 cs_cant_get(cs);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009517
9518 return 1;
9519}
9520
Willy Tarreau60409db2019-08-21 14:14:50 +02009521void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009522{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009523 struct hlua_http_ctx *http_ctx = ctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02009524 struct conn_stream *cs = appctx_cs(ctx);
Christopher Faulet908628c2022-03-25 16:43:49 +01009525 struct stream *strm = __cs_strm(cs);
9526 struct channel *req = cs_oc(cs);
9527 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009528 struct act_rule *rule = ctx->rule;
9529 struct proxy *px = strm->be;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009530 struct hlua *hlua = http_ctx->hlua;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009531 struct htx *req_htx, *res_htx;
9532
9533 res_htx = htx_from_buf(&res->buf);
9534
9535 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +02009536 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009537 goto out;
9538
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009539 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009540 if (!b_size(&res->buf)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009541 cs_rx_room_blk(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009542 goto out;
9543 }
9544 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009545 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009546 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009547
9548 /* Set the currently running flag. */
9549 if (!HLUA_IS_RUNNING(hlua) &&
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009550 !(http_ctx->flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009551 if (!co_data(req)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009552 cs_cant_get(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009553 goto out;
9554 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009555 }
9556
9557 /* Executes The applet if it is not done. */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009558 if (!(http_ctx->flags & APPLET_DONE)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009559
9560 /* Execute the function. */
9561 switch (hlua_ctx_resume(hlua, 1)) {
9562 /* finished. */
9563 case HLUA_E_OK:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009564 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009565 break;
9566
9567 /* yield. */
9568 case HLUA_E_AGAIN:
9569 if (hlua->wake_time != TICK_ETERNITY)
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009570 task_schedule(http_ctx->task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009571 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009572
9573 /* finished with error. */
9574 case HLUA_E_ERRMSG:
9575 /* Display log. */
9576 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009577 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009578 lua_pop(hlua->T, 1);
9579 goto error;
9580
9581 case HLUA_E_ETMOUT:
9582 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009583 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009584 goto error;
9585
9586 case HLUA_E_NOMEM:
9587 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009588 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009589 goto error;
9590
9591 case HLUA_E_YIELD: /* unexpected */
9592 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009593 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009594 goto error;
9595
9596 case HLUA_E_ERR:
9597 /* Display log. */
9598 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009599 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009600 goto error;
9601
9602 default:
9603 goto error;
9604 }
9605 }
9606
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009607 if (http_ctx->flags & APPLET_DONE) {
9608 if (http_ctx->flags & APPLET_RSP_SENT)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009609 goto done;
9610
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009611 if (!(http_ctx->flags & APPLET_HDR_SENT))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009612 goto error;
9613
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009614 /* no more data are expected. If the response buffer is empty
9615 * for a chunked message, be sure to add something (EOT block in
9616 * this case) to have something to send. It is important to be
9617 * sure the EOM flags will be handled by the endpoint.
9618 */
9619 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9620 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009621 cs_rx_room_blk(cs);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009622 goto out;
9623 }
9624 channel_add_input(res, 1);
9625 }
9626
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009627 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009628 res->flags |= CF_EOI;
Willy Tarreau66435e52022-05-10 11:32:31 +02009629 ctx->endp->flags |= CS_EP_EOI;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009630 strm->txn->status = http_ctx->status;
9631 http_ctx->flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009632 }
9633
9634 done:
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009635 if (http_ctx->flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009636 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009637 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009638 cs_shutr(cs);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009639 }
9640
9641 /* eat the whole request */
9642 if (co_data(req)) {
9643 req_htx = htx_from_buf(&req->buf);
9644 co_htx_skip(req, req_htx, co_data(req));
9645 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009646 }
9647 }
9648
9649 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009650 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009651 return;
9652
9653 error:
9654
9655 /* If we are in HTTP mode, and we are not send any
9656 * data, return a 500 server error in best effort:
9657 * if there is no room available in the buffer,
9658 * just close the connection.
9659 */
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009660 if (!(http_ctx->flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009661 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009662
9663 channel_erase(res);
9664 res->buf.data = b_data(err);
9665 memcpy(res->buf.area, b_head(err), b_data(err));
9666 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009667 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009668 }
9669 if (!(strm->flags & SF_ERR_MASK))
9670 strm->flags |= SF_ERR_RESOURCE;
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009671 http_ctx->flags |= APPLET_DONE;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009672 goto done;
9673}
9674
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009675static void hlua_applet_http_release(struct appctx *ctx)
9676{
Willy Tarreauaa229cc2022-05-06 14:26:10 +02009677 struct hlua_http_ctx *http_ctx = ctx->svcctx;
9678
9679 task_destroy(http_ctx->task);
9680 http_ctx->task = NULL;
9681 hlua_ctx_destroy(http_ctx->hlua);
9682 http_ctx->hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009683}
9684
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009685/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009686 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009687 *
9688 * This function can fail with an abort() due to an Lua critical error.
9689 * We are in the configuration parsing process of HAProxy, this abort() is
9690 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009691 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009692static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9693 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009694{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009695 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009696 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009697
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009698 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009699 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009700 if (!rule->arg.hlua_rule) {
9701 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009702 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009703 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009704
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009705 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009706 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9707 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009708 if (!rule->arg.hlua_rule->args) {
9709 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009710 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009711 }
9712
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009713 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009714 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009715
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009716 /* Expect some arguments */
9717 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009718 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009719 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009720 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009721 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009722 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009723 if (!rule->arg.hlua_rule->args[i]) {
9724 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009725 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009726 }
9727 (*cur_arg)++;
9728 }
9729 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009730
Thierry FOURNIER42148732015-09-02 17:17:33 +02009731 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009732 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009733 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009734
9735 error:
9736 if (rule->arg.hlua_rule) {
9737 if (rule->arg.hlua_rule->args) {
9738 for (i = 0; i < fcn->nargs; i++)
9739 ha_free(&rule->arg.hlua_rule->args[i]);
9740 ha_free(&rule->arg.hlua_rule->args);
9741 }
9742 ha_free(&rule->arg.hlua_rule);
9743 }
9744 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009745}
9746
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009747static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9748 struct act_rule *rule, char **err)
9749{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009750 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009751
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009752 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009753 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009754 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009755 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009756 * the call of this analyzer.
9757 */
9758 if (rule->from != ACT_F_HTTP_REQ) {
9759 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9760 return ACT_RET_PRS_ERR;
9761 }
9762
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009763 /* Memory for the rule. */
9764 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9765 if (!rule->arg.hlua_rule) {
9766 memprintf(err, "out of memory error");
9767 return ACT_RET_PRS_ERR;
9768 }
9769
9770 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009771 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009772
9773 /* TODO: later accept arguments. */
9774 rule->arg.hlua_rule->args = NULL;
9775
9776 /* Add applet pointer in the rule. */
9777 rule->applet.obj_type = OBJ_TYPE_APPLET;
9778 rule->applet.name = fcn->name;
9779 rule->applet.init = hlua_applet_http_init;
9780 rule->applet.fct = hlua_applet_http_fct;
9781 rule->applet.release = hlua_applet_http_release;
9782 rule->applet.timeout = hlua_timeout_applet;
9783
9784 return ACT_RET_PRS_OK;
9785}
9786
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009787/* This function is an LUA binding used for registering
9788 * "sample-conv" functions. It expects a converter name used
9789 * in the haproxy configuration file, and an LUA function.
9790 */
9791__LJMP static int hlua_register_action(lua_State *L)
9792{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009793 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009794 const char *name;
9795 int ref;
9796 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009797 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009798 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009799 struct buffer *trash;
9800 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009801
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009802 /* Initialise the number of expected arguments at 0. */
9803 nargs = 0;
9804
9805 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9806 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009807
9808 /* First argument : converter name. */
9809 name = MAY_LJMP(luaL_checkstring(L, 1));
9810
9811 /* Second argument : environment. */
9812 if (lua_type(L, 2) != LUA_TTABLE)
9813 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9814
9815 /* Third argument : lua function. */
9816 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9817
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009818 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009819 if (lua_gettop(L) >= 4)
9820 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9821
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009822 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009823 lua_pushnil(L);
9824 while (lua_next(L, 2) != 0) {
9825 if (lua_type(L, -1) != LUA_TSTRING)
9826 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9827
Thierry Fournierf67442e2020-11-28 20:41:07 +01009828 /* Check if action exists */
9829 trash = get_trash_chunk();
9830 chunk_printf(trash, "lua.%s", name);
9831 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9832 akw = tcp_req_cont_action(trash->area);
9833 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9834 akw = tcp_res_cont_action(trash->area);
9835 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9836 akw = action_http_req_custom(trash->area);
9837 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9838 akw = action_http_res_custom(trash->area);
9839 } else {
9840 akw = NULL;
9841 }
9842 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009843 fcn = akw->private;
9844 if (fcn->function_ref[hlua_state_id] != -1) {
9845 ha_warning("Trying to register action 'lua.%s' more than once. "
9846 "This will become a hard error in version 2.5.\n", name);
9847 }
9848 fcn->function_ref[hlua_state_id] = ref;
9849
9850 /* pop the environment string. */
9851 lua_pop(L, 1);
9852 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009853 }
9854
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009855 /* Check required environment. Only accepted "http" or "tcp". */
9856 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009857 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009858 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009859 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009860 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009861 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009862 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009863
9864 /* Fill fcn. */
9865 fcn->name = strdup(name);
9866 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009867 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009868 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009869
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009870 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009871 fcn->nargs = nargs;
9872
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009873 /* List head */
9874 akl->list.n = akl->list.p = NULL;
9875
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009876 /* action keyword. */
9877 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009878 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009879 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009880 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009881
9882 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9883
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009884 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009885 akl->kw[0].private = fcn;
9886 akl->kw[0].parse = action_register_lua;
9887
9888 /* select the action registering point. */
9889 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9890 tcp_req_cont_keywords_register(akl);
9891 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9892 tcp_res_cont_keywords_register(akl);
9893 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9894 http_req_keywords_register(akl);
9895 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9896 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009897 else {
9898 release_hlua_function(fcn);
9899 if (akl)
9900 ha_free((char **)&(akl->kw[0].kw));
9901 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009902 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009903 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9904 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009905 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009906
9907 /* pop the environment string. */
9908 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009909
9910 /* reset for next loop */
9911 akl = NULL;
9912 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009913 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009914 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009915
9916 alloc_error:
9917 release_hlua_function(fcn);
9918 ha_free(&akl);
9919 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9920 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009921}
9922
9923static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9924 struct act_rule *rule, char **err)
9925{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009926 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009927
Christopher Faulet280f85b2019-07-15 15:02:04 +02009928 if (px->mode == PR_MODE_HTTP) {
9929 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009930 return ACT_RET_PRS_ERR;
9931 }
9932
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009933 /* Memory for the rule. */
9934 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9935 if (!rule->arg.hlua_rule) {
9936 memprintf(err, "out of memory error");
9937 return ACT_RET_PRS_ERR;
9938 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009939
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009940 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009941 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009942
9943 /* TODO: later accept arguments. */
9944 rule->arg.hlua_rule->args = NULL;
9945
9946 /* Add applet pointer in the rule. */
9947 rule->applet.obj_type = OBJ_TYPE_APPLET;
9948 rule->applet.name = fcn->name;
9949 rule->applet.init = hlua_applet_tcp_init;
9950 rule->applet.fct = hlua_applet_tcp_fct;
9951 rule->applet.release = hlua_applet_tcp_release;
9952 rule->applet.timeout = hlua_timeout_applet;
9953
9954 return 0;
9955}
9956
9957/* This function is an LUA binding used for registering
9958 * "sample-conv" functions. It expects a converter name used
9959 * in the haproxy configuration file, and an LUA function.
9960 */
9961__LJMP static int hlua_register_service(lua_State *L)
9962{
9963 struct action_kw_list *akl;
9964 const char *name;
9965 const char *env;
9966 int ref;
9967 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009968 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009969 struct buffer *trash;
9970 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009971
9972 MAY_LJMP(check_args(L, 3, "register_service"));
9973
9974 /* First argument : converter name. */
9975 name = MAY_LJMP(luaL_checkstring(L, 1));
9976
9977 /* Second argument : environment. */
9978 env = MAY_LJMP(luaL_checkstring(L, 2));
9979
9980 /* Third argument : lua function. */
9981 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9982
Thierry Fournierf67442e2020-11-28 20:41:07 +01009983 /* Check for service already registered */
9984 trash = get_trash_chunk();
9985 chunk_printf(trash, "lua.%s", name);
9986 akw = service_find(trash->area);
9987 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009988 fcn = akw->private;
9989 if (fcn->function_ref[hlua_state_id] != -1) {
9990 ha_warning("Trying to register service 'lua.%s' more than once. "
9991 "This will become a hard error in version 2.5.\n", name);
9992 }
9993 fcn->function_ref[hlua_state_id] = ref;
9994 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009995 }
9996
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009997 /* Allocate and fill the sample fetch keyword struct. */
9998 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9999 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010000 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010001 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010002 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010003 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010004
10005 /* Fill fcn. */
10006 len = strlen("<lua.>") + strlen(name) + 1;
10007 fcn->name = calloc(1, len);
10008 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010009 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010010 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +010010011 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010012
10013 /* List head */
10014 akl->list.n = akl->list.p = NULL;
10015
10016 /* converter keyword. */
10017 len = strlen("lua.") + strlen(name) + 1;
10018 akl->kw[0].kw = calloc(1, len);
10019 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +020010020 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010021
10022 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
10023
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010024 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010025 if (strcmp(env, "tcp") == 0)
10026 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010027 else if (strcmp(env, "http") == 0)
10028 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010029 else {
10030 release_hlua_function(fcn);
10031 if (akl)
10032 ha_free((char **)&(akl->kw[0].kw));
10033 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010034 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010035 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010036 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010037
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010038 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010039 akl->kw[0].private = fcn;
10040
10041 /* End of array. */
10042 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10043
10044 /* Register this new converter */
10045 service_keywords_register(akl);
10046
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010047 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010048
10049 alloc_error:
10050 release_hlua_function(fcn);
10051 ha_free(&akl);
10052 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10053 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010054}
10055
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010056/* This function initialises Lua cli handler. It copies the
10057 * arguments in the Lua stack and create channel IO objects.
10058 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010059static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010060{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010061 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010062 struct hlua *hlua;
10063 struct hlua_function *fcn;
10064 int i;
10065 const char *error;
10066
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010067 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010068 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010069
Willy Tarreaubafbe012017-11-24 17:34:44 +010010070 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010071 if (!hlua) {
10072 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010073 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010074 }
10075 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010076 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010077
10078 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010079 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010080 * applet_http. It is absolutely compatible.
10081 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010082 ctx->task = task_new_here();
10083 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010084 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010085 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010086 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010087 ctx->task->nice = 0;
10088 ctx->task->context = appctx;
10089 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010090
10091 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010092 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010093 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010094 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010095 }
10096
10097 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010098 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010099 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10100 error = lua_tostring(hlua->T, -1);
10101 else
10102 error = "critical error";
10103 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10104 goto error;
10105 }
10106
10107 /* Check stack available size. */
10108 if (!lua_checkstack(hlua->T, 2)) {
10109 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10110 goto error;
10111 }
10112
10113 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010114 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010115
10116 /* Once the arguments parsed, the CLI is like an AppletTCP,
10117 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010118 */
10119 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10120 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10121 goto error;
10122 }
10123 hlua->nargs = 1;
10124
10125 /* push keywords in the stack. */
10126 for (i = 0; *args[i]; i++) {
10127 /* Check stack available size. */
10128 if (!lua_checkstack(hlua->T, 1)) {
10129 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10130 goto error;
10131 }
10132 lua_pushstring(hlua->T, args[i]);
10133 hlua->nargs++;
10134 }
10135
10136 /* We must initialize the execution timeouts. */
10137 hlua->max_time = hlua_timeout_session;
10138
10139 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010140 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010141
10142 /* It's ok */
10143 return 0;
10144
10145 /* It's not ok. */
10146error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010147 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010148 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010149 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010150 return 1;
10151}
10152
10153static int hlua_cli_io_handler_fct(struct appctx *appctx)
10154{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010155 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010156 struct hlua *hlua;
Christopher Faulet908628c2022-03-25 16:43:49 +010010157 struct conn_stream *cs;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010158 struct hlua_function *fcn;
10159
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010160 hlua = ctx->hlua;
Willy Tarreau0698c802022-05-11 14:09:57 +020010161 cs = appctx_cs(appctx);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010162 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010163
10164 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +020010165 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010166 return 1;
10167
10168 /* Execute the function. */
10169 switch (hlua_ctx_resume(hlua, 1)) {
10170
10171 /* finished. */
10172 case HLUA_E_OK:
10173 return 1;
10174
10175 /* yield. */
10176 case HLUA_E_AGAIN:
10177 /* We want write. */
10178 if (HLUA_IS_WAKERESWR(hlua))
Christopher Fauleta0bdec32022-04-04 07:51:21 +020010179 cs_rx_room_blk(cs);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010180 /* Set the timeout. */
10181 if (hlua->wake_time != TICK_ETERNITY)
10182 task_schedule(hlua->task, hlua->wake_time);
10183 return 0;
10184
10185 /* finished with error. */
10186 case HLUA_E_ERRMSG:
10187 /* Display log. */
10188 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10189 fcn->name, lua_tostring(hlua->T, -1));
10190 lua_pop(hlua->T, 1);
10191 return 1;
10192
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010193 case HLUA_E_ETMOUT:
10194 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10195 fcn->name);
10196 return 1;
10197
10198 case HLUA_E_NOMEM:
10199 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10200 fcn->name);
10201 return 1;
10202
10203 case HLUA_E_YIELD: /* unexpected */
10204 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10205 fcn->name);
10206 return 1;
10207
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010208 case HLUA_E_ERR:
10209 /* Display log. */
10210 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10211 fcn->name);
10212 return 1;
10213
10214 default:
10215 return 1;
10216 }
10217
10218 return 1;
10219}
10220
10221static void hlua_cli_io_release_fct(struct appctx *appctx)
10222{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010223 struct hlua_cli_ctx *ctx = appctx->svcctx;
10224
10225 hlua_ctx_destroy(ctx->hlua);
10226 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010227}
10228
10229/* This function is an LUA binding used for registering
10230 * new keywords in the cli. It expects a list of keywords
10231 * which are the "path". It is limited to 5 keywords. A
10232 * description of the command, a function to be executed
10233 * for the parsing and a function for io handlers.
10234 */
10235__LJMP static int hlua_register_cli(lua_State *L)
10236{
10237 struct cli_kw_list *cli_kws;
10238 const char *message;
10239 int ref_io;
10240 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010241 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010242 int index;
10243 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010244 struct buffer *trash;
10245 const char *kw[5];
10246 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010247 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010248
10249 MAY_LJMP(check_args(L, 3, "register_cli"));
10250
10251 /* First argument : an array of maximum 5 keywords. */
10252 if (!lua_istable(L, 1))
10253 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10254
10255 /* Second argument : string with contextual message. */
10256 message = MAY_LJMP(luaL_checkstring(L, 2));
10257
10258 /* Third and fourth argument : lua function. */
10259 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10260
Thierry Fournierf67442e2020-11-28 20:41:07 +010010261 /* Check for CLI service already registered */
10262 trash = get_trash_chunk();
10263 index = 0;
10264 lua_pushnil(L);
10265 memset(kw, 0, sizeof(kw));
10266 while (lua_next(L, 1) != 0) {
10267 if (index >= CLI_PREFIX_KW_NB)
10268 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10269 if (lua_type(L, -1) != LUA_TSTRING)
10270 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10271 kw[index] = lua_tostring(L, -1);
10272 if (index == 0)
10273 chunk_printf(trash, "%s", kw[index]);
10274 else
10275 chunk_appendf(trash, " %s", kw[index]);
10276 index++;
10277 lua_pop(L, 1);
10278 }
10279 cli_kw = cli_find_kw_exact((char **)kw);
10280 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010281 fcn = cli_kw->private;
10282 if (fcn->function_ref[hlua_state_id] != -1) {
10283 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10284 "This will become a hard error in version 2.5.\n", trash->area);
10285 }
10286 fcn->function_ref[hlua_state_id] = ref_io;
10287 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010288 }
10289
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010290 /* Allocate and fill the sample fetch keyword struct. */
10291 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010292 if (!cli_kws) {
10293 errmsg = "Lua out of memory error.";
10294 goto error;
10295 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010296 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010297 if (!fcn) {
10298 errmsg = "Lua out of memory error.";
10299 goto error;
10300 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010301
10302 /* Fill path. */
10303 index = 0;
10304 lua_pushnil(L);
10305 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010306 if (index >= 5) {
10307 errmsg = "1st argument must be a table with a maximum of 5 entries";
10308 goto error;
10309 }
10310 if (lua_type(L, -1) != LUA_TSTRING) {
10311 errmsg = "1st argument must be a table filled with strings";
10312 goto error;
10313 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010314 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010315 if (!cli_kws->kw[0].str_kw[index]) {
10316 errmsg = "Lua out of memory error.";
10317 goto error;
10318 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010319 index++;
10320 lua_pop(L, 1);
10321 }
10322
10323 /* Copy help message. */
10324 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010325 if (!cli_kws->kw[0].usage) {
10326 errmsg = "Lua out of memory error.";
10327 goto error;
10328 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010329
10330 /* Fill fcn io handler. */
10331 len = strlen("<lua.cli>") + 1;
10332 for (i = 0; i < index; i++)
10333 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10334 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010335 if (!fcn->name) {
10336 errmsg = "Lua out of memory error.";
10337 goto error;
10338 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010339 strncat((char *)fcn->name, "<lua.cli", len);
10340 for (i = 0; i < index; i++) {
10341 strncat((char *)fcn->name, ".", len);
10342 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10343 }
10344 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010345 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010346
10347 /* Fill last entries. */
10348 cli_kws->kw[0].private = fcn;
10349 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10350 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10351 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10352
10353 /* Register this new converter */
10354 cli_register_kw(cli_kws);
10355
10356 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010357
10358 error:
10359 release_hlua_function(fcn);
10360 if (cli_kws) {
10361 for (i = 0; i < index; i++)
10362 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10363 ha_free((char **)&(cli_kws->kw[0].usage));
10364 }
10365 ha_free(&cli_kws);
10366 WILL_LJMP(luaL_error(L, errmsg));
10367 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010368}
10369
Christopher Faulet69c581a2021-05-31 08:54:04 +020010370static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10371{
10372 struct hlua_flt_config *conf = fconf->conf;
10373 lua_State *L;
10374 int error, pos, state_id, flt_ref;
10375
10376 state_id = reg_flt_to_stack_id(conf->reg);
10377 L = hlua_states[state_id];
10378 pos = lua_gettop(L);
10379
10380 /* The filter parsing function */
10381 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10382
10383 /* Push the filter class on the stack and resolve all callbacks */
10384 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10385
10386 /* Duplicate the filter class so each filter will have its own copy */
10387 lua_newtable(L);
10388 lua_pushnil(L);
10389
10390 while (lua_next(L, pos+2)) {
10391 lua_pushvalue(L, -2);
10392 lua_insert(L, -2);
10393 lua_settable(L, -4);
10394 }
10395 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10396
10397 /* Remove the original lua filter class from the stack */
10398 lua_pop(L, 1);
10399
10400 /* Push the copy on the stack */
10401 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10402
10403 /* extra args are pushed in a table */
10404 lua_newtable(L);
10405 for (pos = 0; conf->args[pos]; pos++) {
10406 /* Check stack available size. */
10407 if (!lua_checkstack(L, 1)) {
10408 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10409 goto error;
10410 }
10411 lua_pushstring(L, conf->args[pos]);
10412 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10413 }
10414
10415 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10416 switch (error) {
10417 case LUA_OK:
10418 /* replace the filter ref */
10419 conf->ref[state_id] = flt_ref;
10420 break;
10421 case LUA_ERRRUN:
10422 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10423 goto error;
10424 case LUA_ERRMEM:
10425 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10426 goto error;
10427 case LUA_ERRERR:
10428 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10429 goto error;
10430#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10431 case LUA_ERRGCMM:
10432 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10433 goto error;
10434#endif
10435 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010436 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010437 goto error;
10438 }
10439
10440 lua_settop(L, 0);
10441 return 0;
10442
10443 error:
10444 lua_settop(L, 0);
10445 return -1;
10446}
10447
10448static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10449{
10450 struct hlua_flt_config *conf = fconf->conf;
10451 lua_State *L;
10452 int state_id;
10453
10454 if (!conf)
10455 return;
10456
10457 state_id = reg_flt_to_stack_id(conf->reg);
10458 L = hlua_states[state_id];
10459 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10460}
10461
10462static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10463{
10464 struct hlua_flt_config *conf = fconf->conf;
10465 int state_id = reg_flt_to_stack_id(conf->reg);
10466
10467 /* Rely on per-thread init for global scripts */
10468 if (!state_id)
10469 return hlua_filter_init_per_thread(px, fconf);
10470 return 0;
10471}
10472
10473static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10474{
10475
10476 if (fconf->conf) {
10477 struct hlua_flt_config *conf = fconf->conf;
10478 int state_id = reg_flt_to_stack_id(conf->reg);
10479 int pos;
10480
10481 /* Rely on per-thread deinit for global scripts */
10482 if (!state_id)
10483 hlua_filter_deinit_per_thread(px, fconf);
10484
10485 for (pos = 0; conf->args[pos]; pos++)
10486 free(conf->args[pos]);
10487 free(conf->args);
10488 }
10489 ha_free(&fconf->conf);
10490 ha_free((char **)&fconf->id);
10491 ha_free(&fconf->ops);
10492}
10493
10494static int hlua_filter_new(struct stream *s, struct filter *filter)
10495{
10496 struct hlua_flt_config *conf = FLT_CONF(filter);
10497 struct hlua_flt_ctx *flt_ctx = NULL;
10498 int ret = 1;
10499
10500 /* In the execution wrappers linked with a stream, the
10501 * Lua context can be not initialized. This behavior
10502 * permits to save performances because a systematic
10503 * Lua initialization cause 5% performances loss.
10504 */
10505 if (!s->hlua) {
10506 struct hlua *hlua;
10507
10508 hlua = pool_alloc(pool_head_hlua);
10509 if (!hlua) {
10510 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10511 conf->reg->name);
10512 ret = 0;
10513 goto end;
10514 }
10515 HLUA_INIT(hlua);
10516 s->hlua = hlua;
10517 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10518 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10519 conf->reg->name);
10520 ret = 0;
10521 goto end;
10522 }
10523 }
10524
10525 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10526 if (!flt_ctx) {
10527 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10528 conf->reg->name);
10529 ret = 0;
10530 goto end;
10531 }
10532 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10533 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10534 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10535 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10536 conf->reg->name);
10537 ret = 0;
10538 goto end;
10539 }
10540 HLUA_INIT(flt_ctx->hlua[0]);
10541 HLUA_INIT(flt_ctx->hlua[1]);
10542 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10543 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10544 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10545 conf->reg->name);
10546 ret = 0;
10547 goto end;
10548 }
10549
10550 if (!HLUA_IS_RUNNING(s->hlua)) {
10551 /* The following Lua calls can fail. */
10552 if (!SET_SAFE_LJMP(s->hlua)) {
10553 const char *error;
10554
10555 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10556 error = lua_tostring(s->hlua->T, -1);
10557 else
10558 error = "critical error";
10559 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10560 ret = 0;
10561 goto end;
10562 }
10563
10564 /* Check stack size. */
10565 if (!lua_checkstack(s->hlua->T, 1)) {
10566 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010567 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010568 ret = 0;
10569 goto end;
10570 }
10571
10572 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10573 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10574 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10575 conf->reg->name);
10576 RESET_SAFE_LJMP(s->hlua);
10577 ret = 0;
10578 goto end;
10579 }
10580 lua_insert(s->hlua->T, -2);
10581
10582 /* Push the copy on the stack */
10583 s->hlua->nargs = 1;
10584
10585 /* We must initialize the execution timeouts. */
10586 s->hlua->max_time = hlua_timeout_session;
10587
10588 /* At this point the execution is safe. */
10589 RESET_SAFE_LJMP(s->hlua);
10590 }
10591
10592 switch (hlua_ctx_resume(s->hlua, 0)) {
10593 case HLUA_E_OK:
10594 /* Nothing returned or not a table, ignore the filter for current stream */
10595 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10596 ret = 0;
10597 goto end;
10598 }
10599
10600 /* Attached the filter pointer to the ctx */
10601 lua_pushstring(s->hlua->T, "__filter");
10602 lua_pushlightuserdata(s->hlua->T, filter);
10603 lua_settable(s->hlua->T, -3);
10604
10605 /* Save a ref on the filter ctx */
10606 lua_pushvalue(s->hlua->T, 1);
10607 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10608 filter->ctx = flt_ctx;
10609 break;
10610 case HLUA_E_ERRMSG:
10611 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10612 ret = -1;
10613 goto end;
10614 case HLUA_E_ETMOUT:
10615 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10616 ret = 0;
10617 goto end;
10618 case HLUA_E_NOMEM:
10619 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10620 ret = 0;
10621 goto end;
10622 case HLUA_E_AGAIN:
10623 case HLUA_E_YIELD:
10624 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10625 " are not allowed from 'new' function.\n", conf->reg->name);
10626 ret = 0;
10627 goto end;
10628 case HLUA_E_ERR:
10629 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10630 ret = 0;
10631 goto end;
10632 default:
10633 ret = 0;
10634 goto end;
10635 }
10636
10637 end:
10638 if (s->hlua)
10639 lua_settop(s->hlua->T, 0);
10640 if (ret <= 0) {
10641 if (flt_ctx) {
10642 hlua_ctx_destroy(flt_ctx->hlua[0]);
10643 hlua_ctx_destroy(flt_ctx->hlua[1]);
10644 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10645 }
10646 }
10647 return ret;
10648}
10649
10650static void hlua_filter_delete(struct stream *s, struct filter *filter)
10651{
10652 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10653
10654 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10655 hlua_ctx_destroy(flt_ctx->hlua[0]);
10656 hlua_ctx_destroy(flt_ctx->hlua[1]);
10657 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10658 filter->ctx = NULL;
10659}
10660
Christopher Faulet9f55a502020-02-25 15:21:02 +010010661static int hlua_filter_from_payload(struct filter *filter)
10662{
10663 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10664
10665 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10666}
10667
Christopher Fauletc404f112020-02-26 15:03:09 +010010668static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10669 int dir, unsigned int flags)
10670{
10671 struct hlua *flt_hlua;
10672 struct hlua_flt_config *conf = FLT_CONF(filter);
10673 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10674 unsigned int hflags = HLUA_TXN_FLT_CTX;
10675 int ret = 1;
10676
10677 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10678 if (!flt_hlua)
10679 goto end;
10680
10681 if (!HLUA_IS_RUNNING(flt_hlua)) {
10682 int extra_idx = lua_gettop(flt_hlua->T);
10683
10684 /* The following Lua calls can fail. */
10685 if (!SET_SAFE_LJMP(flt_hlua)) {
10686 const char *error;
10687
10688 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10689 error = lua_tostring(flt_hlua->T, -1);
10690 else
10691 error = "critical error";
10692 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10693 goto end;
10694 }
10695
10696 /* Check stack size. */
10697 if (!lua_checkstack(flt_hlua->T, 3)) {
10698 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10699 RESET_SAFE_LJMP(flt_hlua);
10700 goto end;
10701 }
10702
10703 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10704 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10705 RESET_SAFE_LJMP(flt_hlua);
10706 goto end;
10707 }
10708 lua_insert(flt_hlua->T, -2);
10709
10710 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10711 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10712 RESET_SAFE_LJMP(flt_hlua);
10713 goto end;
10714 }
10715 flt_hlua->nargs = 2;
10716
10717 if (flags & HLUA_FLT_CB_ARG_CHN) {
10718 if (dir == SMP_OPT_DIR_REQ)
10719 lua_getfield(flt_hlua->T, -1, "req");
10720 else
10721 lua_getfield(flt_hlua->T, -1, "res");
10722 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10723 lua_pushstring(flt_hlua->T, "__filter");
10724 lua_pushlightuserdata(flt_hlua->T, filter);
10725 lua_settable(flt_hlua->T, -3);
10726 }
10727 flt_hlua->nargs++;
10728 }
10729 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010730 if (dir == SMP_OPT_DIR_REQ)
10731 lua_getfield(flt_hlua->T, -1, "http_req");
10732 else
10733 lua_getfield(flt_hlua->T, -1, "http_res");
10734 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10735 lua_pushstring(flt_hlua->T, "__filter");
10736 lua_pushlightuserdata(flt_hlua->T, filter);
10737 lua_settable(flt_hlua->T, -3);
10738 }
10739 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010740 }
10741
10742 /* Check stack size. */
10743 if (!lua_checkstack(flt_hlua->T, 1)) {
10744 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10745 RESET_SAFE_LJMP(flt_hlua);
10746 goto end;
10747 }
10748
10749 while (extra_idx--) {
10750 lua_pushvalue(flt_hlua->T, 1);
10751 lua_remove(flt_hlua->T, 1);
10752 flt_hlua->nargs++;
10753 }
10754
10755 /* We must initialize the execution timeouts. */
10756 flt_hlua->max_time = hlua_timeout_session;
10757
10758 /* At this point the execution is safe. */
10759 RESET_SAFE_LJMP(flt_hlua);
10760 }
10761
10762 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10763 case HLUA_E_OK:
10764 /* Catch the return value if it required */
10765 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10766 ret = lua_tointeger(flt_hlua->T, -1);
10767 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10768 }
10769
10770 /* Set timeout in the required channel. */
10771 if (flt_hlua->wake_time != TICK_ETERNITY) {
10772 if (dir == SMP_OPT_DIR_REQ)
10773 s->req.analyse_exp = flt_hlua->wake_time;
10774 else
10775 s->res.analyse_exp = flt_hlua->wake_time;
10776 }
10777 break;
10778 case HLUA_E_AGAIN:
10779 /* Set timeout in the required channel. */
10780 if (flt_hlua->wake_time != TICK_ETERNITY) {
10781 if (dir == SMP_OPT_DIR_REQ)
10782 s->req.analyse_exp = flt_hlua->wake_time;
10783 else
10784 s->res.analyse_exp = flt_hlua->wake_time;
10785 }
10786 /* Some actions can be wake up when a "write" event
10787 * is detected on a response channel. This is useful
10788 * only for actions targeted on the requests.
10789 */
10790 if (HLUA_IS_WAKERESWR(flt_hlua))
10791 s->res.flags |= CF_WAKE_WRITE;
10792 if (HLUA_IS_WAKEREQWR(flt_hlua))
10793 s->req.flags |= CF_WAKE_WRITE;
10794 ret = 0;
10795 goto end;
10796 case HLUA_E_ERRMSG:
10797 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10798 ret = -1;
10799 goto end;
10800 case HLUA_E_ETMOUT:
10801 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10802 goto end;
10803 case HLUA_E_NOMEM:
10804 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10805 goto end;
10806 case HLUA_E_YIELD:
10807 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10808 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10809 goto end;
10810 case HLUA_E_ERR:
10811 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10812 goto end;
10813 default:
10814 goto end;
10815 }
10816
10817
10818 end:
10819 return ret;
10820}
10821
10822static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10823{
10824 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10825
10826 flt_ctx->flags = 0;
10827 return hlua_filter_callback(s, filter, "start_analyze",
10828 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10829 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10830}
10831
10832static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10833{
10834 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10835
10836 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10837 return hlua_filter_callback(s, filter, "end_analyze",
10838 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10839 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10840}
10841
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010842static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10843{
10844 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10845
10846 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10847 return hlua_filter_callback(s, filter, "http_headers",
10848 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10849 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10850}
10851
10852static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10853 unsigned int offset, unsigned int len)
10854{
10855 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10856 struct hlua *flt_hlua;
10857 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10858 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10859 int ret;
10860
10861 flt_hlua = flt_ctx->hlua[idx];
10862 flt_ctx->cur_off[idx] = offset;
10863 flt_ctx->cur_len[idx] = len;
10864 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10865 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10866 if (ret != -1) {
10867 ret = flt_ctx->cur_len[idx];
10868 if (lua_gettop(flt_hlua->T) > 0) {
10869 ret = lua_tointeger(flt_hlua->T, -1);
10870 if (ret > flt_ctx->cur_len[idx])
10871 ret = flt_ctx->cur_len[idx];
10872 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10873 }
10874 }
10875 return ret;
10876}
10877
10878static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10879{
10880 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10881
10882 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10883 return hlua_filter_callback(s, filter, "http_end",
10884 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10885 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10886}
10887
Christopher Fauletc404f112020-02-26 15:03:09 +010010888static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10889 unsigned int offset, unsigned int len)
10890{
10891 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10892 struct hlua *flt_hlua;
10893 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10894 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10895 int ret;
10896
10897 flt_hlua = flt_ctx->hlua[idx];
10898 flt_ctx->cur_off[idx] = offset;
10899 flt_ctx->cur_len[idx] = len;
10900 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10901 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10902 if (ret != -1) {
10903 ret = flt_ctx->cur_len[idx];
10904 if (lua_gettop(flt_hlua->T) > 0) {
10905 ret = lua_tointeger(flt_hlua->T, -1);
10906 if (ret > flt_ctx->cur_len[idx])
10907 ret = flt_ctx->cur_len[idx];
10908 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10909 }
10910 }
10911 return ret;
10912}
10913
Christopher Faulet69c581a2021-05-31 08:54:04 +020010914static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10915 struct flt_conf *fconf, char **err, void *private)
10916{
10917 struct hlua_reg_filter *reg_flt = private;
10918 lua_State *L;
10919 struct hlua_flt_config *conf = NULL;
10920 const char *flt_id = NULL;
10921 int state_id, pos, flt_flags = 0;
10922 struct flt_ops *hlua_flt_ops = NULL;
10923
10924 state_id = reg_flt_to_stack_id(reg_flt);
10925 L = hlua_states[state_id];
10926
10927 /* Initialize the filter ops with default callbacks */
10928 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010929 if (!hlua_flt_ops)
10930 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010931 hlua_flt_ops->init = hlua_filter_init;
10932 hlua_flt_ops->deinit = hlua_filter_deinit;
10933 if (state_id) {
10934 /* Set per-thread callback if script is loaded per-thread */
10935 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10936 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10937 }
10938 hlua_flt_ops->attach = hlua_filter_new;
10939 hlua_flt_ops->detach = hlua_filter_delete;
10940
10941 /* Push the filter class on the stack and resolve all callbacks */
10942 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10943
Christopher Fauletc404f112020-02-26 15:03:09 +010010944 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10945 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10946 lua_pop(L, 1);
10947 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10948 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10949 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010950 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10951 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10952 lua_pop(L, 1);
10953 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10954 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10955 lua_pop(L, 1);
10956 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10957 hlua_flt_ops->http_end = hlua_filter_http_end;
10958 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010959 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10960 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10961 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010962
10963 /* Get id and flags of the filter class */
10964 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10965 flt_id = lua_tostring(L, -1);
10966 lua_pop(L, 1);
10967 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10968 flt_flags = lua_tointeger(L, -1);
10969 lua_pop(L, 1);
10970
10971 /* Create the filter config */
10972 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010973 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010974 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010975 conf->reg = reg_flt;
10976
10977 /* duplicate args */
10978 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10979 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010980 if (!conf->args)
10981 goto error;
10982 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010983 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010984 if (!conf->args[pos])
10985 goto error;
10986 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010987 conf->args[pos] = NULL;
10988 *cur_arg += pos + 1;
10989
Christopher Fauletc86bb872021-08-13 08:33:57 +020010990 if (flt_id) {
10991 fconf->id = strdup(flt_id);
10992 if (!fconf->id)
10993 goto error;
10994 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010995 fconf->flags = flt_flags;
10996 fconf->conf = conf;
10997 fconf->ops = hlua_flt_ops;
10998
10999 lua_settop(L, 0);
11000 return 0;
11001
11002 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020011003 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011004 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011005 if (conf && conf->args) {
11006 for (pos = 0; conf->args[pos]; pos++)
11007 free(conf->args[pos]);
11008 free(conf->args);
11009 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020011010 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020011011 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011012 lua_settop(L, 0);
11013 return -1;
11014}
11015
Christopher Fauletc404f112020-02-26 15:03:09 +010011016__LJMP static int hlua_register_data_filter(lua_State *L)
11017{
11018 struct filter *filter;
11019 struct channel *chn;
11020
11021 MAY_LJMP(check_args(L, 2, "register_data_filter"));
11022 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11023 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11024
11025 lua_getfield(L, 1, "__filter");
11026 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11027 filter = lua_touserdata (L, -1);
11028 lua_pop(L, 1);
11029
11030 register_data_filter(chn_strm(chn), chn, filter);
11031 return 1;
11032}
11033
11034__LJMP static int hlua_unregister_data_filter(lua_State *L)
11035{
11036 struct filter *filter;
11037 struct channel *chn;
11038
11039 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11040 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11041 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11042
11043 lua_getfield(L, 1, "__filter");
11044 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11045 filter = lua_touserdata (L, -1);
11046 lua_pop(L, 1);
11047
11048 unregister_data_filter(chn_strm(chn), chn, filter);
11049 return 1;
11050}
11051
Christopher Faulet69c581a2021-05-31 08:54:04 +020011052/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011053 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011054 * parse configuration arguments.
11055 */
11056__LJMP static int hlua_register_filter(lua_State *L)
11057{
11058 struct buffer *trash;
11059 struct flt_kw_list *fkl;
11060 struct flt_kw *fkw;
11061 const char *name;
11062 struct hlua_reg_filter *reg_flt= NULL;
11063 int flt_ref, fun_ref;
11064 int len;
11065
11066 MAY_LJMP(check_args(L, 3, "register_filter"));
11067
11068 /* First argument : filter name. */
11069 name = MAY_LJMP(luaL_checkstring(L, 1));
11070
11071 /* Second argument : The filter class */
11072 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11073
11074 /* Third argument : lua function. */
11075 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11076
11077 trash = get_trash_chunk();
11078 chunk_printf(trash, "lua.%s", name);
11079 fkw = flt_find_kw(trash->area);
11080 if (fkw != NULL) {
11081 reg_flt = fkw->private;
11082 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11083 ha_warning("Trying to register filter 'lua.%s' more than once. "
11084 "This will become a hard error in version 2.5.\n", name);
11085 }
11086 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11087 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11088 return 0;
11089 }
11090
11091 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11092 if (!fkl)
11093 goto alloc_error;
11094 fkl->scope = "HLUA";
11095
11096 reg_flt = new_hlua_reg_filter(name);
11097 if (!reg_flt)
11098 goto alloc_error;
11099
11100 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11101 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11102
11103 /* The filter keyword */
11104 len = strlen("lua.") + strlen(name) + 1;
11105 fkl->kw[0].kw = calloc(1, len);
11106 if (!fkl->kw[0].kw)
11107 goto alloc_error;
11108
11109 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11110
11111 fkl->kw[0].parse = hlua_filter_parse_fct;
11112 fkl->kw[0].private = reg_flt;
11113 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11114
11115 /* Register this new filter */
11116 flt_register_keywords(fkl);
11117
11118 return 0;
11119
11120 alloc_error:
11121 release_hlua_reg_filter(reg_flt);
11122 ha_free(&fkl);
11123 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11124 return 0; /* Never reached */
11125}
11126
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011127static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011128 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011129 char **err, unsigned int *timeout)
11130{
11131 const char *error;
11132
11133 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011134 if (error == PARSE_TIME_OVER) {
11135 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11136 args[1], args[0]);
11137 return -1;
11138 }
11139 else if (error == PARSE_TIME_UNDER) {
11140 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11141 args[1], args[0]);
11142 return -1;
11143 }
11144 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011145 memprintf(err, "%s: invalid timeout", args[0]);
11146 return -1;
11147 }
11148 return 0;
11149}
11150
11151static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011152 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011153 char **err)
11154{
11155 return hlua_read_timeout(args, section_type, curpx, defpx,
11156 file, line, err, &hlua_timeout_session);
11157}
11158
11159static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011160 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011161 char **err)
11162{
11163 return hlua_read_timeout(args, section_type, curpx, defpx,
11164 file, line, err, &hlua_timeout_task);
11165}
11166
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011167static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011168 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011169 char **err)
11170{
11171 return hlua_read_timeout(args, section_type, curpx, defpx,
11172 file, line, err, &hlua_timeout_applet);
11173}
11174
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011175static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011176 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011177 char **err)
11178{
11179 char *error;
11180
11181 hlua_nb_instruction = strtoll(args[1], &error, 10);
11182 if (*error != '\0') {
11183 memprintf(err, "%s: invalid number", args[0]);
11184 return -1;
11185 }
11186 return 0;
11187}
11188
Willy Tarreau32f61e22015-03-18 17:54:59 +010011189static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011190 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011191 char **err)
11192{
11193 char *error;
11194
11195 if (*(args[1]) == 0) {
11196 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11197 return -1;
11198 }
11199 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11200 if (*error != '\0') {
11201 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11202 return -1;
11203 }
11204 return 0;
11205}
11206
11207
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011208/* This function is called by the main configuration key "lua-load". It loads and
11209 * execute an lua file during the parsing of the HAProxy configuration file. It is
11210 * the main lua entry point.
11211 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011212 * This function runs with the HAProxy keywords API. It returns -1 if an error
11213 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011214 *
11215 * In some error case, LUA set an error message in top of the stack. This function
11216 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011217 *
11218 * This function can fail with an abort() due to an Lua critical error.
11219 * We are in the configuration parsing process of HAProxy, this abort() is
11220 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011221 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011222static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011223{
11224 int error;
11225
11226 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011227 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011228 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011229 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11230 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011231 return -1;
11232 }
11233
11234 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011235 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011236 switch (error) {
11237 case LUA_OK:
11238 break;
11239 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011240 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11241 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011242 return -1;
11243 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011244 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011245 return -1;
11246 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011247 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11248 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011249 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011250#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011251 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011252 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11253 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011254 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011255#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011256 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011257 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11258 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011259 return -1;
11260 }
11261
11262 return 0;
11263}
11264
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011265static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011266 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011267 char **err)
11268{
11269 if (*(args[1]) == 0) {
11270 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11271 return -1;
11272 }
11273
Thierry Fournier59f11be2020-11-29 00:37:41 +010011274 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011275 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011276 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011277 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011278}
11279
Thierry Fournier59f11be2020-11-29 00:37:41 +010011280static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011281 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011282 char **err)
11283{
11284 int len;
11285
11286 if (*(args[1]) == 0) {
11287 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11288 return -1;
11289 }
11290
11291 if (per_thread_load == NULL) {
11292 /* allocate the first entry large enough to store the final NULL */
11293 per_thread_load = calloc(1, sizeof(*per_thread_load));
11294 if (per_thread_load == NULL) {
11295 memprintf(err, "out of memory error");
11296 return -1;
11297 }
11298 }
11299
11300 /* count used entries */
11301 for (len = 0; per_thread_load[len] != NULL; len++)
11302 ;
11303
11304 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11305 if (per_thread_load == NULL) {
11306 memprintf(err, "out of memory error");
11307 return -1;
11308 }
11309
11310 per_thread_load[len] = strdup(args[1]);
11311 per_thread_load[len + 1] = NULL;
11312
11313 if (per_thread_load[len] == NULL) {
11314 memprintf(err, "out of memory error");
11315 return -1;
11316 }
11317
11318 /* loading for thread 1 only */
11319 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011320 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011321 return hlua_load_state(args[1], hlua_states[1], err);
11322}
11323
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011324/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11325 * in the given <ctx>.
11326 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011327static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011328{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011329 lua_getglobal(L, "package"); /* push package variable */
11330 lua_pushstring(L, path); /* push given path */
11331 lua_pushstring(L, ";"); /* push semicolon */
11332 lua_getfield(L, -3, type); /* push old path */
11333 lua_concat(L, 3); /* concatenate to new path */
11334 lua_setfield(L, -2, type); /* store new path */
11335 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011336
11337 return 0;
11338}
11339
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011340static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011341 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011342 char **err)
11343{
11344 char *path;
11345 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011346 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011347 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011348
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011349 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011350 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011351 }
11352
11353 if (!(*args[1])) {
11354 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011355 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011356 }
11357 path = args[1];
11358
11359 if (*args[2]) {
11360 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11361 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011362 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011363 }
11364 type = args[2];
11365 }
11366
Thierry Fournier59f11be2020-11-29 00:37:41 +010011367 p = calloc(1, sizeof(*p));
11368 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011369 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011370 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011371 }
11372 p->path = strdup(path);
11373 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011374 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011375 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011376 }
11377 p->type = strdup(type);
11378 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011379 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011380 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011381 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011382 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011383
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011384 /* Handle the global state and the per-thread state for the first
11385 * thread. The remaining threads will be initialized based on
11386 * prepend_path_list.
11387 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011388 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011389 lua_State *L = hlua_states[i];
11390 const char *error;
11391
11392 if (setjmp(safe_ljmp_env) != 0) {
11393 lua_atpanic(L, hlua_panic_safe);
11394 if (lua_type(L, -1) == LUA_TSTRING)
11395 error = lua_tostring(L, -1);
11396 else
11397 error = "critical error";
11398 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11399 exit(1);
11400 } else {
11401 lua_atpanic(L, hlua_panic_ljmp);
11402 }
11403
11404 hlua_prepend_path(L, type, path);
11405
11406 lua_atpanic(L, hlua_panic_safe);
11407 }
11408
Thierry Fournier59f11be2020-11-29 00:37:41 +010011409 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011410
11411err2:
11412 free(p->type);
11413 free(p->path);
11414err:
11415 free(p);
11416 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011417}
11418
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011419/* configuration keywords declaration */
11420static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011421 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011422 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011423 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011424 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11425 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011426 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011427 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011428 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011429 { 0, NULL, NULL },
11430}};
11431
Willy Tarreau0108d902018-11-25 19:14:37 +010011432INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11433
William Lallemand52139182022-03-30 15:05:42 +020011434#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011435
William Lallemand30fcca12022-03-30 12:03:12 +020011436/*
11437 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11438 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11439 * difference is that the yield in lua and for the CLI is not handled the same
11440 * way.
11441 */
11442__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11443{
11444 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11445 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11446 struct ckch_inst *ckchi = *lua_ckchi;
11447 struct ckch_store *old_ckchs = lua_ckchs[0];
11448 struct ckch_store *new_ckchs = lua_ckchs[1];
11449 struct hlua *hlua;
11450 char *err = NULL;
11451 int y = 1;
11452
11453 hlua = hlua_gethlua(L);
11454
11455 /* get the first ckchi to copy */
11456 if (ckchi == NULL)
11457 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11458
11459 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11460 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11461 struct ckch_inst *new_inst;
11462
11463 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11464 if (y % 10 == 0) {
11465
11466 *lua_ckchi = ckchi;
11467
11468 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11469 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11470 }
11471
11472 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11473 goto error;
11474
11475 /* link the new ckch_inst to the duplicate */
11476 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11477 y++;
11478 }
11479
11480 /* The generation is finished, we can insert everything */
11481 ckch_store_replace(old_ckchs, new_ckchs);
11482
11483 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11484
11485 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11486
11487 return 0;
11488
11489error:
11490 ckch_store_free(new_ckchs);
11491 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11492 WILL_LJMP(luaL_error(L, "%s", err));
11493 free(err);
11494
11495 return 0;
11496}
11497
11498/*
11499 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11500 * from the table in parameter.
11501 *
11502 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11503 * means it does not need to have a transaction since everything is done in the
11504 * same function.
11505 *
11506 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11507 *
11508 */
11509__LJMP static int hlua_ckch_set(lua_State *L)
11510{
11511 struct hlua *hlua;
11512 struct ckch_inst **lua_ckchi;
11513 struct ckch_store **lua_ckchs;
11514 struct ckch_store *old_ckchs = NULL;
11515 struct ckch_store *new_ckchs = NULL;
11516 int errcode = 0;
11517 char *err = NULL;
11518 struct cert_exts *cert_ext = NULL;
11519 char *filename;
11520 struct cert_key_and_chain *ckch;
11521 int ret;
11522
11523 if (lua_type(L, -1) != LUA_TTABLE)
11524 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11525
11526 hlua = hlua_gethlua(L);
11527
11528 /* FIXME: this should not return an error but should come back later */
11529 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11530 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11531
11532 ret = lua_getfield(L, -1, "filename");
11533 if (ret != LUA_TSTRING) {
11534 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11535 errcode |= ERR_ALERT | ERR_FATAL;
11536 goto end;
11537 }
11538 filename = (char *)lua_tostring(L, -1);
11539
11540
11541 /* look for the filename in the tree */
11542 old_ckchs = ckchs_lookup(filename);
11543 if (!old_ckchs) {
11544 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11545 errcode |= ERR_ALERT | ERR_FATAL;
11546 goto end;
11547 }
11548 /* TODO: handle extra_files_noext */
11549
11550 new_ckchs = ckchs_dup(old_ckchs);
11551 if (!new_ckchs) {
11552 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11553 errcode |= ERR_ALERT | ERR_FATAL;
11554 goto end;
11555 }
11556
11557 ckch = new_ckchs->ckch;
11558
11559 /* loop on the field in the table, which have the same name as the
11560 * possible extensions of files */
11561 lua_pushnil(L);
11562 while (lua_next(L, 1)) {
11563 int i;
11564 const char *field = lua_tostring(L, -2);
11565 char *payload = (char *)lua_tostring(L, -1);
11566
11567 if (!field || strcmp(field, "filename") == 0) {
11568 lua_pop(L, 1);
11569 continue;
11570 }
11571
11572 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11573 if (strcmp(field, cert_exts[i].ext) == 0) {
11574 cert_ext = &cert_exts[i];
11575 break;
11576 }
11577 }
11578
11579 /* this is the default type, the field is not supported */
11580 if (cert_ext == NULL) {
11581 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11582 errcode |= ERR_ALERT | ERR_FATAL;
11583 goto end;
11584 }
11585
11586 /* appply the change on the duplicate */
11587 if (cert_exts->load(filename, payload, ckch, &err) != 0) {
11588 memprintf(&err, "%sCan't load the payload\n", err ? err : "");
11589 errcode |= ERR_ALERT | ERR_FATAL;
11590 goto end;
11591 }
11592 lua_pop(L, 1);
11593 }
11594
11595 /* store the pointers on the lua stack */
11596 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11597 lua_ckchs[0] = old_ckchs;
11598 lua_ckchs[1] = new_ckchs;
11599 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11600 *lua_ckchi = NULL;
11601
11602 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11603 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11604
11605end:
11606 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11607
11608 if (errcode & ERR_CODE) {
11609 ckch_store_free(new_ckchs);
11610 WILL_LJMP(luaL_error(L, "%s", err));
11611 }
11612 free(err);
11613
11614 return 0;
11615}
11616
William Lallemand52139182022-03-30 15:05:42 +020011617#else
11618
11619__LJMP static int hlua_ckch_set(lua_State *L)
11620{
11621 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11622
11623 return 0;
11624}
11625#endif /* ! USE_OPENSSL */
11626
11627
11628
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011629/* This function can fail with an abort() due to an Lua critical error.
11630 * We are in the initialisation process of HAProxy, this abort() is
11631 * tolerated.
11632 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011633int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011634{
11635 struct hlua_init_function *init;
11636 const char *msg;
11637 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011638 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011639 const char *kind;
11640 const char *trace;
11641 int return_status = 1;
11642#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11643 int nres;
11644#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011645
Willy Tarreaucdb53462020-12-02 12:12:00 +010011646 /* disable memory limit checks if limit is not set */
11647 if (!hlua_global_allocator.limit)
11648 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11649
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011650 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011651 if (setjmp(safe_ljmp_env) != 0) {
11652 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011653 if (lua_type(L, -1) == LUA_TSTRING)
11654 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011655 else
11656 error = "critical error";
11657 fprintf(stderr, "Lua post-init: %s.\n", error);
11658 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011659 } else {
11660 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011661 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011662
Thierry Fournierb8cef172020-11-28 15:37:17 +010011663 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011664
Thierry Fournierc7492592020-11-28 23:57:24 +010011665 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011666 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011667
11668#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011669 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011670#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011671 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011672#endif
11673 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011674 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011675
11676 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011677 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011678 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011679
11680 case LUA_ERRERR:
11681 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011682 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011683 case LUA_ERRRUN:
11684 if (!kind)
11685 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011686 msg = lua_tostring(L, -1);
11687 lua_settop(L, 0); /* Empty the stack. */
11688 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011689 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011690 if (msg)
11691 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11692 else
11693 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11694 return_status = 0;
11695 break;
11696
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011697 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011698 /* Unknown error */
11699 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011700 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011701 case LUA_YIELD:
11702 /* yield is not configured at this step, this state doesn't happen */
11703 if (!kind)
11704 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011705 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011706 case LUA_ERRMEM:
11707 if (!kind)
11708 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011709 lua_settop(L, 0);
11710 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011711 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011712 ha_alert("Lua init: %s: %s\n", kind, trace);
11713 return_status = 0;
11714 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011715 }
Thierry Fournier670db242020-11-28 10:49:59 +010011716 if (!return_status)
11717 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011718 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011719
11720 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011721 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011722}
11723
Thierry Fournierb8cef172020-11-28 15:37:17 +010011724int hlua_post_init()
11725{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011726 int ret;
11727 int i;
11728 int errors;
11729 char *err = NULL;
11730 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011731 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011732
Willy Tarreaub1310492021-08-30 09:35:18 +020011733#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011734 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011735 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011736 int saved_used_backed = global.ssl_used_backend;
11737 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011738 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011739 global.ssl_used_backend = saved_used_backed;
11740 }
11741#endif
11742
Thierry Fournierc7492592020-11-28 23:57:24 +010011743 /* Perform post init of common thread */
11744 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011745 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011746 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11747 if (ret == 0)
11748 return 0;
11749
11750 /* init remaining lua states and load files */
11751 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11752
11753 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011754 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011755
11756 /* Init lua state */
11757 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11758
11759 /* Load lua files */
11760 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11761 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11762 if (ret != 0) {
11763 ha_alert("Lua init: %s\n", err);
11764 return 0;
11765 }
11766 }
11767 }
11768
11769 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011770 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011771
11772 /* Execute post init for all states */
11773 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11774
11775 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011776 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011777
11778 /* run post init */
11779 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11780 if (ret == 0)
11781 return 0;
11782 }
11783
11784 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011785 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011786
11787 /* control functions registering. Each function must have:
11788 * - only the function_ref[0] set positive and all other to -1
11789 * - only the function_ref[0] set to -1 and all other positive
11790 * This ensure a same reference is not used both in shared
11791 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011792 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011793 * complicated to found for the end user.
11794 */
11795 errors = 0;
11796 list_for_each_entry(fcn, &referenced_functions, l) {
11797 ret = 0;
11798 for (i = 1; i < global.nbthread + 1; i++) {
11799 if (fcn->function_ref[i] == -1)
11800 ret--;
11801 else
11802 ret++;
11803 }
11804 if (abs(ret) != global.nbthread) {
11805 ha_alert("Lua function '%s' is not referenced in all thread. "
11806 "Expect function in all thread or in none thread.\n", fcn->name);
11807 errors++;
11808 continue;
11809 }
11810
11811 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011812 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11813 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011814 "exclusive.\n", fcn->name);
11815 errors++;
11816 }
11817 }
11818
Christopher Faulet69c581a2021-05-31 08:54:04 +020011819 /* Do the same with registered filters */
11820 list_for_each_entry(reg_flt, &referenced_filters, l) {
11821 ret = 0;
11822 for (i = 1; i < global.nbthread + 1; i++) {
11823 if (reg_flt->flt_ref[i] == -1)
11824 ret--;
11825 else
11826 ret++;
11827 }
11828 if (abs(ret) != global.nbthread) {
11829 ha_alert("Lua filter '%s' is not referenced in all thread. "
11830 "Expect function in all thread or in none thread.\n", reg_flt->name);
11831 errors++;
11832 continue;
11833 }
11834
11835 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11836 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11837 "and per-thread Lua context (through lua-load-per-thread). these two context "
11838 "exclusive.\n", fcn->name);
11839 errors++;
11840 }
11841 }
11842
11843
Thierry Fournier59f11be2020-11-29 00:37:41 +010011844 if (errors > 0)
11845 return 0;
11846
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011847 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011848 * -1 in order to have probably a segfault if someone use it
11849 */
11850 hlua_state_id = -1;
11851
11852 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011853}
11854
Willy Tarreau32f61e22015-03-18 17:54:59 +010011855/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11856 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11857 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011858 * allocation. <nsize> is the requested new size. A new allocation is
11859 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011860 * zero. This one verifies that the limits are respected but is optimized
11861 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011862 *
11863 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11864 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11865 * that and will simply allocate zero as if it were the result of malloc(0),
11866 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11867 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011868 */
11869static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11870{
11871 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011872 size_t limit, old, new;
11873
11874 /* a limit of ~0 means unlimited and boot complete, so there's no need
11875 * for accounting anymore.
11876 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011877 if (likely(~zone->limit == 0)) {
11878 if (!nsize)
11879 ha_free(&ptr);
11880 else
11881 ptr = realloc(ptr, nsize);
11882 return ptr;
11883 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011884
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011885 if (!ptr)
11886 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011887
Willy Tarreaucdb53462020-12-02 12:12:00 +010011888 /* enforce strict limits across all threads */
11889 limit = zone->limit;
11890 old = _HA_ATOMIC_LOAD(&zone->allocated);
11891 do {
11892 new = old + nsize - osize;
11893 if (unlikely(nsize && limit && new > limit))
11894 return NULL;
11895 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011896
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011897 if (!nsize)
11898 ha_free(&ptr);
11899 else
11900 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011901
11902 if (unlikely(!ptr && nsize)) // failed
11903 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11904
11905 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011906 return ptr;
11907}
11908
Thierry Fournierecb83c22020-11-28 15:49:44 +010011909/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011910 * We are in the initialisation process of HAProxy, this abort() is
11911 * tolerated.
11912 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011913lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011914{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011915 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011916 int idx;
11917 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011918 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011919 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011920 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011921 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011922 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011923 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011924
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011925 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011926 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011927
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011928 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011929 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011930 *context = NULL;
11931
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011932 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011933 * the Lua function can fail with an abort. We are in the initialisation
11934 * process of HAProxy, this abort() is tolerated.
11935 */
11936
Thierry Fournier3c539322020-11-28 16:05:05 +010011937 /* Call post initialisation function in safe environment. */
11938 if (setjmp(safe_ljmp_env) != 0) {
11939 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011940 if (lua_type(L, -1) == LUA_TSTRING)
11941 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011942 else
11943 error_msg = "critical error";
11944 fprintf(stderr, "Lua init: %s.\n", error_msg);
11945 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011946 } else {
11947 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011948 }
11949
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011950 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011951 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011952#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11953#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11954#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011955 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011956#endif
11957#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011958 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011959#endif
11960#undef HLUA_PREPEND_PATH_TOSTRING
11961#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011962
Thierry Fournier59f11be2020-11-29 00:37:41 +010011963 /* Apply configured prepend path */
11964 list_for_each_entry(pp, &prepend_path_list, l)
11965 hlua_prepend_path(L, pp->type, pp->path);
11966
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011967 /*
11968 *
11969 * Create "core" object.
11970 *
11971 */
11972
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011973 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011974 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011975
Thierry Fournierecb83c22020-11-28 15:49:44 +010011976 /* set the thread id */
11977 hlua_class_const_int(L, "thread", thread_num);
11978
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011979 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011980 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011981 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011982
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011983 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011984 hlua_class_function(L, "register_init", hlua_register_init);
11985 hlua_class_function(L, "register_task", hlua_register_task);
11986 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11987 hlua_class_function(L, "register_converters", hlua_register_converters);
11988 hlua_class_function(L, "register_action", hlua_register_action);
11989 hlua_class_function(L, "register_service", hlua_register_service);
11990 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011991 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011992 hlua_class_function(L, "yield", hlua_yield);
11993 hlua_class_function(L, "set_nice", hlua_set_nice);
11994 hlua_class_function(L, "sleep", hlua_sleep);
11995 hlua_class_function(L, "msleep", hlua_msleep);
11996 hlua_class_function(L, "add_acl", hlua_add_acl);
11997 hlua_class_function(L, "del_acl", hlua_del_acl);
11998 hlua_class_function(L, "set_map", hlua_set_map);
11999 hlua_class_function(L, "del_map", hlua_del_map);
12000 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020012001 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012002 hlua_class_function(L, "log", hlua_log);
12003 hlua_class_function(L, "Debug", hlua_log_debug);
12004 hlua_class_function(L, "Info", hlua_log_info);
12005 hlua_class_function(L, "Warning", hlua_log_warning);
12006 hlua_class_function(L, "Alert", hlua_log_alert);
12007 hlua_class_function(L, "done", hlua_done);
12008 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010012009
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012010 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012011
12012 /*
12013 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012014 * Create "act" object.
12015 *
12016 */
12017
12018 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012019 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012020
12021 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012022 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
12023 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12024 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12025 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12026 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12027 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12028 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12029 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012030
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012031 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012032
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012033 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012034
12035 /*
12036 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012037 * Create "Filter" object.
12038 *
12039 */
12040
12041 /* This table entry is the object "filter" base. */
12042 lua_newtable(L);
12043
12044 /* push flags and constants */
12045 hlua_class_const_int(L, "CONTINUE", 1);
12046 hlua_class_const_int(L, "WAIT", 0);
12047 hlua_class_const_int(L, "ERROR", -1);
12048
12049 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12050
Christopher Fauletc404f112020-02-26 15:03:09 +010012051 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12052 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12053 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12054
Christopher Faulet69c581a2021-05-31 08:54:04 +020012055 lua_setglobal(L, "filter");
12056
12057 /*
12058 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012059 * Register class Map
12060 *
12061 */
12062
12063 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012064 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012065
12066 /* register pattern types. */
12067 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012068 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012069 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012070 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012071 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012072 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012073
12074 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012075 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012076
12077 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012078 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012079
Ilya Shipitsind4259502020-04-08 01:07:56 +050012080 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012081 lua_pushstring(L, "__index");
12082 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012083
12084 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012085 hlua_class_function(L, "lookup", hlua_map_lookup);
12086 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012087
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012088 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012089
Thierry Fournier45e78d72016-02-19 18:34:46 +010012090 /* Register previous table in the registry with reference and named entry.
12091 * The function hlua_register_metatable() pops the stack, so we
12092 * previously create a copy of the table.
12093 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012094 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12095 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012096
12097 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012098 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012099
12100 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012101 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012102
12103 /*
12104 *
William Lallemand30fcca12022-03-30 12:03:12 +020012105 * Register "CertCache" class
12106 *
12107 */
12108
12109 /* Create and fill the metatable. */
12110 lua_newtable(L);
12111 /* Register */
12112 hlua_class_function(L, "set", hlua_ckch_set);
12113 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12114
12115 /*
12116 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012117 * Register class Channel
12118 *
12119 */
12120
12121 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012122 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012123
Ilya Shipitsind4259502020-04-08 01:07:56 +050012124 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012125 lua_pushstring(L, "__index");
12126 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012127
12128 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012129 hlua_class_function(L, "data", hlua_channel_get_data);
12130 hlua_class_function(L, "line", hlua_channel_get_line);
12131 hlua_class_function(L, "set", hlua_channel_set_data);
12132 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012133 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012134 hlua_class_function(L, "prepend", hlua_channel_prepend);
12135 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012136 hlua_class_function(L, "send", hlua_channel_send);
12137 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012138 hlua_class_function(L, "input", hlua_channel_get_in_len);
12139 hlua_class_function(L, "output", hlua_channel_get_out_len);
12140 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012141 hlua_class_function(L, "is_full", hlua_channel_is_full);
12142 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012143
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012144 /* Deprecated API */
12145 hlua_class_function(L, "get", hlua_channel_get);
12146 hlua_class_function(L, "dup", hlua_channel_dup);
12147 hlua_class_function(L, "getline", hlua_channel_getline);
12148 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12149 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12150
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012151 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012152
12153 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012154 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012155
12156 /*
12157 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012158 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012159 *
12160 */
12161
12162 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012163 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012164
Ilya Shipitsind4259502020-04-08 01:07:56 +050012165 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012166 lua_pushstring(L, "__index");
12167 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012168
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012169 /* Browse existing fetches and create the associated
12170 * object method.
12171 */
12172 sf = NULL;
12173 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012174 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12175 * by an underscore.
12176 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012177 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012178 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012179 if (*p == '.' || *p == '-' || *p == '+')
12180 *p = '_';
12181
12182 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012183 lua_pushstring(L, trash.area);
12184 lua_pushlightuserdata(L, sf);
12185 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12186 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012187 }
12188
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012189 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012190
12191 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012192 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012193
12194 /*
12195 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012196 * Register class Converters
12197 *
12198 */
12199
12200 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012201 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012202
12203 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012204 lua_pushstring(L, "__index");
12205 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012206
12207 /* Browse existing converters and create the associated
12208 * object method.
12209 */
12210 sc = NULL;
12211 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012212 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12213 * by an underscore.
12214 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012215 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012216 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012217 if (*p == '.' || *p == '-' || *p == '+')
12218 *p = '_';
12219
12220 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012221 lua_pushstring(L, trash.area);
12222 lua_pushlightuserdata(L, sc);
12223 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12224 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012225 }
12226
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012227 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012228
12229 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012230 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012231
12232 /*
12233 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012234 * Register class HTTP
12235 *
12236 */
12237
12238 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012239 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012240
Ilya Shipitsind4259502020-04-08 01:07:56 +050012241 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012242 lua_pushstring(L, "__index");
12243 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012244
12245 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012246 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12247 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12248 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12249 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12250 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12251 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12252 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12253 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12254 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12255 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012256
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012257 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12258 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12259 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12260 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12261 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12262 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12263 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012264
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012265 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012266
12267 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012268 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012269
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012270 /*
12271 *
12272 * Register class HTTPMessage
12273 *
12274 */
12275
12276 /* Create and fill the metatable. */
12277 lua_newtable(L);
12278
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012279 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012280 lua_pushstring(L, "__index");
12281 lua_newtable(L);
12282
12283 /* Register Lua functions. */
12284 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12285 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12286 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12287 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12288 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12289 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12290 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12291 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12292 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12293 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12294 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12295 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12296 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12297 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12298 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12299 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12300 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12301 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12302
12303 hlua_class_function(L, "body", hlua_http_msg_get_body);
12304 hlua_class_function(L, "set", hlua_http_msg_set_data);
12305 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12306 hlua_class_function(L, "append", hlua_http_msg_append);
12307 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12308 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12309 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12310 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12311
12312 hlua_class_function(L, "send", hlua_http_msg_send);
12313 hlua_class_function(L, "forward", hlua_http_msg_forward);
12314
12315 lua_rawset(L, -3);
12316
12317 /* Register previous table in the registry with reference and named entry. */
12318 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012319
12320 /*
12321 *
12322 * Register class HTTPClient
12323 *
12324 */
12325
12326 /* Create and fill the metatable. */
12327 lua_newtable(L);
12328 lua_pushstring(L, "__index");
12329 lua_newtable(L);
12330 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012331 hlua_class_function(L, "head", hlua_httpclient_head);
12332 hlua_class_function(L, "put", hlua_httpclient_put);
12333 hlua_class_function(L, "post", hlua_httpclient_post);
12334 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012335 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012336 /* Register the garbage collector entry. */
12337 lua_pushstring(L, "__gc");
12338 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12339 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12340
William Lallemand3956c4e2021-09-21 16:25:15 +020012341
12342
12343 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012344 /*
12345 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012346 * Register class AppletTCP
12347 *
12348 */
12349
12350 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012351 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012352
Ilya Shipitsind4259502020-04-08 01:07:56 +050012353 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012354 lua_pushstring(L, "__index");
12355 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012356
12357 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012358 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12359 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12360 hlua_class_function(L, "send", hlua_applet_tcp_send);
12361 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12362 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12363 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12364 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12365 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012366
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012367 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012368
12369 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012370 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012371
12372 /*
12373 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012374 * Register class AppletHTTP
12375 *
12376 */
12377
12378 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012379 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012380
Ilya Shipitsind4259502020-04-08 01:07:56 +050012381 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012382 lua_pushstring(L, "__index");
12383 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012384
12385 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012386 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12387 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12388 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12389 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12390 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12391 hlua_class_function(L, "getline", hlua_applet_http_getline);
12392 hlua_class_function(L, "receive", hlua_applet_http_recv);
12393 hlua_class_function(L, "send", hlua_applet_http_send);
12394 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12395 hlua_class_function(L, "set_status", hlua_applet_http_status);
12396 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012397
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012398 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012399
12400 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012401 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012402
12403 /*
12404 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012405 * Register class TXN
12406 *
12407 */
12408
12409 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012410 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012411
Ilya Shipitsind4259502020-04-08 01:07:56 +050012412 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012413 lua_pushstring(L, "__index");
12414 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012415
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012416 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012417 hlua_class_function(L, "set_priv", hlua_set_priv);
12418 hlua_class_function(L, "get_priv", hlua_get_priv);
12419 hlua_class_function(L, "set_var", hlua_set_var);
12420 hlua_class_function(L, "unset_var", hlua_unset_var);
12421 hlua_class_function(L, "get_var", hlua_get_var);
12422 hlua_class_function(L, "done", hlua_txn_done);
12423 hlua_class_function(L, "reply", hlua_txn_reply_new);
12424 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12425 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12426 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12427 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12428 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12429 hlua_class_function(L, "deflog", hlua_txn_deflog);
12430 hlua_class_function(L, "log", hlua_txn_log);
12431 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12432 hlua_class_function(L, "Info", hlua_txn_log_info);
12433 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12434 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012435
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012436 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012437
12438 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012439 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012440
12441 /*
12442 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012443 * Register class reply
12444 *
12445 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012446 lua_newtable(L);
12447 lua_pushstring(L, "__index");
12448 lua_newtable(L);
12449 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12450 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12451 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12452 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12453 lua_settable(L, -3); /* Sets the __index entry. */
12454 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012455
12456
12457 /*
12458 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012459 * Register class Socket
12460 *
12461 */
12462
12463 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012464 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012465
Ilya Shipitsind4259502020-04-08 01:07:56 +050012466 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012467 lua_pushstring(L, "__index");
12468 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012469
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012470#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012471 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012472#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012473 hlua_class_function(L, "connect", hlua_socket_connect);
12474 hlua_class_function(L, "send", hlua_socket_send);
12475 hlua_class_function(L, "receive", hlua_socket_receive);
12476 hlua_class_function(L, "close", hlua_socket_close);
12477 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12478 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12479 hlua_class_function(L, "setoption", hlua_socket_setoption);
12480 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012481
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012482 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012483
12484 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012485 lua_pushstring(L, "__gc");
12486 lua_pushcclosure(L, hlua_socket_gc, 0);
12487 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012488
12489 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012490 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012491
Thierry Fournieraafc7772020-12-04 11:47:47 +010012492 lua_atpanic(L, hlua_panic_safe);
12493
12494 return L;
12495}
12496
12497void hlua_init(void) {
12498 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012499 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012500#ifdef USE_OPENSSL
12501 struct srv_kw *kw;
12502 int tmp_error;
12503 char *error;
12504 char *args[] = { /* SSL client configuration. */
12505 "ssl",
12506 "verify",
12507 "none",
12508 NULL
12509 };
12510#endif
12511
12512 /* Init post init function list head */
12513 for (i = 0; i < MAX_THREADS + 1; i++)
12514 LIST_INIT(&hlua_init_functions[i]);
12515
12516 /* Init state for common/shared lua parts */
12517 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012518 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012519 hlua_states[0] = hlua_init_state(0);
12520
12521 /* Init state 1 for thread 0. We have at least one thread. */
12522 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012523 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012524 hlua_states[1] = hlua_init_state(1);
12525
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012526 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012527 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012528 if (!socket_proxy) {
12529 fprintf(stderr, "Lua init: %s\n", errmsg);
12530 exit(1);
12531 }
12532 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012533
12534 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012535 socket_tcp = new_server(socket_proxy);
12536 if (!socket_tcp) {
12537 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12538 exit(1);
12539 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012540
12541#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012542 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012543 socket_ssl = new_server(socket_proxy);
12544 if (!socket_ssl) {
12545 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12546 exit(1);
12547 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012548
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012549 socket_ssl->use_ssl = 1;
12550 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012551
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012552 for (i = 0; args[i] != NULL; i++) {
12553 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012554 /*
12555 *
12556 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012557 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012558 * features like client certificates and ssl_verify.
12559 *
12560 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012561 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012562 if (tmp_error != 0) {
12563 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12564 abort(); /* This must be never arrives because the command line
12565 not editable by the user. */
12566 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012567 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012568 }
12569 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012570#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012571
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012572}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012573
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012574static void hlua_deinit()
12575{
Willy Tarreau186f3762020-12-04 11:48:12 +010012576 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012577 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12578
12579 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12580 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012581
12582 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12583 if (hlua_states[thr])
12584 lua_close(hlua_states[thr]);
12585 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012586
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012587 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012588
Willy Tarreau0f143af2021-03-05 10:41:48 +010012589#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012590 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012591#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012592
12593 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012594}
12595
12596REGISTER_POST_DEINIT(hlua_deinit);
12597
Willy Tarreau80713382018-11-26 10:19:54 +010012598static void hlua_register_build_options(void)
12599{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012600 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012601
Willy Tarreaubb57d942016-12-21 19:04:56 +010012602 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12603 hap_register_build_opts(ptr, 1);
12604}
Willy Tarreau80713382018-11-26 10:19:54 +010012605
12606INITCALL0(STG_REGISTER, hlua_register_build_options);