blob: cc7a585965e5011cbc2a368dd3ce119f2edc5f20 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020037#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020038#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020039#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020040#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020041#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020042#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020043#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020044#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020045#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020046#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020047#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020048#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020049#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020050#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020051#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020052#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020053#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010054#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020055#include <haproxy/session.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020056#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020057#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020058#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020059#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020060#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020061#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020062#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020063#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/xref.h>
65
Thierry FOURNIER380d0932015-01-23 14:27:52 +010066
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010067/* Lua uses longjmp to perform yield or throwing errors. This
68 * macro is used only for identifying the function that can
69 * not return because a longjmp is executed.
70 * __LJMP marks a prototype of hlua file that can use longjmp.
71 * WILL_LJMP() marks an lua function that will use longjmp.
72 * MAY_LJMP() marks an lua function that may use longjmp.
73 */
74#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020075#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010076#define MAY_LJMP(func) func
77
Thierry FOURNIERbabae282015-09-17 11:36:37 +020078/* This couple of function executes securely some Lua calls outside of
79 * the lua runtime environment. Each Lua call can return a longjmp
80 * if it encounter a memory error.
81 *
82 * Lua documentation extract:
83 *
84 * If an error happens outside any protected environment, Lua calls
85 * a panic function (see lua_atpanic) and then calls abort, thus
86 * exiting the host application. Your panic function can avoid this
87 * exit by never returning (e.g., doing a long jump to your own
88 * recovery point outside Lua).
89 *
90 * The panic function runs as if it were a message handler (see
91 * §2.3); in particular, the error message is at the top of the
92 * stack. However, there is no guarantee about stack space. To push
93 * anything on the stack, the panic function must first check the
94 * available space (see §4.2).
95 *
96 * We must check all the Lua entry point. This includes:
97 * - The include/proto/hlua.h exported functions
98 * - the task wrapper function
99 * - The action wrapper function
100 * - The converters wrapper function
101 * - The sample-fetch wrapper functions
102 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500103 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800104 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200105 *
106 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
107 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
108 * because they must be exists in the program stack when the longjmp
109 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200110 *
111 * Note that the Lua processing is not really thread safe. It provides
112 * heavy system which consists to add our own lock function in the Lua
113 * code and recompile the library. This system will probably not accepted
114 * by maintainers of various distribs.
115 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500116 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200117 * quick looking on the Lua sources displays a lua_lock() a the start
118 * of function and a lua_unlock() at the end of the function. So I
119 * conclude that the Lua thread safe mode just perform a mutex around
120 * all execution. So I prefer to do this in the HAProxy code, it will be
121 * easier for distro maintainers.
122 *
123 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
124 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
125 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200126 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100127__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200128THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200130static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200131
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100132/* This is the chained list of struct hlua_function referenced
133 * for haproxy action, sample-fetches, converters, cli and
134 * applet bindings. It is used for a post-initialisation control.
135 */
136static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
137
Thierry Fournierc7492592020-11-28 23:57:24 +0100138/* This variable is used only during initialization to identify the Lua state
139 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
140 * states dedicated to each thread (in this case hlua_state_id==tid+1).
141 */
142static int hlua_state_id;
143
Thierry Fournier59f11be2020-11-29 00:37:41 +0100144/* This is a NULL-terminated list of lua file which are referenced to load per thread */
145static char **per_thread_load = NULL;
146
147lua_State *hlua_init_state(int thread_id);
148
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200149/* This function takes the Lua global lock. Keep this function's visibility
150 * global so that it can appear in stack dumps and performance profiles!
151 */
152void lua_take_global_lock()
153{
154 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
155}
156
157static inline void lua_drop_global_lock()
158{
159 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
160}
161
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100162#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200163 ({ \
164 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100165 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200166 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200167 if (setjmp(safe_ljmp_env) != 0) { \
168 lua_atpanic(__L, hlua_panic_safe); \
169 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100170 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200171 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200172 } else { \
173 lua_atpanic(__L, hlua_panic_ljmp); \
174 ret = 1; \
175 } \
176 ret; \
177 })
178
179/* If we are the last function catching Lua errors, we
180 * must reset the panic function.
181 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100182#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200183 do { \
184 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100185 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200186 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200187 } while(0)
188
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100189#define SET_SAFE_LJMP(__HLUA) \
190 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
191
192#define RESET_SAFE_LJMP(__HLUA) \
193 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100196 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100197
198#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200201/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200202#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100203/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200204#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200205/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100206#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100207#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200208
Thierry Fournierafc63e22020-11-28 17:06:51 +0100209/* The main Lua execution context. The 0 index is the
210 * common state shared by all threads.
211 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100212static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100213
Christopher Fauletc404f112020-02-26 15:03:09 +0100214#define HLUA_FLT_CB_FINAL 0x00000001
215#define HLUA_FLT_CB_RETVAL 0x00000002
216#define HLUA_FLT_CB_ARG_CHN 0x00000004
217#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
218
Christopher Faulet9f55a502020-02-25 15:21:02 +0100219#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
220
Christopher Faulet69c581a2021-05-31 08:54:04 +0200221struct hlua_reg_filter {
222 char *name;
223 int flt_ref[MAX_THREADS + 1];
224 int fun_ref[MAX_THREADS + 1];
225 struct list l;
226};
227
228struct hlua_flt_config {
229 struct hlua_reg_filter *reg;
230 int ref[MAX_THREADS + 1];
231 char **args;
232};
233
234struct hlua_flt_ctx {
235 int ref; /* ref to the filter lua object */
236 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
237 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
238 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
239 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
240};
241
242DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
243
Christopher Faulet9f55a502020-02-25 15:21:02 +0100244static int hlua_filter_from_payload(struct filter *filter);
245
Christopher Faulet69c581a2021-05-31 08:54:04 +0200246/* This is the chained list of struct hlua_flt referenced
247 * for haproxy filters. It is used for a post-initialisation control.
248 */
249static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
250
251
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100252/* This is the memory pool containing struct lua for applets
253 * (including cli).
254 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100255DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100256
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100257/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100258static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100259static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100260#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100261static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100262#endif
263
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100264/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100265struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100266
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100267/* The following variables contains the reference of the different
268 * Lua classes. These references are useful for identify metadata
269 * associated with an object.
270 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100271static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100272static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100273static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100274static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100275static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100276static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100277static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200278static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200279static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200280static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200281static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100282static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100283
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100284/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200285 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100286 * short timeout. Lua linked with tasks doesn't have a timeout
287 * because a task may remain alive during all the haproxy execution.
288 */
289static unsigned int hlua_timeout_session = 4000; /* session timeout. */
290static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200291static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100292
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100293/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
294 * it is used for preventing infinite loops.
295 *
296 * I test the scheer with an infinite loop containing one incrementation
297 * and one test. I run this loop between 10 seconds, I raise a ceil of
298 * 710M loops from one interrupt each 9000 instructions, so I fix the value
299 * to one interrupt each 10 000 instructions.
300 *
301 * configured | Number of
302 * instructions | loops executed
303 * between two | in milions
304 * forced yields |
305 * ---------------+---------------
306 * 10 | 160
307 * 500 | 670
308 * 1000 | 680
309 * 5000 | 700
310 * 7000 | 700
311 * 8000 | 700
312 * 9000 | 710 <- ceil
313 * 10000 | 710
314 * 100000 | 710
315 * 1000000 | 710
316 *
317 */
318static unsigned int hlua_nb_instruction = 10000;
319
Willy Tarreaucdb53462020-12-02 12:12:00 +0100320/* Descriptor for the memory allocation state. The limit is pre-initialised to
321 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
322 * is replaced with ~0 during post_init after everything was loaded. This way
323 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
324 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100325 */
326struct hlua_mem_allocator {
327 size_t allocated;
328 size_t limit;
329};
330
Willy Tarreaucdb53462020-12-02 12:12:00 +0100331static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100332
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100333/* These functions converts types between HAProxy internal args or
334 * sample and LUA types. Another function permits to check if the
335 * LUA stack contains arguments according with an required ARG_T
336 * format.
337 */
338static int hlua_arg2lua(lua_State *L, const struct arg *arg);
339static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100340__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100341 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100342static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100343static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100344static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
345
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100346__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200347
Thierry Fournier59f11be2020-11-29 00:37:41 +0100348struct prepend_path {
349 struct list l;
350 char *type;
351 char *path;
352};
353
354static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
355
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200356#define SEND_ERR(__be, __fmt, __args...) \
357 do { \
358 send_log(__be, LOG_ERR, __fmt, ## __args); \
359 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100360 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200361 } while (0)
362
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100363static inline struct hlua_function *new_hlua_function()
364{
365 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100366 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100367
368 fcn = calloc(1, sizeof(*fcn));
369 if (!fcn)
370 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200371 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100372 for (i = 0; i < MAX_THREADS + 1; i++)
373 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100374 return fcn;
375}
376
Christopher Fauletdda44442021-04-12 14:05:43 +0200377static inline void release_hlua_function(struct hlua_function *fcn)
378{
379 if (!fcn)
380 return;
381 if (fcn->name)
382 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200383 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200384 ha_free(&fcn);
385}
386
Thierry Fournierc7492592020-11-28 23:57:24 +0100387/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
388static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
389{
390 if (fcn->function_ref[0] == -1)
391 return tid + 1;
392 return 0;
393}
394
Christopher Faulet69c581a2021-05-31 08:54:04 +0200395/* Create a new registered filter. Only its name is filled */
396static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
397{
398 struct hlua_reg_filter *reg_flt;
399 int i;
400
401 reg_flt = calloc(1, sizeof(*reg_flt));
402 if (!reg_flt)
403 return NULL;
404 reg_flt->name = strdup(name);
405 if (!reg_flt->name) {
406 free(reg_flt);
407 return NULL;
408 }
409 LIST_APPEND(&referenced_filters, &reg_flt->l);
410 for (i = 0; i < MAX_THREADS + 1; i++) {
411 reg_flt->flt_ref[i] = -1;
412 reg_flt->fun_ref[i] = -1;
413 }
414 return reg_flt;
415}
416
417/* Release a registered filter */
418static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
419{
420 if (!reg_flt)
421 return;
422 if (reg_flt->name)
423 ha_free(&reg_flt->name);
424 LIST_DELETE(&reg_flt->l);
425 ha_free(&reg_flt);
426}
427
428/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
429static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
430{
431 if (reg_flt->fun_ref[0] == -1)
432 return tid + 1;
433 return 0;
434}
435
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100436/* Used to check an Lua function type in the stack. It creates and
437 * returns a reference of the function. This function throws an
438 * error if the rgument is not a "function".
439 */
440__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
441{
442 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100443 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100444 WILL_LJMP(luaL_argerror(L, argno, msg));
445 }
446 lua_pushvalue(L, argno);
447 return luaL_ref(L, LUA_REGISTRYINDEX);
448}
449
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100450/* Used to check an Lua table type in the stack. It creates and
451 * returns a reference of the table. This function throws an
452 * error if the rgument is not a "table".
453 */
454__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
455{
456 if (!lua_istable(L, argno)) {
457 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
458 WILL_LJMP(luaL_argerror(L, argno, msg));
459 }
460 lua_pushvalue(L, argno);
461 return luaL_ref(L, LUA_REGISTRYINDEX);
462}
463
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200464/* Return the string that is of the top of the stack. */
465const char *hlua_get_top_error_string(lua_State *L)
466{
467 if (lua_gettop(L) < 1)
468 return "unknown error";
469 if (lua_type(L, -1) != LUA_TSTRING)
470 return "unknown error";
471 return lua_tostring(L, -1);
472}
473
Christopher Fauletd09cc512021-03-24 14:48:45 +0100474__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200475{
476 lua_Debug ar;
477 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200478 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200479
480 while (lua_getstack(L, level++, &ar)) {
481
482 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100483 if (b_data(msg))
484 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200485
486 /* Fill fields:
487 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
488 * 'l': fills in the field currentline;
489 * 'n': fills in the field name and namewhat;
490 * 't': fills in the field istailcall;
491 */
492 lua_getinfo(L, "Slnt", &ar);
493
494 /* Append code localisation */
495 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100496 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200497 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100498 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200499
500 /*
501 * Get function name
502 *
503 * if namewhat is no empty, name is defined.
504 * what contains "Lua" for Lua function, "C" for C function,
505 * or "main" for main code.
506 */
507 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100508 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200509
510 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100511 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200512
513 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100514 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200515
516 else /* nothing left... */
517 chunk_appendf(msg, "?");
518
519
520 /* Display tailed call */
521 if (ar.istailcall)
522 chunk_appendf(msg, " ...");
523 }
524
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200525 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200526}
527
528
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100529/* This function check the number of arguments available in the
530 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500531 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100532 */
533__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
534{
535 if (lua_gettop(L) == nb)
536 return;
537 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
538}
539
Mark Lakes22154b42018-01-29 14:38:40 -0800540/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100541 * and the line number where the error is encountered.
542 */
543static int hlua_pusherror(lua_State *L, const char *fmt, ...)
544{
545 va_list argp;
546 va_start(argp, fmt);
547 luaL_where(L, 1);
548 lua_pushvfstring(L, fmt, argp);
549 va_end(argp);
550 lua_concat(L, 2);
551 return 1;
552}
553
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100554/* This functions is used with sample fetch and converters. It
555 * converts the HAProxy configuration argument in a lua stack
556 * values.
557 *
558 * It takes an array of "arg", and each entry of the array is
559 * converted and pushed in the LUA stack.
560 */
561static int hlua_arg2lua(lua_State *L, const struct arg *arg)
562{
563 switch (arg->type) {
564 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100565 case ARGT_TIME:
566 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100567 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100568 break;
569
570 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200571 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100572 break;
573
574 case ARGT_IPV4:
575 case ARGT_IPV6:
576 case ARGT_MSK4:
577 case ARGT_MSK6:
578 case ARGT_FE:
579 case ARGT_BE:
580 case ARGT_TAB:
581 case ARGT_SRV:
582 case ARGT_USR:
583 case ARGT_MAP:
584 default:
585 lua_pushnil(L);
586 break;
587 }
588 return 1;
589}
590
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500591/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500593 * with sample fetch wrappers. The input arguments are given to the
594 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 */
596static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
597{
598 switch (lua_type(L, ud)) {
599
600 case LUA_TNUMBER:
601 case LUA_TBOOLEAN:
602 arg->type = ARGT_SINT;
603 arg->data.sint = lua_tointeger(L, ud);
604 break;
605
606 case LUA_TSTRING:
607 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200608 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200609 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200610 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200611 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100612 break;
613
614 case LUA_TUSERDATA:
615 case LUA_TNIL:
616 case LUA_TTABLE:
617 case LUA_TFUNCTION:
618 case LUA_TTHREAD:
619 case LUA_TLIGHTUSERDATA:
620 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200621 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 break;
623 }
624 return 1;
625}
626
627/* the following functions are used to convert a struct sample
628 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500629 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100630 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100631static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100632{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200633 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100634 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100635 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200636 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100637 break;
638
639 case SMP_T_BIN:
640 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200641 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 break;
643
644 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200645 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100646 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
647 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
648 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
649 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
650 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
651 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
652 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
653 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
654 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200655 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100656 break;
657 default:
658 lua_pushnil(L);
659 break;
660 }
661 break;
662
663 case SMP_T_IPV4:
664 case SMP_T_IPV6:
665 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200666 if (sample_casts[smp->data.type][SMP_T_STR] &&
667 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200668 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100669 else
670 lua_pushnil(L);
671 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 default:
673 lua_pushnil(L);
674 break;
675 }
676 return 1;
677}
678
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100679/* the following functions are used to convert a struct sample
680 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500681 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100682 */
683static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
684{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200685 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100686
687 case SMP_T_BIN:
688 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200689 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100690 break;
691
692 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200693 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100694 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
695 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
696 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
697 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
698 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
699 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
700 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
701 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
702 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200703 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100704 break;
705 default:
706 lua_pushstring(L, "");
707 break;
708 }
709 break;
710
711 case SMP_T_SINT:
712 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100713 case SMP_T_IPV4:
714 case SMP_T_IPV6:
715 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200716 if (sample_casts[smp->data.type][SMP_T_STR] &&
717 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200718 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100719 else
720 lua_pushstring(L, "");
721 break;
722 default:
723 lua_pushstring(L, "");
724 break;
725 }
726 return 1;
727}
728
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100729/* the following functions are used to convert an Lua type in a
730 * struct sample. This is useful to provide data from a converter
731 * to the LUA code.
732 */
733static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
734{
735 switch (lua_type(L, ud)) {
736
737 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200738 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200739 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100740 break;
741
742
743 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200744 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200745 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100746 break;
747
748 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200749 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100750 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200751 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200752 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200753 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200754 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100755 break;
756
757 case LUA_TUSERDATA:
758 case LUA_TNIL:
759 case LUA_TTABLE:
760 case LUA_TFUNCTION:
761 case LUA_TTHREAD:
762 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200763 case LUA_TNONE:
764 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200765 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200766 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100767 break;
768 }
769 return 1;
770}
771
Ilya Shipitsind4259502020-04-08 01:07:56 +0500772/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800773 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100774 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100775 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500776 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200777 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100778 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100779__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100780 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100781{
782 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200783 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100784 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200785 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200786 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200787 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200788 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100789
790 idx = 0;
791 min_arg = ARGM(mask);
792 mask >>= ARGM_BITS;
793
794 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200795 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100796
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100797 /* Check for mandatory arguments. */
798 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100799 if (idx < min_arg) {
800
801 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200802 if (idx > 0) {
803 msg = "Mandatory argument expected";
804 goto error;
805 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100806
807 /* If first argument have a certain type, some default values
808 * may be used. See the function smp_resolve_args().
809 */
810 switch (mask & ARGT_MASK) {
811
812 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200813 if (!(p->cap & PR_CAP_FE)) {
814 msg = "Mandatory argument expected";
815 goto error;
816 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100817 argp[idx].data.prx = p;
818 argp[idx].type = ARGT_FE;
819 argp[idx+1].type = ARGT_STOP;
820 break;
821
822 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200823 if (!(p->cap & PR_CAP_BE)) {
824 msg = "Mandatory argument expected";
825 goto error;
826 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100827 argp[idx].data.prx = p;
828 argp[idx].type = ARGT_BE;
829 argp[idx+1].type = ARGT_STOP;
830 break;
831
832 case ARGT_TAB:
833 argp[idx].data.prx = p;
834 argp[idx].type = ARGT_TAB;
835 argp[idx+1].type = ARGT_STOP;
836 break;
837
838 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200839 msg = "Mandatory argument expected";
840 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100841 break;
842 }
843 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200844 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100845 }
846
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500847 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100848 if ((mask & ARGT_MASK) == ARGT_STOP &&
849 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200850 msg = "Last argument expected";
851 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100852 }
853
854 if ((mask & ARGT_MASK) == ARGT_STOP &&
855 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200856 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100857 }
858
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200859 /* Convert some argument types. All string in argp[] are for not
860 * duplicated yet.
861 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100862 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100863 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200864 if (argp[idx].type != ARGT_SINT) {
865 msg = "integer expected";
866 goto error;
867 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100868 argp[idx].type = ARGT_SINT;
869 break;
870
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100871 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200872 if (argp[idx].type != ARGT_SINT) {
873 msg = "integer expected";
874 goto error;
875 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200876 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100877 break;
878
879 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200880 if (argp[idx].type != ARGT_SINT) {
881 msg = "integer expected";
882 goto error;
883 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200884 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100885 break;
886
887 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200888 if (argp[idx].type != ARGT_STR) {
889 msg = "string expected";
890 goto error;
891 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200892 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200893 if (!argp[idx].data.prx) {
894 msg = "frontend doesn't exist";
895 goto error;
896 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100897 argp[idx].type = ARGT_FE;
898 break;
899
900 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200901 if (argp[idx].type != ARGT_STR) {
902 msg = "string expected";
903 goto error;
904 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200905 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200906 if (!argp[idx].data.prx) {
907 msg = "backend doesn't exist";
908 goto error;
909 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100910 argp[idx].type = ARGT_BE;
911 break;
912
913 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200914 if (argp[idx].type != ARGT_STR) {
915 msg = "string expected";
916 goto error;
917 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200918 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200919 if (!argp[idx].data.t) {
920 msg = "table doesn't exist";
921 goto error;
922 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100923 argp[idx].type = ARGT_TAB;
924 break;
925
926 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200927 if (argp[idx].type != ARGT_STR) {
928 msg = "string expected";
929 goto error;
930 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200931 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100932 if (sname) {
933 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200934 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200935 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200936 if (!px) {
937 msg = "backend doesn't exist";
938 goto error;
939 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100940 }
941 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200942 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100943 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100944 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100945 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200946 if (!argp[idx].data.srv) {
947 msg = "server doesn't exist";
948 goto error;
949 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100950 argp[idx].type = ARGT_SRV;
951 break;
952
953 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200954 if (argp[idx].type != ARGT_STR) {
955 msg = "string expected";
956 goto error;
957 }
958 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
959 msg = "invalid IPv4 address";
960 goto error;
961 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100962 argp[idx].type = ARGT_IPV4;
963 break;
964
965 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200966 if (argp[idx].type == ARGT_SINT)
967 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
968 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200969 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
970 msg = "invalid IPv4 mask";
971 goto error;
972 }
973 }
974 else {
975 msg = "integer or string expected";
976 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200977 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100978 argp[idx].type = ARGT_MSK4;
979 break;
980
981 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200982 if (argp[idx].type != ARGT_STR) {
983 msg = "string expected";
984 goto error;
985 }
986 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
987 msg = "invalid IPv6 address";
988 goto error;
989 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100990 argp[idx].type = ARGT_IPV6;
991 break;
992
993 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200994 if (argp[idx].type == ARGT_SINT)
995 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
996 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200997 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
998 msg = "invalid IPv6 mask";
999 goto error;
1000 }
1001 }
1002 else {
1003 msg = "integer or string expected";
1004 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001005 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001006 argp[idx].type = ARGT_MSK6;
1007 break;
1008
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001009 case ARGT_REG:
1010 if (argp[idx].type != ARGT_STR) {
1011 msg = "string expected";
1012 goto error;
1013 }
1014 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1015 if (!reg) {
1016 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1017 argp[idx].data.str.area, err);
1018 free(err);
1019 goto error;
1020 }
1021 argp[idx].type = ARGT_REG;
1022 argp[idx].data.reg = reg;
1023 break;
1024
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001025 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001026 if (argp[idx].type != ARGT_STR) {
1027 msg = "string expected";
1028 goto error;
1029 }
1030 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001031 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001032 ul = p->uri_auth->userlist;
1033 else
1034 ul = auth_find_userlist(argp[idx].data.str.area);
1035
1036 if (!ul) {
1037 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1038 goto error;
1039 }
1040 argp[idx].type = ARGT_USR;
1041 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001042 break;
1043
1044 case ARGT_STR:
1045 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1046 msg = "unable to duplicate string arg";
1047 goto error;
1048 }
1049 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001050 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001051
Christopher Fauletd25d9262020-08-06 11:04:46 +02001052 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001053 msg = "type not yet supported";
1054 goto error;
1055 break;
1056
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001057 }
1058
1059 /* Check for type of argument. */
1060 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001061 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1062 arg_type_names[(mask & ARGT_MASK)],
1063 arg_type_names[argp[idx].type & ARGT_MASK]);
1064 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001065 }
1066
1067 /* Next argument. */
1068 mask >>= ARGT_BITS;
1069 idx++;
1070 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001071 return 0;
1072
1073 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001074 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001075 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1076 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001077}
1078
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001079/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001080 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001081 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001082 *
1083 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001084 * - hlua_sethlua : create the association between hlua context and lua_state.
1085 */
1086static inline struct hlua *hlua_gethlua(lua_State *L)
1087{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001088 struct hlua **hlua = lua_getextraspace(L);
1089 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001090}
1091static inline void hlua_sethlua(struct hlua *hlua)
1092{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001093 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1094 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001095}
1096
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001097/* This function is used to send logs. It try to send on screen (stderr)
1098 * and on the default syslog server.
1099 */
1100static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1101{
1102 struct tm tm;
1103 char *p;
1104
1105 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001106 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001107 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001108 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001109 /* Break the message if exceed the buffer size. */
1110 *(p-4) = ' ';
1111 *(p-3) = '.';
1112 *(p-2) = '.';
1113 *(p-1) = '.';
1114 break;
1115 }
Willy Tarreau90807112020-02-25 08:16:33 +01001116 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001117 *p = *msg;
1118 else
1119 *p = '.';
1120 }
1121 *p = '\0';
1122
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001123 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001124 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001125 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1126 return;
1127
Willy Tarreaua678b432015-08-28 10:14:59 +02001128 get_localtime(date.tv_sec, &tm);
1129 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001130 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001131 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001132 fflush(stderr);
1133 }
1134}
1135
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001136/* This function just ensure that the yield will be always
1137 * returned with a timeout and permit to set some flags
1138 */
1139__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001140 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001141{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001142 struct hlua *hlua;
1143
1144 /* Get hlua struct, or NULL if we execute from main lua state */
1145 hlua = hlua_gethlua(L);
1146 if (!hlua) {
1147 return;
1148 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001149
1150 /* Set the wake timeout. If timeout is required, we set
1151 * the expiration time.
1152 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001153 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001154
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001155 hlua->flags |= flags;
1156
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001157 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001158 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001159}
1160
Willy Tarreau87b09662015-04-03 00:22:06 +02001161/* This function initialises the Lua environment stored in the stream.
1162 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001163 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001164 *
1165 * This function is particular. it initialises a new Lua thread. If the
1166 * initialisation fails (example: out of memory error), the lua function
1167 * throws an error (longjmp).
1168 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001169 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001170 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001171 * threads appear, the safe environment set a lock to ensure only one
1172 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001173 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001174 *
1175 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001176 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001177 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001178 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001179 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001180 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001181 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001182 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001183int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001184{
1185 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001186 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001187 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001188 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001189 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001190 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001191 if (!already_safe) {
1192 if (!SET_SAFE_LJMP_PARENT(lua)) {
1193 lua->Tref = LUA_REFNIL;
1194 return 0;
1195 }
1196 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001197 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001198 if (!lua->T) {
1199 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001200 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001201 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001202 return 0;
1203 }
1204 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001205 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001206 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001207 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001208 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001209 return 1;
1210}
1211
Willy Tarreau87b09662015-04-03 00:22:06 +02001212/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001213 * is destroyed. The destroy also the memory context. The struct "lua"
1214 * is not freed.
1215 */
1216void hlua_ctx_destroy(struct hlua *lua)
1217{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001218 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001219 return;
1220
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001221 if (!lua->T)
1222 goto end;
1223
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001224 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001225 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001226
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001227 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001228 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001229 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001230 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001231
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001232 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001233 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001234 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001235 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001236 /* Forces a garbage collecting process. If the Lua program is finished
1237 * without error, we run the GC on the thread pointer. Its freed all
1238 * the unused memory.
1239 * If the thread is finnish with an error or is currently yielded,
1240 * it seems that the GC applied on the thread doesn't clean anything,
1241 * so e run the GC on the main thread.
1242 * NOTE: maybe this action locks all the Lua threads untiml the en of
1243 * the garbage collection.
1244 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001245 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001246 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001247 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001248 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001249 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001250 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001251
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001252 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001253
1254end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001255 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001256}
1257
1258/* This function is used to restore the Lua context when a coroutine
1259 * fails. This function copy the common memory between old coroutine
1260 * and the new coroutine. The old coroutine is destroyed, and its
1261 * replaced by the new coroutine.
1262 * If the flag "keep_msg" is set, the last entry of the old is assumed
1263 * as string error message and it is copied in the new stack.
1264 */
1265static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1266{
1267 lua_State *T;
1268 int new_ref;
1269
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001270 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001271 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001272 if (!T)
1273 return 0;
1274
1275 /* Copy last error message. */
1276 if (keep_msg)
1277 lua_xmove(lua->T, T, 1);
1278
1279 /* Copy data between the coroutines. */
1280 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1281 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001282 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001283
1284 /* Destroy old data. */
1285 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1286
1287 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001288 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001289
1290 /* Fill the struct with the new coroutine values. */
1291 lua->Mref = new_ref;
1292 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001293 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001294
1295 /* Set context. */
1296 hlua_sethlua(lua);
1297
1298 return 1;
1299}
1300
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001301void hlua_hook(lua_State *L, lua_Debug *ar)
1302{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001303 struct hlua *hlua;
1304
1305 /* Get hlua struct, or NULL if we execute from main lua state */
1306 hlua = hlua_gethlua(L);
1307 if (!hlua)
1308 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001309
1310 /* Lua cannot yield when its returning from a function,
1311 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001312 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001313 */
1314 if (lua_gethookmask(L) & LUA_MASKRET) {
1315 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1316 return;
1317 }
1318
1319 /* restore the interrupt condition. */
1320 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1321
1322 /* If we interrupt the Lua processing in yieldable state, we yield.
1323 * If the state is not yieldable, trying yield causes an error.
1324 */
1325 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001326 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001327
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001328 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001329 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001330 hlua->run_time += now_ms - hlua->start_time;
1331 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001332 lua_pushfstring(L, "execution timeout");
1333 WILL_LJMP(lua_error(L));
1334 }
1335
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001336 /* Update the start time. */
1337 hlua->start_time = now_ms;
1338
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001339 /* Try to interrupt the process at the end of the current
1340 * unyieldable function.
1341 */
1342 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001343}
1344
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001345/* This function start or resumes the Lua stack execution. If the flag
1346 * "yield_allowed" if no set and the LUA stack execution returns a yield
1347 * The function return an error.
1348 *
1349 * The function can returns 4 values:
1350 * - HLUA_E_OK : The execution is terminated without any errors.
1351 * - HLUA_E_AGAIN : The execution must continue at the next associated
1352 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001353 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001354 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001355 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001356 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001357 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001358 * LUA code.
1359 */
1360static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1361{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001362#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1363 int nres;
1364#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001365 int ret;
1366 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001367 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001368
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001369 /* Initialise run time counter. */
1370 if (!HLUA_IS_RUNNING(lua))
1371 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001372
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001373 /* Lock the whole Lua execution. This lock must be before the
1374 * label "resume_execution".
1375 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001376 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001377 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001378
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001379resume_execution:
1380
1381 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1382 * instructions. it is used for preventing infinite loops.
1383 */
1384 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1385
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001386 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001387 HLUA_SET_RUN(lua);
1388 HLUA_CLR_CTRLYIELD(lua);
1389 HLUA_CLR_WAKERESWR(lua);
1390 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001391 HLUA_CLR_NOYIELD(lua);
1392 if (!yield_allowed)
1393 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001394
Christopher Fauletbc275a92020-02-26 14:55:16 +01001395 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001396 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001397 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001398
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001399 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001400#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001401 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001402#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001403 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001404#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001405 switch (ret) {
1406
1407 case LUA_OK:
1408 ret = HLUA_E_OK;
1409 break;
1410
1411 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001412 /* Check if the execution timeout is expired. It it is the case, we
1413 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001414 */
Willy Tarreau55542642021-10-08 09:33:24 +02001415 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001416 lua->run_time += now_ms - lua->start_time;
1417 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001418 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001419 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001420 break;
1421 }
1422 /* Process the forced yield. if the general yield is not allowed or
1423 * if no task were associated this the current Lua execution
1424 * coroutine, we resume the execution. Else we want to return in the
1425 * scheduler and we want to be waked up again, to continue the
1426 * current Lua execution. So we schedule our own task.
1427 */
1428 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001429 if (!yield_allowed || !lua->task)
1430 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001431 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001432 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001433 if (!yield_allowed) {
1434 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001435 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001436 break;
1437 }
1438 ret = HLUA_E_AGAIN;
1439 break;
1440
1441 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001442
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001443 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001444 * because the errors ares the only one mean to return immediately
1445 * from and lua execution.
1446 */
1447 if (lua->flags & HLUA_EXIT) {
1448 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001449 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001450 break;
1451 }
1452
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001453 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001454 if (!lua_checkstack(lua->T, 1)) {
1455 ret = HLUA_E_ERR;
1456 break;
1457 }
1458 msg = lua_tostring(lua->T, -1);
1459 lua_settop(lua->T, 0); /* Empty the stack. */
1460 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001461 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001462 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001463 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001464 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001465 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001466 ret = HLUA_E_ERRMSG;
1467 break;
1468
1469 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001470 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001471 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001472 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001473 break;
1474
1475 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001476 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001477 if (!lua_checkstack(lua->T, 1)) {
1478 ret = HLUA_E_ERR;
1479 break;
1480 }
1481 msg = lua_tostring(lua->T, -1);
1482 lua_settop(lua->T, 0); /* Empty the stack. */
1483 lua_pop(lua->T, 1);
1484 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001485 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001486 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001487 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001488 ret = HLUA_E_ERRMSG;
1489 break;
1490
1491 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001492 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001493 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001494 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001495 break;
1496 }
1497
1498 switch (ret) {
1499 case HLUA_E_AGAIN:
1500 break;
1501
1502 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001503 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001504 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001505 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001506 break;
1507
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001508 case HLUA_E_ETMOUT:
1509 case HLUA_E_NOMEM:
1510 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001511 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001512 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001513 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001514 hlua_ctx_renew(lua, 0);
1515 break;
1516
1517 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001518 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001519 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001520 break;
1521 }
1522
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001523 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001524 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001525 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001526
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001527 return ret;
1528}
1529
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001530/* This function exit the current code. */
1531__LJMP static int hlua_done(lua_State *L)
1532{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001533 struct hlua *hlua;
1534
1535 /* Get hlua struct, or NULL if we execute from main lua state */
1536 hlua = hlua_gethlua(L);
1537 if (!hlua)
1538 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001539
1540 hlua->flags |= HLUA_EXIT;
1541 WILL_LJMP(lua_error(L));
1542
1543 return 0;
1544}
1545
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001546/* This function is an LUA binding. It provides a function
1547 * for deleting ACL from a referenced ACL file.
1548 */
1549__LJMP static int hlua_del_acl(lua_State *L)
1550{
1551 const char *name;
1552 const char *key;
1553 struct pat_ref *ref;
1554
1555 MAY_LJMP(check_args(L, 2, "del_acl"));
1556
1557 name = MAY_LJMP(luaL_checkstring(L, 1));
1558 key = MAY_LJMP(luaL_checkstring(L, 2));
1559
1560 ref = pat_ref_lookup(name);
1561 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001562 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001563
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001564 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001565 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001566 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001567 return 0;
1568}
1569
1570/* This function is an LUA binding. It provides a function
1571 * for deleting map entry from a referenced map file.
1572 */
1573static int hlua_del_map(lua_State *L)
1574{
1575 const char *name;
1576 const char *key;
1577 struct pat_ref *ref;
1578
1579 MAY_LJMP(check_args(L, 2, "del_map"));
1580
1581 name = MAY_LJMP(luaL_checkstring(L, 1));
1582 key = MAY_LJMP(luaL_checkstring(L, 2));
1583
1584 ref = pat_ref_lookup(name);
1585 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001586 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001587
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001588 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001589 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001590 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001591 return 0;
1592}
1593
1594/* This function is an LUA binding. It provides a function
1595 * for adding ACL pattern from a referenced ACL file.
1596 */
1597static int hlua_add_acl(lua_State *L)
1598{
1599 const char *name;
1600 const char *key;
1601 struct pat_ref *ref;
1602
1603 MAY_LJMP(check_args(L, 2, "add_acl"));
1604
1605 name = MAY_LJMP(luaL_checkstring(L, 1));
1606 key = MAY_LJMP(luaL_checkstring(L, 2));
1607
1608 ref = pat_ref_lookup(name);
1609 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001610 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001611
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001612 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001613 if (pat_ref_find_elt(ref, key) == NULL)
1614 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001615 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001616 return 0;
1617}
1618
1619/* This function is an LUA binding. It provides a function
1620 * for setting map pattern and sample from a referenced map
1621 * file.
1622 */
1623static int hlua_set_map(lua_State *L)
1624{
1625 const char *name;
1626 const char *key;
1627 const char *value;
1628 struct pat_ref *ref;
1629
1630 MAY_LJMP(check_args(L, 3, "set_map"));
1631
1632 name = MAY_LJMP(luaL_checkstring(L, 1));
1633 key = MAY_LJMP(luaL_checkstring(L, 2));
1634 value = MAY_LJMP(luaL_checkstring(L, 3));
1635
1636 ref = pat_ref_lookup(name);
1637 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001638 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001639
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001640 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001641 if (pat_ref_find_elt(ref, key) != NULL)
1642 pat_ref_set(ref, key, value, NULL);
1643 else
1644 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001645 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001646 return 0;
1647}
1648
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001649/* A class is a lot of memory that contain data. This data can be a table,
1650 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001651 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001652 * the name of the object (_G[<name>] = <metable> ).
1653 *
1654 * A metable is a table that modify the standard behavior of a standard
1655 * access to the associated data. The entries of this new metatable are
1656 * defined as is:
1657 *
1658 * http://lua-users.org/wiki/MetatableEvents
1659 *
1660 * __index
1661 *
1662 * we access an absent field in a table, the result is nil. This is
1663 * true, but it is not the whole truth. Actually, such access triggers
1664 * the interpreter to look for an __index metamethod: If there is no
1665 * such method, as usually happens, then the access results in nil;
1666 * otherwise, the metamethod will provide the result.
1667 *
1668 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1669 * the key does not appear in the table, but the metatable has an __index
1670 * property:
1671 *
1672 * - if the value is a function, the function is called, passing in the
1673 * table and the key; the return value of that function is returned as
1674 * the result.
1675 *
1676 * - if the value is another table, the value of the key in that table is
1677 * asked for and returned (and if it doesn't exist in that table, but that
1678 * table's metatable has an __index property, then it continues on up)
1679 *
1680 * - Use "rawget(myTable,key)" to skip this metamethod.
1681 *
1682 * http://www.lua.org/pil/13.4.1.html
1683 *
1684 * __newindex
1685 *
1686 * Like __index, but control property assignment.
1687 *
1688 * __mode - Control weak references. A string value with one or both
1689 * of the characters 'k' and 'v' which specifies that the the
1690 * keys and/or values in the table are weak references.
1691 *
1692 * __call - Treat a table like a function. When a table is followed by
1693 * parenthesis such as "myTable( 'foo' )" and the metatable has
1694 * a __call key pointing to a function, that function is invoked
1695 * (passing any specified arguments) and the return value is
1696 * returned.
1697 *
1698 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1699 * called, if the metatable for myTable has a __metatable
1700 * key, the value of that key is returned instead of the
1701 * actual metatable.
1702 *
1703 * __tostring - Control string representation. When the builtin
1704 * "tostring( myTable )" function is called, if the metatable
1705 * for myTable has a __tostring property set to a function,
1706 * that function is invoked (passing myTable to it) and the
1707 * return value is used as the string representation.
1708 *
1709 * __len - Control table length. When the table length is requested using
1710 * the length operator ( '#' ), if the metatable for myTable has
1711 * a __len key pointing to a function, that function is invoked
1712 * (passing myTable to it) and the return value used as the value
1713 * of "#myTable".
1714 *
1715 * __gc - Userdata finalizer code. When userdata is set to be garbage
1716 * collected, if the metatable has a __gc field pointing to a
1717 * function, that function is first invoked, passing the userdata
1718 * to it. The __gc metamethod is not called for tables.
1719 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1720 *
1721 * Special metamethods for redefining standard operators:
1722 * http://www.lua.org/pil/13.1.html
1723 *
1724 * __add "+"
1725 * __sub "-"
1726 * __mul "*"
1727 * __div "/"
1728 * __unm "!"
1729 * __pow "^"
1730 * __concat ".."
1731 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001732 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001733 * http://www.lua.org/pil/13.2.html
1734 *
1735 * __eq "=="
1736 * __lt "<"
1737 * __le "<="
1738 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001739
1740/*
1741 *
1742 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001743 * Class Map
1744 *
1745 *
1746 */
1747
1748/* Returns a struct hlua_map if the stack entry "ud" is
1749 * a class session, otherwise it throws an error.
1750 */
1751__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1752{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001753 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001754}
1755
1756/* This function is the map constructor. It don't need
1757 * the class Map object. It creates and return a new Map
1758 * object. It must be called only during "body" or "init"
1759 * context because it process some filesystem accesses.
1760 */
1761__LJMP static int hlua_map_new(struct lua_State *L)
1762{
1763 const char *fn;
1764 int match = PAT_MATCH_STR;
1765 struct sample_conv conv;
1766 const char *file = "";
1767 int line = 0;
1768 lua_Debug ar;
1769 char *err = NULL;
1770 struct arg args[2];
1771
1772 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1773 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1774
1775 fn = MAY_LJMP(luaL_checkstring(L, 1));
1776
1777 if (lua_gettop(L) >= 2) {
1778 match = MAY_LJMP(luaL_checkinteger(L, 2));
1779 if (match < 0 || match >= PAT_MATCH_NUM)
1780 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1781 }
1782
1783 /* Get Lua filename and line number. */
1784 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1785 lua_getinfo(L, "Sl", &ar); /* get info about it */
1786 if (ar.currentline > 0) { /* is there info? */
1787 file = ar.short_src;
1788 line = ar.currentline;
1789 }
1790 }
1791
1792 /* fill fake sample_conv struct. */
1793 conv.kw = ""; /* unused. */
1794 conv.process = NULL; /* unused. */
1795 conv.arg_mask = 0; /* unused. */
1796 conv.val_args = NULL; /* unused. */
1797 conv.out_type = SMP_T_STR;
1798 conv.private = (void *)(long)match;
1799 switch (match) {
1800 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1801 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1802 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1803 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1804 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1805 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1806 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001807 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001808 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1809 default:
1810 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1811 }
1812
1813 /* fill fake args. */
1814 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001815 args[0].data.str.area = strdup(fn);
1816 args[0].data.str.data = strlen(fn);
1817 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001818 args[1].type = ARGT_STOP;
1819
1820 /* load the map. */
1821 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001822 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001823 * free the err variable.
1824 */
1825 luaL_where(L, 1);
1826 lua_pushfstring(L, "'new': %s.", err);
1827 lua_concat(L, 2);
1828 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001829 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001830 WILL_LJMP(lua_error(L));
1831 }
1832
1833 /* create the lua object. */
1834 lua_newtable(L);
1835 lua_pushlightuserdata(L, args[0].data.map);
1836 lua_rawseti(L, -2, 0);
1837
1838 /* Pop a class Map metatable and affect it to the userdata. */
1839 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1840 lua_setmetatable(L, -2);
1841
1842
1843 return 1;
1844}
1845
1846__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1847{
1848 struct map_descriptor *desc;
1849 struct pattern *pat;
1850 struct sample smp;
1851
1852 MAY_LJMP(check_args(L, 2, "lookup"));
1853 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001854 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001855 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001856 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001857 }
1858 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001859 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001860 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001861 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 +01001862 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001863 }
1864
1865 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001866 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001867 if (str)
1868 lua_pushstring(L, "");
1869 else
1870 lua_pushnil(L);
1871 return 1;
1872 }
1873
1874 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001875 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001876 return 1;
1877}
1878
1879__LJMP static int hlua_map_lookup(struct lua_State *L)
1880{
1881 return _hlua_map_lookup(L, 0);
1882}
1883
1884__LJMP static int hlua_map_slookup(struct lua_State *L)
1885{
1886 return _hlua_map_lookup(L, 1);
1887}
1888
1889/*
1890 *
1891 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001892 * Class Socket
1893 *
1894 *
1895 */
1896
1897__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1898{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001899 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001900}
1901
1902/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001903 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001904 * received.
1905 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001906static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001907{
Christopher Faulet86e1c332021-12-20 17:09:39 +01001908 struct stream_interface *si = cs_si(appctx->owner);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001909
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001910 if (appctx->ctx.hlua_cosocket.die) {
1911 si_shutw(si);
1912 si_shutr(si);
1913 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001914 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1915 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001916 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1917 }
1918
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001919 /* If we can't write, wakeup the pending write signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001920 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001921 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001922
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001923 /* If we can't read, wakeup the pending read signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001924 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001925 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001926
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001927 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001928 * to be notified whenever the connection completes.
1929 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001930 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001931 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001932 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001933 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001934 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001935 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001936
1937 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001938 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001939
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001940 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001941 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001942 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001943
1944 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001945 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001946 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001947
1948 /* Some data were injected in the buffer, notify the stream
1949 * interface.
1950 */
1951 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001952 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001953
1954 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001955 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001956 */
1957 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001958 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001959}
1960
Willy Tarreau87b09662015-04-03 00:22:06 +02001961/* This function is called when the "struct stream" is destroyed.
1962 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001963 * Wake all the pending signals.
1964 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001965static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001966{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001967 struct xref *peer;
1968
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001969 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001970 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1971 if (peer)
1972 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001973
1974 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001975 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1976 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001977}
1978
1979/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001980 * uses this object. If the stream does not exists, just quit.
1981 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001982 * pending signal can rest in the read and write lists. destroy
1983 * it.
1984 */
1985__LJMP static int hlua_socket_gc(lua_State *L)
1986{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001987 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001988 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001989 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001990
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001991 MAY_LJMP(check_args(L, 1, "__gc"));
1992
1993 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001994 peer = xref_get_peer_and_lock(&socket->xref);
1995 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001996 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001997 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001999 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002000 appctx->ctx.hlua_cosocket.die = 1;
2001 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002002
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002003 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002004 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002005 return 0;
2006}
2007
2008/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002009 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002010 */
sada05ed3302018-05-11 11:48:18 -07002011__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002013 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002014 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002015 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002016 struct hlua *hlua;
2017
2018 /* Get hlua struct, or NULL if we execute from main lua state */
2019 hlua = hlua_gethlua(L);
2020 if (!hlua)
2021 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002022
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002023 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002024
2025 /* Check if we run on the same thread than the xreator thread.
2026 * We cannot access to the socket if the thread is different.
2027 */
2028 if (socket->tid != tid)
2029 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2030
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002031 peer = xref_get_peer_and_lock(&socket->xref);
2032 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002033 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002034
2035 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002036 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002037
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002038 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002039 appctx->ctx.hlua_cosocket.die = 1;
2040 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002041
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002042 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002043 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002044 return 0;
2045}
2046
sada05ed3302018-05-11 11:48:18 -07002047/* The close function calls close_helper.
2048 */
2049__LJMP static int hlua_socket_close(lua_State *L)
2050{
2051 MAY_LJMP(check_args(L, 1, "close"));
2052 return hlua_socket_close_helper(L);
2053}
2054
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002055/* This Lua function assumes that the stack contain three parameters.
2056 * 1 - USERDATA containing a struct socket
2057 * 2 - INTEGER with values of the macro defined below
2058 * If the integer is -1, we must read at most one line.
2059 * If the integer is -2, we ust read all the data until the
2060 * end of the stream.
2061 * If the integer is positive value, we must read a number of
2062 * bytes corresponding to this value.
2063 */
2064#define HLSR_READ_LINE (-1)
2065#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002066__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067{
2068 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2069 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002070 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002072 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002073 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002074 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002075 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002076 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002077 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002078 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002079 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002080 struct stream_interface *si;
2081 struct stream *s;
2082 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002083 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002084
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002085 /* Get hlua struct, or NULL if we execute from main lua state */
2086 hlua = hlua_gethlua(L);
2087
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088 /* Check if this lua stack is schedulable. */
2089 if (!hlua || !hlua->task)
2090 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2091 "'frontend', 'backend' or 'task'"));
2092
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002093 /* Check if we run on the same thread than the xreator thread.
2094 * We cannot access to the socket if the thread is different.
2095 */
2096 if (socket->tid != tid)
2097 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2098
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002099 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002100 peer = xref_get_peer_and_lock(&socket->xref);
2101 if (!peer)
2102 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002103 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002104 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002105 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002106
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002107 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002108 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002109 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002110 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111 if (nblk < 0) /* Connection close. */
2112 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002113 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002114 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002115
2116 /* remove final \r\n. */
2117 if (nblk == 1) {
2118 if (blk1[len1-1] == '\n') {
2119 len1--;
2120 skip_at_end++;
2121 if (blk1[len1-1] == '\r') {
2122 len1--;
2123 skip_at_end++;
2124 }
2125 }
2126 }
2127 else {
2128 if (blk2[len2-1] == '\n') {
2129 len2--;
2130 skip_at_end++;
2131 if (blk2[len2-1] == '\r') {
2132 len2--;
2133 skip_at_end++;
2134 }
2135 }
2136 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002137 }
2138
2139 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002140 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002141 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 if (nblk < 0) /* Connection close. */
2143 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002144 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145 goto connection_empty;
2146 }
2147
2148 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002150 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151 if (nblk < 0) /* Connection close. */
2152 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002153 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002154 goto connection_empty;
2155
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002156 missing_bytes = wanted - socket->b.n;
2157 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002159 len1 = missing_bytes;
2160 } if (nblk == 2 && len1 + len2 > missing_bytes)
2161 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162 }
2163
2164 len = len1;
2165
2166 luaL_addlstring(&socket->b, blk1, len1);
2167 if (nblk == 2) {
2168 len += len2;
2169 luaL_addlstring(&socket->b, blk2, len2);
2170 }
2171
2172 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002173 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174
2175 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002176 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
2178 /* If the pattern reclaim to read all the data
2179 * in the connection, got out.
2180 */
2181 if (wanted == HLSR_READ_ALL)
2182 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002183 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002184 goto connection_empty;
2185
2186 /* Return result. */
2187 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002188 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002189 return 1;
2190
2191connection_closed:
2192
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002193 xref_unlock(&socket->xref, peer);
2194
2195no_peer:
2196
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197 /* If the buffer containds data. */
2198 if (socket->b.n > 0) {
2199 luaL_pushresult(&socket->b);
2200 return 1;
2201 }
2202 lua_pushnil(L);
2203 lua_pushstring(L, "connection closed.");
2204 return 2;
2205
2206connection_empty:
2207
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002208 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
2209 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002210 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002211 }
2212 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002213 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214 return 0;
2215}
2216
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002217/* This Lua function gets two parameters. The first one can be string
2218 * or a number. If the string is "*l", the user requires one line. If
2219 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220 * If the value is a number, the user require a number of bytes equal
2221 * to the value. The default value is "*l" (a line).
2222 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002223 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224 * integer takes this values:
2225 * -1 : read a line
2226 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002227 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002229 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 * concatenated with the read data.
2231 */
2232__LJMP static int hlua_socket_receive(struct lua_State *L)
2233{
2234 int wanted = HLSR_READ_LINE;
2235 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002236 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237 char *error;
2238 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002239 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240
2241 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2242 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2243
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002244 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002246 /* Check if we run on the same thread than the xreator thread.
2247 * We cannot access to the socket if the thread is different.
2248 */
2249 if (socket->tid != tid)
2250 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2251
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252 /* check for pattern. */
2253 if (lua_gettop(L) >= 2) {
2254 type = lua_type(L, 2);
2255 if (type == LUA_TSTRING) {
2256 pattern = lua_tostring(L, 2);
2257 if (strcmp(pattern, "*a") == 0)
2258 wanted = HLSR_READ_ALL;
2259 else if (strcmp(pattern, "*l") == 0)
2260 wanted = HLSR_READ_LINE;
2261 else {
2262 wanted = strtoll(pattern, &error, 10);
2263 if (*error != '\0')
2264 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2265 }
2266 }
2267 else if (type == LUA_TNUMBER) {
2268 wanted = lua_tointeger(L, 2);
2269 if (wanted < 0)
2270 WILL_LJMP(luaL_error(L, "Unsupported size."));
2271 }
2272 }
2273
2274 /* Set pattern. */
2275 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002276
2277 /* Check if we would replace the top by itself. */
2278 if (lua_gettop(L) != 2)
2279 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280
Christopher Fauletc31b2002021-05-03 10:11:13 +02002281 /* Save index of the top of the stack because since buffers are used, it
2282 * may change
2283 */
2284 lastarg = lua_gettop(L);
2285
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002286 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287 luaL_buffinit(L, &socket->b);
2288
2289 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002290 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291 if (lua_type(L, 3) != LUA_TSTRING)
2292 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2293 pattern = lua_tolstring(L, 3, &len);
2294 luaL_addlstring(&socket->b, pattern, len);
2295 }
2296
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002297 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298}
2299
2300/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002301 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002303static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304{
2305 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002306 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002307 struct appctx *appctx;
2308 size_t buf_len;
2309 const char *buf;
2310 int len;
2311 int send_len;
2312 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002313 struct xref *peer;
2314 struct stream_interface *si;
2315 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002317 /* Get hlua struct, or NULL if we execute from main lua state */
2318 hlua = hlua_gethlua(L);
2319
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002320 /* Check if this lua stack is schedulable. */
2321 if (!hlua || !hlua->task)
2322 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2323 "'frontend', 'backend' or 'task'"));
2324
2325 /* Get object */
2326 socket = MAY_LJMP(hlua_checksocket(L, 1));
2327 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002328 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002329
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002330 /* Check if we run on the same thread than the xreator thread.
2331 * We cannot access to the socket if the thread is different.
2332 */
2333 if (socket->tid != tid)
2334 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2335
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002336 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002337 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002338 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002339 lua_pushinteger(L, -1);
2340 return 1;
2341 }
2342 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002343 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002344 s = si_strm(si);
2345
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002347 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002348 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 lua_pushinteger(L, -1);
2350 return 1;
2351 }
2352
2353 /* Update the input buffer data. */
2354 buf += sent;
2355 send_len = buf_len - sent;
2356
2357 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002358 if (sent >= buf_len) {
2359 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002360 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002361 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002363 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002364 * the request buffer if its not required.
2365 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002366 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002367 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002368 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002369 }
2370
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002371 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002372 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002373 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002375 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376
2377 /* send data */
2378 if (len < send_len)
2379 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002380 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002381
2382 /* "Not enough space" (-1), "Buffer too little to contain
2383 * the data" (-2) are not expected because the available length
2384 * is tested.
2385 * Other unknown error are also not expected.
2386 */
2387 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002388 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002389 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002390
sada05ed3302018-05-11 11:48:18 -07002391 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002392 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002393 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002394 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395 return 1;
2396 }
2397
2398 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002399 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002400
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002401 s->req.rex = TICK_ETERNITY;
2402 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002403
2404 /* Update length sent. */
2405 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002406 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407
2408 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002409 if (sent + len >= buf_len) {
2410 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002411 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002412 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002413
2414hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002415 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2416 xref_unlock(&socket->xref, peer);
2417 WILL_LJMP(luaL_error(L, "out of memory"));
2418 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002419 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002420 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421 return 0;
2422}
2423
2424/* This function initiate the send of data. It just check the input
2425 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002426 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002427 * "hlua_socket_write_yield" that can yield.
2428 *
2429 * The Lua function gets between 3 and 4 parameters. The first one is
2430 * the associated object. The second is a string buffer. The third is
2431 * a facultative integer that represents where is the buffer position
2432 * of the start of the data that can send. The first byte is the
2433 * position "1". The default value is "1". The fourth argument is a
2434 * facultative integer that represents where is the buffer position
2435 * of the end of the data that can send. The default is the last byte.
2436 */
2437static int hlua_socket_send(struct lua_State *L)
2438{
2439 int i;
2440 int j;
2441 const char *buf;
2442 size_t buf_len;
2443
2444 /* Check number of arguments. */
2445 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2446 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2447
2448 /* Get the string. */
2449 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2450
2451 /* Get and check j. */
2452 if (lua_gettop(L) == 4) {
2453 j = MAY_LJMP(luaL_checkinteger(L, 4));
2454 if (j < 0)
2455 j = buf_len + j + 1;
2456 if (j > buf_len)
2457 j = buf_len + 1;
2458 lua_pop(L, 1);
2459 }
2460 else
2461 j = buf_len;
2462
2463 /* Get and check i. */
2464 if (lua_gettop(L) == 3) {
2465 i = MAY_LJMP(luaL_checkinteger(L, 3));
2466 if (i < 0)
2467 i = buf_len + i + 1;
2468 if (i > buf_len)
2469 i = buf_len + 1;
2470 lua_pop(L, 1);
2471 } else
2472 i = 1;
2473
2474 /* Check bth i and j. */
2475 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002476 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002477 return 1;
2478 }
2479 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002480 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002481 return 1;
2482 }
2483 if (i == 0)
2484 i = 1;
2485 if (j == 0)
2486 j = 1;
2487
2488 /* Pop the string. */
2489 lua_pop(L, 1);
2490
2491 /* Update the buffer length. */
2492 buf += i - 1;
2493 buf_len = j - i + 1;
2494 lua_pushlstring(L, buf, buf_len);
2495
2496 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002497 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002498
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002499 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500}
2501
Willy Tarreau22b0a682015-06-17 19:43:49 +02002502#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002503__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002504{
2505 static char buffer[SOCKET_INFO_MAX_LEN];
2506 int ret;
2507 int len;
2508 char *p;
2509
2510 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2511 if (ret <= 0) {
2512 lua_pushnil(L);
2513 return 1;
2514 }
2515
2516 if (ret == AF_UNIX) {
2517 lua_pushstring(L, buffer+1);
2518 return 1;
2519 }
2520 else if (ret == AF_INET6) {
2521 buffer[0] = '[';
2522 len = strlen(buffer);
2523 buffer[len] = ']';
2524 len++;
2525 buffer[len] = ':';
2526 len++;
2527 p = buffer;
2528 }
2529 else if (ret == AF_INET) {
2530 p = buffer + 1;
2531 len = strlen(p);
2532 p[len] = ':';
2533 len++;
2534 }
2535 else {
2536 lua_pushnil(L);
2537 return 1;
2538 }
2539
2540 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2541 lua_pushnil(L);
2542 return 1;
2543 }
2544
2545 lua_pushstring(L, p);
2546 return 1;
2547}
2548
2549/* Returns information about the peer of the connection. */
2550__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2551{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002552 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002553 struct xref *peer;
2554 struct appctx *appctx;
2555 struct stream_interface *si;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002556 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002557 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002558
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002559 MAY_LJMP(check_args(L, 1, "getpeername"));
2560
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002561 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002562
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002563 /* Check if we run on the same thread than the xreator thread.
2564 * We cannot access to the socket if the thread is different.
2565 */
2566 if (socket->tid != tid)
2567 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2568
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002569 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002570 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002571 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002572 lua_pushnil(L);
2573 return 1;
2574 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002575 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002576 si = cs_si(appctx->owner);
Christopher Faulet16f16af2021-10-27 09:34:56 +02002577 dst = si_dst(si_opposite(si));
2578 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002579 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002580 lua_pushnil(L);
2581 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002582 }
2583
Christopher Faulet16f16af2021-10-27 09:34:56 +02002584 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002585 xref_unlock(&socket->xref, peer);
2586 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002587}
2588
2589/* Returns information about my connection side. */
2590static int hlua_socket_getsockname(struct lua_State *L)
2591{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002592 struct hlua_socket *socket;
2593 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002594 struct appctx *appctx;
2595 struct xref *peer;
2596 struct stream_interface *si;
2597 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002598 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002599
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002600 MAY_LJMP(check_args(L, 1, "getsockname"));
2601
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002602 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002603
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002604 /* Check if we run on the same thread than the xreator thread.
2605 * We cannot access to the socket if the thread is different.
2606 */
2607 if (socket->tid != tid)
2608 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2609
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002610 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002611 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002612 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002613 lua_pushnil(L);
2614 return 1;
2615 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002616 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002617 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002618 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002619
Christopher Faulet95a61e82021-12-22 14:22:03 +01002620 conn = cs_conn(s->csb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002621 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002622 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002623 lua_pushnil(L);
2624 return 1;
2625 }
2626
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002627 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002628 xref_unlock(&socket->xref, peer);
2629 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002630}
2631
2632/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002633static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634 .obj_type = OBJ_TYPE_APPLET,
2635 .name = "<LUA_TCP>",
2636 .fct = hlua_socket_handler,
2637 .release = hlua_socket_release,
2638};
2639
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002640__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002641{
2642 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002643 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002644 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002645 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002646 struct stream_interface *si;
2647 struct stream *s;
2648
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002649 /* Get hlua struct, or NULL if we execute from main lua state */
2650 hlua = hlua_gethlua(L);
2651 if (!hlua)
2652 return 0;
2653
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002654 /* Check if we run on the same thread than the xreator thread.
2655 * We cannot access to the socket if the thread is different.
2656 */
2657 if (socket->tid != tid)
2658 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2659
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002660 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002661 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002662 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002663 lua_pushnil(L);
2664 lua_pushstring(L, "Can't connect");
2665 return 2;
2666 }
2667 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002668 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002669 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002670
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002671 /* Check if we run on the same thread than the xreator thread.
2672 * We cannot access to the socket if the thread is different.
2673 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002674 if (socket->tid != tid) {
2675 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002676 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002677 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002678
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002679 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002680 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002681 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002682 lua_pushnil(L);
2683 lua_pushstring(L, "Can't connect");
2684 return 2;
2685 }
2686
Christopher Faulet95a61e82021-12-22 14:22:03 +01002687 appctx = cs_appctx(s->csf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002688
2689 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002690 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002691 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002692 lua_pushinteger(L, 1);
2693 return 1;
2694 }
2695
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002696 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2697 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002698 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002699 }
2700 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002701 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002702 return 0;
2703}
2704
2705/* This function fail or initite the connection. */
2706__LJMP static int hlua_socket_connect(struct lua_State *L)
2707{
2708 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002709 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002710 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002711 struct hlua *hlua;
2712 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002713 int low, high;
2714 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002715 struct xref *peer;
2716 struct stream_interface *si;
2717 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002718
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002719 if (lua_gettop(L) < 2)
2720 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002721
2722 /* Get args. */
2723 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002724
2725 /* Check if we run on the same thread than the xreator thread.
2726 * We cannot access to the socket if the thread is different.
2727 */
2728 if (socket->tid != tid)
2729 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2730
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002731 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002732 if (lua_gettop(L) >= 3) {
2733 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002734 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002735
Tim Duesterhus6edab862018-01-06 19:04:45 +01002736 /* Force the ip to end with a colon, to support IPv6 addresses
2737 * that are not enclosed within square brackets.
2738 */
2739 if (port > 0) {
2740 luaL_buffinit(L, &b);
2741 luaL_addstring(&b, ip);
2742 luaL_addchar(&b, ':');
2743 luaL_pushresult(&b);
2744 ip = lua_tolstring(L, lua_gettop(L), NULL);
2745 }
2746 }
2747
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002748 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002749 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002750 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002751 lua_pushnil(L);
2752 return 1;
2753 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002754
2755 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002756 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 +02002757 if (!addr) {
2758 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002759 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002760 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002761
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002762 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002763 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002764 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002765 if (port == -1) {
2766 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002767 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002768 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002769 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2770 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002771 if (port == -1) {
2772 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002773 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002774 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002775 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002776 }
2777 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002778
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002779 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002780 si = cs_si(appctx->owner);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002781 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002782
Christopher Faulet16f16af2021-10-27 09:34:56 +02002783 if (!sockaddr_alloc(&si_opposite(si)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002784 xref_unlock(&socket->xref, peer);
2785 WILL_LJMP(luaL_error(L, "connect: internal error"));
2786 }
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002787 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002788
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002789 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002790 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002791 if (!hlua)
2792 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002793
2794 /* inform the stream that we want to be notified whenever the
2795 * connection completes.
2796 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002797 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002798 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002799 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002800
Willy Tarreauf31af932020-01-14 09:59:38 +01002801 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002802
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002803 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2804 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002805 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002806 }
2807 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002808
2809 task_wakeup(s->task, TASK_WOKEN_INIT);
2810 /* Return yield waiting for connection. */
2811
Willy Tarreau9635e032018-10-16 17:52:55 +02002812 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002813
2814 return 0;
2815}
2816
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002817#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002818__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2819{
2820 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002821 struct xref *peer;
2822 struct appctx *appctx;
2823 struct stream_interface *si;
2824 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002825
2826 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2827 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002828
2829 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002830 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002831 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002832 lua_pushnil(L);
2833 return 1;
2834 }
2835 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002836 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002837 s = si_strm(si);
2838
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002839 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002840 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002841 return MAY_LJMP(hlua_socket_connect(L));
2842}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002843#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002844
2845__LJMP static int hlua_socket_setoption(struct lua_State *L)
2846{
2847 return 0;
2848}
2849
2850__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2851{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002852 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002853 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002854 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002855 struct xref *peer;
2856 struct appctx *appctx;
2857 struct stream_interface *si;
2858 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002859
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002860 MAY_LJMP(check_args(L, 2, "settimeout"));
2861
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002862 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002863
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002864 /* convert the timeout to millis */
2865 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002866
Thierry Fournier17a921b2018-03-08 09:59:02 +01002867 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002868 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002869 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2870
Mark Lakes56cc1252018-03-27 09:48:06 +02002871 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002872 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002873
2874 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002875 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002876 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002877
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002878 /* Check if we run on the same thread than the xreator thread.
2879 * We cannot access to the socket if the thread is different.
2880 */
2881 if (socket->tid != tid)
2882 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2883
Mark Lakes56cc1252018-03-27 09:48:06 +02002884 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002885 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002886 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002887 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2888 WILL_LJMP(lua_error(L));
2889 return 0;
2890 }
2891 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002892 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002893 s = si_strm(si);
2894
Cyril Bonté7bb63452018-08-17 23:51:02 +02002895 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002896 s->req.rto = tmout;
2897 s->req.wto = tmout;
2898 s->res.rto = tmout;
2899 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002900 s->req.rex = tick_add_ifset(now_ms, tmout);
2901 s->req.wex = tick_add_ifset(now_ms, tmout);
2902 s->res.rex = tick_add_ifset(now_ms, tmout);
2903 s->res.wex = tick_add_ifset(now_ms, tmout);
2904
2905 s->task->expire = tick_add_ifset(now_ms, tmout);
2906 task_queue(s->task);
2907
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002908 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002909
Thierry Fourniere9636f12018-03-08 09:54:32 +01002910 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002911 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002912}
2913
2914__LJMP static int hlua_socket_new(lua_State *L)
2915{
2916 struct hlua_socket *socket;
2917 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002918 struct session *sess;
Christopher Faulet13a35e52021-12-20 15:34:16 +01002919 struct conn_stream *cs;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002920 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002921
2922 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002923 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002924 hlua_pusherror(L, "socket: full stack");
2925 goto out_fail_conf;
2926 }
2927
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002928 /* Create the object: obj[0] = userdata. */
2929 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002930 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002931 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002932 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002933 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002934
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002935 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002936 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002937 hlua_pusherror(L, "socket: uninitialized pools.");
2938 goto out_fail_conf;
2939 }
2940
Willy Tarreau87b09662015-04-03 00:22:06 +02002941 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002942 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2943 lua_setmetatable(L, -2);
2944
Willy Tarreaud420a972015-04-06 00:39:18 +02002945 /* Create the applet context */
Willy Tarreaue6124462021-09-13 10:07:38 +02002946 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002947 if (!appctx) {
2948 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002949 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002950 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002951
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002952 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002953 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002954 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2955 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002956
Willy Tarreaud420a972015-04-06 00:39:18 +02002957 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002958 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002959 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002960 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet13a35e52021-12-20 15:34:16 +01002961 goto out_fail_appctx;
2962 }
2963
Christopher Fauletf835dea2021-12-21 14:35:17 +01002964 cs = cs_new(&appctx->obj_type, appctx, NULL, NULL, NULL);
Christopher Faulet13a35e52021-12-20 15:34:16 +01002965 if (!cs) {
2966 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002967 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002968 }
2969
Christopher Faulet13a35e52021-12-20 15:34:16 +01002970 strm = stream_new(sess, cs, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002971 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002972 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet13a35e52021-12-20 15:34:16 +01002973 goto out_fail_cs;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002974 }
2975
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002976 /* Initialise cross reference between stream and Lua socket object. */
2977 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002978
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002979 /* Configure "right" stream interface. this "si" is used to connect
2980 * and retrieve data from the server. The connection is initialized
2981 * with the "struct server".
2982 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002983 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002984
2985 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002986 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002987 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002988
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002989 return 1;
2990
Christopher Faulet13a35e52021-12-20 15:34:16 +01002991 out_fail_cs:
2992 cs_free(cs);
Willy Tarreaud420a972015-04-06 00:39:18 +02002993 out_fail_sess:
Christopher Faulet13a35e52021-12-20 15:34:16 +01002994 session_free(sess);
2995 out_fail_appctx:
Willy Tarreaud420a972015-04-06 00:39:18 +02002996 appctx_free(appctx);
2997 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998 WILL_LJMP(lua_error(L));
2999 return 0;
3000}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003001
3002/*
3003 *
3004 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003005 * Class Channel
3006 *
3007 *
3008 */
3009
3010/* Returns the struct hlua_channel join to the class channel in the
3011 * stack entry "ud" or throws an argument error.
3012 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003013__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003014{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003015 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003016}
3017
Willy Tarreau47860ed2015-03-10 14:07:50 +01003018/* Pushes the channel onto the top of the stack. If the stask does not have a
3019 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003020 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003021static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003022{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003023 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003024 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003025 return 0;
3026
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003027 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003028 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003029 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003030
3031 /* Pop a class sesison metatable and affect it to the userdata. */
3032 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3033 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003034 return 1;
3035}
3036
Christopher Faulet9f55a502020-02-25 15:21:02 +01003037/* Helper function returning a filter attached to a channel at the position <ud>
3038 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003039 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003040 * initialized.
3041 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003042static 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 +01003043{
3044 struct filter *filter = NULL;
3045
3046 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3047 struct hlua_flt_ctx *flt_ctx;
3048
3049 filter = lua_touserdata (L, -1);
3050 flt_ctx = filter->ctx;
3051 if (hlua_filter_from_payload(filter)) {
3052 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3053 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3054 }
3055 }
3056
3057 lua_pop(L, 1);
3058 return filter;
3059}
3060
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003061/* Copies <len> bytes of data present in the channel's buffer, starting at the
3062* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003063* responsibility to ensure <len> and <offset> are valid. It always return the
3064* length of the built string. <len> may be 0, in this case, an empty string is
3065* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003066*/
3067static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003068{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003069 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003070 luaL_Buffer b;
3071
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003072 block1 = len;
3073 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3074 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3075 block2 = len - block1;
3076
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003077 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003078 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3079 if (block2)
3080 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003081 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003082 return len;
3083}
3084
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003085/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3086 * function returns -1 if data cannot be copied. Otherwise, it returns the
3087 * number of bytes copied.
3088 */
3089static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3090{
3091 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003092
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003093 /* Nothing to do, just return */
3094 if (unlikely(istlen(str) == 0))
3095 goto end;
3096
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003097 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003098 ret = -1;
3099 goto end;
3100 }
3101 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3102
3103 end:
3104 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003105}
3106
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003107/* Removes <len> bytes of data at the absolute position <offset>.
3108 */
3109static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3110{
3111 size_t end = offset + len;
3112
3113 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3114 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3115 b_data(&chn->buf) - end, -len);
3116 b_sub(&chn->buf, len);
3117}
3118
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003119/* Copies input data in the channel's buffer. It is possible to set a specific
3120 * offset (0 by default) and a length (all remaining input data starting for the
3121 * offset by default). If there is not enough input data and more data can be
3122 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003123 *
3124 * From an action, All input data are considered. For a filter, the offset and
3125 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003126 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003127__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003128{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003129 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003130 struct filter *filter;
3131 size_t input, output;
3132 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003133
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003134 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003135
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003136 output = co_data(chn);
3137 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003138
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003139 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3140 if (filter && !hlua_filter_from_payload(filter))
3141 WILL_LJMP(lua_error(L));
3142
3143 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003144 if (lua_gettop(L) > 1) {
3145 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3146 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003147 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003148 offset += output;
3149 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003150 lua_pushfstring(L, "offset out of range.");
3151 WILL_LJMP(lua_error(L));
3152 }
3153 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003154 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003155 if (lua_gettop(L) == 3) {
3156 len = MAY_LJMP(luaL_checkinteger(L, 3));
3157 if (!len)
3158 goto dup;
3159 if (len == -1)
3160 len = global.tune.bufsize;
3161 if (len < 0) {
3162 lua_pushfstring(L, "length out of range.");
3163 WILL_LJMP(lua_error(L));
3164 }
3165 }
3166
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003167 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003168 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3169 /* Yield waiting for more data, as requested */
3170 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3171 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003172 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003173 }
3174
3175 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003176 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003177 return 1;
3178}
3179
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003180/* Copies the first line (including the trailing LF) of input data in the
3181 * channel's buffer. It is possible to set a specific offset (0 by default) and
3182 * a length (all remaining input data starting for the offset by default). If
3183 * there is not enough input data and more data can be received, the function
3184 * yields. If a length is explicitly specified, no more data are
3185 * copied. Otherwise, if no LF is found and more data can be received, this
3186 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003187 *
3188 * From an action, All input data are considered. For a filter, the offset and
3189 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003190 */
3191__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003192{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003193 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003194 struct filter *filter;
3195 size_t l, input, output;
3196 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003197
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003198 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003199 output = co_data(chn);
3200 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003201
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003202 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3203 if (filter && !hlua_filter_from_payload(filter))
3204 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003205
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003206 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003207 if (lua_gettop(L) > 1) {
3208 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3209 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003210 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003211 offset += output;
3212 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003213 lua_pushfstring(L, "offset out of range.");
3214 WILL_LJMP(lua_error(L));
3215 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003216 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003217
3218 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003219 if (lua_gettop(L) == 3) {
3220 len = MAY_LJMP(luaL_checkinteger(L, 3));
3221 if (!len)
3222 goto dup;
3223 if (len == -1)
3224 len = global.tune.bufsize;
3225 if (len < 0) {
3226 lua_pushfstring(L, "length out of range.");
3227 WILL_LJMP(lua_error(L));
3228 }
3229 }
3230
3231 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003232 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003233 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003234 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003235 len = l+1;
3236 goto dup;
3237 }
3238 }
3239
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003240 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003241 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3242 /* Yield waiting for more data */
3243 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3244 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003245 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003246 }
3247
3248 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003249 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003250 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003251}
3252
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003253/* [ DEPRECATED ]
3254 *
3255 * Duplicate all input data foud in the channel's buffer. The data are not
3256 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003257 *
3258 * From an action, All input data are considered. For a filter, the offset and
3259 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003260 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003261__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003262{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003263 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003264 struct filter *filter;
3265 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003266
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003267 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003268 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003269 if (IS_HTX_STRM(chn_strm(chn))) {
3270 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3271 WILL_LJMP(lua_error(L));
3272 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003273
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003274 offset = co_data(chn);
3275 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003276
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003277 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3278 if (filter && !hlua_filter_from_payload(filter))
3279 WILL_LJMP(lua_error(L));
3280
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003281 if (!ci_data(chn) && channel_input_closed(chn)) {
3282 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003283 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003284 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003285
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003286 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003287 return 1;
3288}
3289
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003290/* [ DEPRECATED ]
3291 *
3292 * Get all input data foud in the channel's buffer. The data are removed from
3293 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3294 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003295 *
3296 * From an action, All input data are considered. For a filter, the offset and
3297 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003298 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003299__LJMP static int hlua_channel_get(lua_State *L)
3300{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003301 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003302 struct filter *filter;
3303 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003304 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003305
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003306 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003307 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3308 if (IS_HTX_STRM(chn_strm(chn))) {
3309 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3310 WILL_LJMP(lua_error(L));
3311 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003312
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003313 offset = co_data(chn);
3314 len = ci_data(chn);
3315
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003316 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3317 if (filter && !hlua_filter_from_payload(filter))
3318 WILL_LJMP(lua_error(L));
3319
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003320 if (!ci_data(chn) && channel_input_closed(chn)) {
3321 lua_pushnil(L);
3322 return 1;
3323 }
3324
3325 ret = _hlua_channel_dup(chn, L, offset, len);
3326 _hlua_channel_delete(chn, offset, ret);
3327 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003328}
3329
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003330/* This functions consumes and returns one line. If the channel is closed,
3331 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003332 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003333 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003334 *
3335 * From an action, All input data are considered. For a filter, the offset and
3336 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003337 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003338__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003339{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003340 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003341 struct filter *filter;
3342 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003343 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003344
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003345 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003346
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003347 offset = co_data(chn);
3348 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003349
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003350 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3351 if (filter && !hlua_filter_from_payload(filter))
3352 WILL_LJMP(lua_error(L));
3353
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003354 if (!ci_data(chn) && channel_input_closed(chn)) {
3355 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003356 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003357 }
3358
3359 for (l = 0; l < len; l++) {
3360 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3361 len = l+1;
3362 goto dup;
3363 }
3364 }
3365
3366 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3367 /* Yield waiting for more data */
3368 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3369 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003370
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003371 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003372 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003373 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003374 return 1;
3375}
3376
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003377/* [ DEPRECATED ]
3378 *
3379 * Check arguments for the function "hlua_channel_getline_yield".
3380 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003381__LJMP static int hlua_channel_getline(lua_State *L)
3382{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003383 struct channel *chn;
3384
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003385 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003386 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3387 if (IS_HTX_STRM(chn_strm(chn))) {
3388 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3389 WILL_LJMP(lua_error(L));
3390 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003391 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3392}
3393
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003394/* Retrieves a given amount of input data at the given offset. By default all
3395 * available input data are returned. The offset may be negactive to start from
3396 * the end of input data. The length may be -1 to set it to the maximum buffer
3397 * size.
3398 */
3399__LJMP static int hlua_channel_get_data(lua_State *L)
3400{
3401 struct channel *chn;
3402
3403 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3404 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3405 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3406 if (IS_HTX_STRM(chn_strm(chn))) {
3407 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3408 WILL_LJMP(lua_error(L));
3409 }
3410 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3411}
3412
3413/* Retrieves a given amount of input data at the given offset. By default all
3414 * available input data are returned. The offset may be negactive to start from
3415 * the end of input data. The length may be -1 to set it to the maximum buffer
3416 * size.
3417 */
3418__LJMP static int hlua_channel_get_line(lua_State *L)
3419{
3420 struct channel *chn;
3421
3422 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3423 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3424 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3425 if (IS_HTX_STRM(chn_strm(chn))) {
3426 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3427 WILL_LJMP(lua_error(L));
3428 }
3429 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3430}
3431
3432/* Appends a string into the input side of channel. It returns the length of the
3433 * written string, or -1 if the channel is closed or if the buffer size is too
3434 * little for the data. 0 may be returned if nothing is copied. This function
3435 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003436 *
3437 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003438 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003439__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003440{
Christopher Faulet23976d92021-08-06 09:59:49 +02003441 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003442 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003443 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003444 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003445 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003446
3447 MAY_LJMP(check_args(L, 2, "append"));
3448 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003449 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003450 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003451 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003452 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003453 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003454
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003455 offset = co_data(chn);
3456 len = ci_data(chn);
3457
3458 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3459 if (filter && !hlua_filter_from_payload(filter))
3460 WILL_LJMP(lua_error(L));
3461
3462 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3463 if (ret > 0 && filter) {
3464 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3465
3466 flt_update_offsets(filter, chn, ret);
3467 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3468 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003469 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003470 return 1;
3471}
3472
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003473/* Prepends a string into the input side of channel. It returns the length of the
3474 * written string, or -1 if the channel is closed or if the buffer size is too
3475 * little for the data. 0 may be returned if nothing is copied. This function
3476 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003477 *
3478 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003479 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003480__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003481{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003482 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003483 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003484 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003485 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003486 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003487
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003488 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003489 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003490 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3491 if (IS_HTX_STRM(chn_strm(chn))) {
3492 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3493 WILL_LJMP(lua_error(L));
3494 }
3495
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003496 offset = co_data(chn);
3497 len = ci_data(chn);
3498
3499 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3500 if (filter && !hlua_filter_from_payload(filter))
3501 WILL_LJMP(lua_error(L));
3502
3503 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3504 if (ret > 0 && filter) {
3505 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3506
3507 flt_update_offsets(filter, chn, ret);
3508 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3509 }
3510
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003511 lua_pushinteger(L, ret);
3512 return 1;
3513}
3514
3515/* Inserts a given amount of input data at the given offset by a string
3516 * content. By default the string is appended at the end of input data. It
3517 * returns the length of the written string, or -1 if the channel is closed or
3518 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003519 *
3520 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003521 */
3522__LJMP static int hlua_channel_insert_data(lua_State *L)
3523{
3524 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003525 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003526 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003527 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003528 int ret, offset;
3529
3530 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3531 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3532 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3533 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003534
3535 output = co_data(chn);
3536 input = ci_data(chn);
3537
3538 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3539 if (filter && !hlua_filter_from_payload(filter))
3540 WILL_LJMP(lua_error(L));
3541
3542 offset = input + output;
3543 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003544 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003545 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003546 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003547 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003548 if (offset < output || offset > output + input) {
3549 lua_pushfstring(L, "offset out of range.");
3550 WILL_LJMP(lua_error(L));
3551 }
3552 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003553 if (IS_HTX_STRM(chn_strm(chn))) {
3554 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3555 WILL_LJMP(lua_error(L));
3556 }
3557
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003558 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3559 if (ret > 0 && filter) {
3560 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003561
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003562 flt_update_offsets(filter, chn, ret);
3563 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003564 }
3565
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566 lua_pushinteger(L, ret);
3567 return 1;
3568}
3569/* Replaces a given amount of input data at the given offset by a string
3570 * content. By default all remaining data are removed (offset = 0 and len =
3571 * -1). It returns the length of the written string, or -1 if the channel is
3572 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003573 *
3574 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003575 */
3576__LJMP static int hlua_channel_set_data(lua_State *L)
3577{
3578 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003579 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003580 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003581 size_t sz, input, output;
3582 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003583
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003584 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3585 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3586 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3587 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003588
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003589 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003590 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003591 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003592 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003593
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003594 output = co_data(chn);
3595 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003596
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003597 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3598 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003600
3601 offset = output;
3602 if (lua_gettop(L) > 2) {
3603 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3604 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003605 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003606 offset += output;
3607 if (offset < output || offset > input + output) {
3608 lua_pushfstring(L, "offset out of range.");
3609 WILL_LJMP(lua_error(L));
3610 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003611 }
3612
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003613 len = output + input - offset;
3614 if (lua_gettop(L) == 4) {
3615 len = MAY_LJMP(luaL_checkinteger(L, 4));
3616 if (!len)
3617 goto set;
3618 if (len == -1)
3619 len = output + input - offset;
3620 if (len < 0 || offset + len > output + input) {
3621 lua_pushfstring(L, "length out of range.");
3622 WILL_LJMP(lua_error(L));
3623 }
3624 }
3625
3626 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003627 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003628 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003629 lua_pushinteger(L, -1);
3630 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003631 _hlua_channel_delete(chn, offset, len);
3632 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3633 if (filter) {
3634 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3635
3636 len -= (ret > 0 ? ret : 0);
3637 flt_update_offsets(filter, chn, -len);
3638 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3639 }
3640
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003641 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003642 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003643 return 1;
3644}
3645
3646/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003647 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003648 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003649 *
3650 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003651 */
3652__LJMP static int hlua_channel_del_data(lua_State *L)
3653{
3654 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003655 struct filter *filter;
3656 size_t input, output;
3657 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003658
3659 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3660 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3661 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003662
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003663 if (IS_HTX_STRM(chn_strm(chn))) {
3664 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3665 WILL_LJMP(lua_error(L));
3666 }
3667
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003668 output = co_data(chn);
3669 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003670
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003671 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3672 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003673 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003674
3675 offset = output;
3676 if (lua_gettop(L) > 2) {
3677 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3678 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003679 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003680 offset += output;
3681 if (offset < output || offset > input + output) {
3682 lua_pushfstring(L, "offset out of range.");
3683 WILL_LJMP(lua_error(L));
3684 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003685 }
3686
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003687 len = output + input - offset;
3688 if (lua_gettop(L) == 4) {
3689 len = MAY_LJMP(luaL_checkinteger(L, 4));
3690 if (!len)
3691 goto end;
3692 if (len == -1)
3693 len = output + input - offset;
3694 if (len < 0 || offset + len > output + input) {
3695 lua_pushfstring(L, "length out of range.");
3696 WILL_LJMP(lua_error(L));
3697 }
3698 }
3699
3700 _hlua_channel_delete(chn, offset, len);
3701 if (filter) {
3702 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3703
3704 flt_update_offsets(filter, chn, -len);
3705 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3706 }
3707
3708 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003709 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003710 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003711}
3712
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003713/* Append data in the output side of the buffer. This data is immediately
3714 * sent. The function returns the amount of data written. If the buffer
3715 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003716 * if the channel is closed.
3717 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003718__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003719{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003720 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003721 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003722 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003723 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003724 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003725 struct hlua *hlua;
3726
3727 /* Get hlua struct, or NULL if we execute from main lua state */
3728 hlua = hlua_gethlua(L);
3729 if (!hlua) {
3730 lua_pushnil(L);
3731 return 1;
3732 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003733
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003734 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3735 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3736 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003737
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003738 offset = co_data(chn);
3739 len = ci_data(chn);
3740
3741 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3742 if (filter && !hlua_filter_from_payload(filter))
3743 WILL_LJMP(lua_error(L));
3744
3745
Willy Tarreau47860ed2015-03-10 14:07:50 +01003746 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003747 lua_pushinteger(L, -1);
3748 return 1;
3749 }
3750
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003751 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003752 if (len > sz -l) {
3753 if (filter) {
3754 lua_pushinteger(L, -1);
3755 return 1;
3756 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003757 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003759
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003760 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003761 if (ret == -1) {
3762 lua_pop(L, 1);
3763 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003764 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003765 }
3766 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003767 if (filter) {
3768 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3769
3770
3771 flt_update_offsets(filter, chn, ret);
3772 FLT_OFF(filter, chn) += ret;
3773 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3774 }
3775 else
3776 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003777
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003778 l += ret;
3779 lua_pop(L, 1);
3780 lua_pushinteger(L, l);
3781 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003782
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003783 if (l < sz) {
3784 /* Yield only if the channel's output is not empty.
3785 * Otherwise it means we cannot add more data. */
3786 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003787 return 1;
3788
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003789 /* If we are waiting for space in the response buffer, we
3790 * must set the flag WAKERESWR. This flag required the task
3791 * wake up if any activity is detected on the response buffer.
3792 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003793 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003794 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003795 else
3796 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003797 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003798 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003799
3800 return 1;
3801}
3802
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003803/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003804 * yield the LUA process, and resume it without checking the
3805 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003806 *
3807 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003808 */
3809__LJMP static int hlua_channel_send(lua_State *L)
3810{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003811 struct channel *chn;
3812
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003813 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003814 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3815 if (IS_HTX_STRM(chn_strm(chn))) {
3816 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3817 WILL_LJMP(lua_error(L));
3818 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003819 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003820 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003821}
3822
3823/* This function forward and amount of butes. The data pass from
3824 * the input side of the buffer to the output side, and can be
3825 * forwarded. This function never fails.
3826 *
3827 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003828 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003829 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003830__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003831{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003832 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003833 struct filter *filter;
3834 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003835 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003836 struct hlua *hlua;
3837
3838 /* Get hlua struct, or NULL if we execute from main lua state */
3839 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003840 if (!hlua) {
3841 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003842 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003843 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003844
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003845 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003846 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003847 l = MAY_LJMP(luaL_checkinteger(L, -1));
3848
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003849 offset = co_data(chn);
3850 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003851
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003852 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3853 if (filter && !hlua_filter_from_payload(filter))
3854 WILL_LJMP(lua_error(L));
3855
3856 max = fwd - l;
3857 if (max > len)
3858 max = len;
3859
3860 if (filter) {
3861 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3862
3863 FLT_OFF(filter, chn) += max;
3864 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3865 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3866 }
3867 else
3868 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003869
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003870 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003871 lua_pop(L, 1);
3872 lua_pushinteger(L, l);
3873
3874 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003875 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003876 /* The the input channel or the output channel are closed, we
3877 * must return the amount of data forwarded.
3878 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003879 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003880 return 1;
3881
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003882 /* If we are waiting for space data in the response buffer, we
3883 * must set the flag WAKERESWR. This flag required the task
3884 * wake up if any activity is detected on the response buffer.
3885 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003886 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003887 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003888 else
3889 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003890
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003891 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003892 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003893 }
3894
3895 return 1;
3896}
3897
3898/* Just check the input and prepare the stack for the previous
3899 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003900 *
3901 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003902 */
3903__LJMP static int hlua_channel_forward(lua_State *L)
3904{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003905 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003906
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003907 MAY_LJMP(check_args(L, 2, "forward"));
3908 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3909 if (IS_HTX_STRM(chn_strm(chn))) {
3910 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3911 WILL_LJMP(lua_error(L));
3912 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003913 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003914 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003915}
3916
3917/* Just returns the number of bytes available in the input
3918 * side of the buffer. This function never fails.
3919 */
3920__LJMP static int hlua_channel_get_in_len(lua_State *L)
3921{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003922 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003923 struct filter *filter;
3924 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003925
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003926 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003927 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003928
3929 output = co_data(chn);
3930 input = ci_data(chn);
3931 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3932 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3933 lua_pushinteger(L, input);
3934 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003935 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003936
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003937 lua_pushinteger(L, htx->data - co_data(chn));
3938 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003939 return 1;
3940}
3941
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003942/* Returns true if the channel is full. */
3943__LJMP static int hlua_channel_is_full(lua_State *L)
3944{
3945 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003946
3947 MAY_LJMP(check_args(L, 1, "is_full"));
3948 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003949 /* ignore the reserve, we are not on a producer side (ie in an
3950 * applet).
3951 */
3952 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003953 return 1;
3954}
3955
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003956/* Returns true if the channel may still receive data. */
3957__LJMP static int hlua_channel_may_recv(lua_State *L)
3958{
3959 struct channel *chn;
3960
3961 MAY_LJMP(check_args(L, 1, "may_recv"));
3962 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3963 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3964 return 1;
3965}
3966
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003967/* Returns true if the channel is the response channel. */
3968__LJMP static int hlua_channel_is_resp(lua_State *L)
3969{
3970 struct channel *chn;
3971
3972 MAY_LJMP(check_args(L, 1, "is_resp"));
3973 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3974
3975 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3976 return 1;
3977}
3978
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003979/* Just returns the number of bytes available in the output
3980 * side of the buffer. This function never fails.
3981 */
3982__LJMP static int hlua_channel_get_out_len(lua_State *L)
3983{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003984 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003985 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003986
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003987 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003988 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003989
3990 output = co_data(chn);
3991 input = ci_data(chn);
3992 hlua_channel_filter(L, 1, chn, &output, &input);
3993
3994 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003995 return 1;
3996}
3997
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003998/*
3999 *
4000 *
4001 * Class Fetches
4002 *
4003 *
4004 */
4005
4006/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004007 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004008 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004009__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004010{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004011 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004012}
4013
4014/* This function creates and push in the stack a fetch object according
4015 * with a current TXN.
4016 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004017static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004018{
Willy Tarreau7073c472015-04-06 11:15:40 +02004019 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004020
4021 /* Check stack size. */
4022 if (!lua_checkstack(L, 3))
4023 return 0;
4024
4025 /* Create the object: obj[0] = userdata.
4026 * Note that the base of the Fetches object is the
4027 * transaction object.
4028 */
4029 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004030 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004031 lua_rawseti(L, -2, 0);
4032
Willy Tarreau7073c472015-04-06 11:15:40 +02004033 hsmp->s = txn->s;
4034 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004035 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004036 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004037
4038 /* Pop a class sesison metatable and affect it to the userdata. */
4039 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4040 lua_setmetatable(L, -2);
4041
4042 return 1;
4043}
4044
4045/* This function is an LUA binding. It is called with each sample-fetch.
4046 * It uses closure argument to store the associated sample-fetch. It
4047 * returns only one argument or throws an error. An error is thrown
4048 * only if an error is encountered during the argument parsing. If
4049 * the "sample-fetch" function fails, nil is returned.
4050 */
4051__LJMP static int hlua_run_sample_fetch(lua_State *L)
4052{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004053 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004054 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004055 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004056 int i;
4057 struct sample smp;
4058
4059 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004060 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004061
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004062 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004063 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004064
Thierry FOURNIERca988662015-12-20 18:43:03 +01004065 /* Check execution authorization. */
4066 if (f->use & SMP_USE_HTTP_ANY &&
4067 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4068 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4069 "is not available in Lua services", f->kw);
4070 WILL_LJMP(lua_error(L));
4071 }
4072
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004073 /* Get extra arguments. */
4074 for (i = 0; i < lua_gettop(L) - 1; i++) {
4075 if (i >= ARGM_NBARGS)
4076 break;
4077 hlua_lua2arg(L, i + 2, &args[i]);
4078 }
4079 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004080 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004081
4082 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004083 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004084
4085 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004086 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004087 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004088 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004089 }
4090
4091 /* Initialise the sample. */
4092 memset(&smp, 0, sizeof(smp));
4093
4094 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004095 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004096 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004097 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004098 lua_pushstring(L, "");
4099 else
4100 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004101 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004102 }
4103
4104 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004105 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004106 hlua_smp2lua_str(L, &smp);
4107 else
4108 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004109
4110 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004111 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004112 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004113
4114 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004115 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004116 WILL_LJMP(lua_error(L));
4117 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004118}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004119
4120/*
4121 *
4122 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004123 * Class Converters
4124 *
4125 *
4126 */
4127
4128/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004129 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004130 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004131__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004132{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004133 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004134}
4135
4136/* This function creates and push in the stack a Converters object
4137 * according with a current TXN.
4138 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004139static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004140{
Willy Tarreau7073c472015-04-06 11:15:40 +02004141 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004142
4143 /* Check stack size. */
4144 if (!lua_checkstack(L, 3))
4145 return 0;
4146
4147 /* Create the object: obj[0] = userdata.
4148 * Note that the base of the Converters object is the
4149 * same than the TXN object.
4150 */
4151 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004152 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004153 lua_rawseti(L, -2, 0);
4154
Willy Tarreau7073c472015-04-06 11:15:40 +02004155 hsmp->s = txn->s;
4156 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004157 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004158 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004159
Willy Tarreau87b09662015-04-03 00:22:06 +02004160 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004161 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4162 lua_setmetatable(L, -2);
4163
4164 return 1;
4165}
4166
4167/* This function is an LUA binding. It is called with each converter.
4168 * It uses closure argument to store the associated converter. It
4169 * returns only one argument or throws an error. An error is thrown
4170 * only if an error is encountered during the argument parsing. If
4171 * the converter function function fails, nil is returned.
4172 */
4173__LJMP static int hlua_run_sample_conv(lua_State *L)
4174{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004175 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004176 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004177 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004178 int i;
4179 struct sample smp;
4180
4181 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004182 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004183
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004184 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004185 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004186
4187 /* Get extra arguments. */
4188 for (i = 0; i < lua_gettop(L) - 2; i++) {
4189 if (i >= ARGM_NBARGS)
4190 break;
4191 hlua_lua2arg(L, i + 3, &args[i]);
4192 }
4193 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004194 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004195
4196 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004197 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004198
4199 /* Run the special args checker. */
4200 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4201 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004202 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004203 }
4204
4205 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004206 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004207 if (!hlua_lua2smp(L, 2, &smp)) {
4208 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004209 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210 }
4211
Willy Tarreau1777ea62016-03-10 16:15:46 +01004212 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4213
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004214 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004215 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004216 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004217 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004218 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004219 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004220 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4221 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004222 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004223 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004224 }
4225
4226 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004227 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004228 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004229 lua_pushstring(L, "");
4230 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004231 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004232 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004233 }
4234
4235 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004236 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004237 hlua_smp2lua_str(L, &smp);
4238 else
4239 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004240 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004241 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004242 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004243
4244 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004245 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004246 WILL_LJMP(lua_error(L));
4247 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004248}
4249
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004250/*
4251 *
4252 *
4253 * Class AppletTCP
4254 *
4255 *
4256 */
4257
4258/* Returns a struct hlua_txn if the stack entry "ud" is
4259 * a class stream, otherwise it throws an error.
4260 */
4261__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4262{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004263 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004264}
4265
4266/* This function creates and push in the stack an Applet object
4267 * according with a current TXN.
4268 */
4269static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4270{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004271 struct hlua_appctx *luactx;
Christopher Faulet86e1c332021-12-20 17:09:39 +01004272 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004273 struct stream *s = si_strm(si);
4274 struct proxy *p = s->be;
4275
4276 /* Check stack size. */
4277 if (!lua_checkstack(L, 3))
4278 return 0;
4279
4280 /* Create the object: obj[0] = userdata.
4281 * Note that the base of the Converters object is the
4282 * same than the TXN object.
4283 */
4284 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004285 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004286 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004287 luactx->appctx = ctx;
4288 luactx->htxn.s = s;
4289 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004290
4291 /* Create the "f" field that contains a list of fetches. */
4292 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004293 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004294 return 0;
4295 lua_settable(L, -3);
4296
4297 /* Create the "sf" field that contains a list of stringsafe fetches. */
4298 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004299 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004300 return 0;
4301 lua_settable(L, -3);
4302
4303 /* Create the "c" field that contains a list of converters. */
4304 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004305 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004306 return 0;
4307 lua_settable(L, -3);
4308
4309 /* Create the "sc" field that contains a list of stringsafe converters. */
4310 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004311 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004312 return 0;
4313 lua_settable(L, -3);
4314
4315 /* Pop a class stream metatable and affect it to the table. */
4316 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4317 lua_setmetatable(L, -2);
4318
4319 return 1;
4320}
4321
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004322__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4323{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004324 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004325 struct stream *s;
4326 const char *name;
4327 size_t len;
4328 struct sample smp;
4329
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004330 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4331 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004332
4333 /* It is useles to retrieve the stream, but this function
4334 * runs only in a stream context.
4335 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004336 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004337 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004338 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004339
4340 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004341 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004342 hlua_lua2smp(L, 3, &smp);
4343
4344 /* Store the sample in a variable. */
4345 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004346
4347 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4348 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4349 else
4350 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4351
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004352 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004353}
4354
4355__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4356{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004357 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004358 struct stream *s;
4359 const char *name;
4360 size_t len;
4361 struct sample smp;
4362
4363 MAY_LJMP(check_args(L, 2, "unset_var"));
4364
4365 /* It is useles to retrieve the stream, but this function
4366 * runs only in a stream context.
4367 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004368 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004369 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004370 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004371
4372 /* Unset the variable. */
4373 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004374 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4375 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004376}
4377
4378__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4379{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004380 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004381 struct stream *s;
4382 const char *name;
4383 size_t len;
4384 struct sample smp;
4385
4386 MAY_LJMP(check_args(L, 2, "get_var"));
4387
4388 /* It is useles to retrieve the stream, but this function
4389 * runs only in a stream context.
4390 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004391 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004392 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004393 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004394
4395 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004396 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004397 lua_pushnil(L);
4398 return 1;
4399 }
4400
4401 return hlua_smp2lua(L, &smp);
4402}
4403
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004404__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4405{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004406 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4407 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004408 struct hlua *hlua;
4409
4410 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004411 if (!s->hlua)
4412 return 0;
4413 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004414
4415 MAY_LJMP(check_args(L, 2, "set_priv"));
4416
4417 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004418 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004419
4420 /* Get and store new value. */
4421 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4422 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4423
4424 return 0;
4425}
4426
4427__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4428{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004429 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4430 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004431 struct hlua *hlua;
4432
4433 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004434 if (!s->hlua) {
4435 lua_pushnil(L);
4436 return 1;
4437 }
4438 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004439
4440 /* Push configuration index in the stack. */
4441 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4442
4443 return 1;
4444}
4445
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004446/* If expected data not yet available, it returns a yield. This function
4447 * consumes the data in the buffer. It returns a string containing the
4448 * data. This string can be empty.
4449 */
4450__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4451{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004452 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004453 struct stream_interface *si = cs_si(luactx->appctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004454 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004455 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004456 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004457 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004458 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004459
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004460 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004461 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004462
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004463 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004464 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004465 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004466 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004467 }
4468
4469 /* End of data: commit the total strings and return. */
4470 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004471 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004472 return 1;
4473 }
4474
4475 /* Ensure that the block 2 length is usable. */
4476 if (ret == 1)
4477 len2 = 0;
4478
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004479 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004480 luaL_addlstring(&luactx->b, blk1, len1);
4481 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004482
4483 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004484 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004485 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004486 return 1;
4487}
4488
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004489/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004490__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4491{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004492 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004493
4494 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004495 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004496
4497 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4498}
4499
4500/* If expected data not yet available, it returns a yield. This function
4501 * consumes the data in the buffer. It returns a string containing the
4502 * data. This string can be empty.
4503 */
4504__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4505{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004506 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004507 struct stream_interface *si = cs_si(luactx->appctx->owner);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004508 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004509 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004510 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004511 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004512 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004513 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004514
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004515 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004516 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004517
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004518 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004519 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004520 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004521 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004522 }
4523
4524 /* End of data: commit the total strings and return. */
4525 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004526 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004527 return 1;
4528 }
4529
4530 /* Ensure that the block 2 length is usable. */
4531 if (ret == 1)
4532 len2 = 0;
4533
4534 if (len == -1) {
4535
4536 /* If len == -1, catenate all the data avalaile and
4537 * yield because we want to get all the data until
4538 * the end of data stream.
4539 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004540 luaL_addlstring(&luactx->b, blk1, len1);
4541 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004542 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004543 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004544 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004545
4546 } else {
4547
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004548 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004549 if (len1 > len)
4550 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004551 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004552 len -= len1;
4553
4554 /* Copy the second block. */
4555 if (len2 > len)
4556 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004557 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004558 len -= len2;
4559
4560 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004561 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004562
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004563 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004564 if (len > 0) {
4565 lua_pushinteger(L, len);
4566 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004567 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004568 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004569 }
4570
4571 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004572 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004573 return 1;
4574 }
4575
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004576 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004577 hlua_pusherror(L, "Lua: internal error");
4578 WILL_LJMP(lua_error(L));
4579 return 0;
4580}
4581
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004582/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004583__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4584{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004585 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004586 int len = -1;
4587
4588 if (lua_gettop(L) > 2)
4589 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4590 if (lua_gettop(L) >= 2) {
4591 len = MAY_LJMP(luaL_checkinteger(L, 2));
4592 lua_pop(L, 1);
4593 }
4594
4595 /* Confirm or set the required length */
4596 lua_pushinteger(L, len);
4597
4598 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004599 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004600
4601 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4602}
4603
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004604/* Append data in the output side of the buffer. This data is immediately
4605 * sent. The function returns the amount of data written. If the buffer
4606 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607 * if the channel is closed.
4608 */
4609__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4610{
4611 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004612 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004613 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4614 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004615 struct stream_interface *si = cs_si(luactx->appctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004616 struct channel *chn = si_ic(si);
4617 int max;
4618
4619 /* Get the max amount of data which can write as input in the channel. */
4620 max = channel_recv_max(chn);
4621 if (max > (len - l))
4622 max = len - l;
4623
4624 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004625 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004626
4627 /* update counters. */
4628 l += max;
4629 lua_pop(L, 1);
4630 lua_pushinteger(L, l);
4631
4632 /* If some data is not send, declares the situation to the
4633 * applet, and returns a yield.
4634 */
4635 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004636 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004637 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004638 }
4639
4640 return 1;
4641}
4642
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004643/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004644 * yield the LUA process, and resume it without checking the
4645 * input arguments.
4646 */
4647__LJMP static int hlua_applet_tcp_send(lua_State *L)
4648{
4649 MAY_LJMP(check_args(L, 2, "send"));
4650 lua_pushinteger(L, 0);
4651
4652 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4653}
4654
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004655/*
4656 *
4657 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004658 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004659 *
4660 *
4661 */
4662
4663/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004664 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004665 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004666__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004667{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004668 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004669}
4670
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004671/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004672 * according with a current TXN.
4673 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004674static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004675{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004676 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004677 struct hlua_txn htxn;
Christopher Faulet86e1c332021-12-20 17:09:39 +01004678 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004679 struct stream *s = si_strm(si);
4680 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004681 struct htx *htx;
4682 struct htx_blk *blk;
4683 struct htx_sl *sl;
4684 struct ist path;
4685 unsigned long long len = 0;
4686 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004687 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004688
4689 /* Check stack size. */
4690 if (!lua_checkstack(L, 3))
4691 return 0;
4692
4693 /* Create the object: obj[0] = userdata.
4694 * Note that the base of the Converters object is the
4695 * same than the TXN object.
4696 */
4697 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004698 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004699 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004700 luactx->appctx = ctx;
4701 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4702 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4703 luactx->htxn.s = s;
4704 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004705
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004706 /* Create the "f" field that contains a list of fetches. */
4707 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004708 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004709 return 0;
4710 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004711
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004712 /* Create the "sf" field that contains a list of stringsafe fetches. */
4713 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004714 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004715 return 0;
4716 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004717
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004718 /* Create the "c" field that contains a list of converters. */
4719 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004720 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004721 return 0;
4722 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004723
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004724 /* Create the "sc" field that contains a list of stringsafe converters. */
4725 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004726 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004727 return 0;
4728 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004729
Christopher Fauleta2097962019-07-15 16:25:33 +02004730 htx = htxbuf(&s->req.buf);
4731 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004732 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004733 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004734
Christopher Fauleta2097962019-07-15 16:25:33 +02004735 /* Stores the request method. */
4736 lua_pushstring(L, "method");
4737 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4738 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004739
Christopher Fauleta2097962019-07-15 16:25:33 +02004740 /* Stores the http version. */
4741 lua_pushstring(L, "version");
4742 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4743 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004744
Christopher Fauleta2097962019-07-15 16:25:33 +02004745 /* creates an array of headers. hlua_http_get_headers() crates and push
4746 * the array on the top of the stack.
4747 */
4748 lua_pushstring(L, "headers");
4749 htxn.s = s;
4750 htxn.p = px;
4751 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004752 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004753 return 0;
4754 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004755
Amaury Denoyellec453f952021-07-06 11:40:12 +02004756 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4757 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004758 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004759 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004760
Christopher Fauleta2097962019-07-15 16:25:33 +02004761 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004762 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004763 q = p;
4764 while (q < end && *q != '?')
4765 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004766
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004767 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004768 lua_pushstring(L, "path");
4769 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004770 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004771
Christopher Fauleta2097962019-07-15 16:25:33 +02004772 /* Stores the query string. */
4773 lua_pushstring(L, "qs");
4774 if (*q == '?')
4775 q++;
4776 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004777 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004778 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004779
Christopher Fauleta2097962019-07-15 16:25:33 +02004780 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4781 struct htx_blk *blk = htx_get_blk(htx, pos);
4782 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004783
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004784 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004785 break;
4786 if (type == HTX_BLK_DATA)
4787 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004788 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004789 if (htx->extra != ULLONG_MAX)
4790 len += htx->extra;
4791
4792 /* Stores the request path. */
4793 lua_pushstring(L, "length");
4794 lua_pushinteger(L, len);
4795 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004796
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004797 /* Create an empty array of HTTP request headers. */
4798 lua_pushstring(L, "response");
4799 lua_newtable(L);
4800 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004801
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004802 /* Pop a class stream metatable and affect it to the table. */
4803 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4804 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004805
4806 return 1;
4807}
4808
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004809__LJMP static int hlua_applet_http_set_var(lua_State *L)
4810{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004811 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004812 struct stream *s;
4813 const char *name;
4814 size_t len;
4815 struct sample smp;
4816
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004817 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4818 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004819
4820 /* It is useles to retrieve the stream, but this function
4821 * runs only in a stream context.
4822 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004823 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004824 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004825 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004826
4827 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004828 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004829 hlua_lua2smp(L, 3, &smp);
4830
4831 /* Store the sample in a variable. */
4832 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004833
4834 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4835 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4836 else
4837 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4838
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004839 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004840}
4841
4842__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4843{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004844 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004845 struct stream *s;
4846 const char *name;
4847 size_t len;
4848 struct sample smp;
4849
4850 MAY_LJMP(check_args(L, 2, "unset_var"));
4851
4852 /* It is useles to retrieve the stream, but this function
4853 * runs only in a stream context.
4854 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004855 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004856 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004857 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004858
4859 /* Unset the variable. */
4860 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004861 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4862 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004863}
4864
4865__LJMP static int hlua_applet_http_get_var(lua_State *L)
4866{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004867 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004868 struct stream *s;
4869 const char *name;
4870 size_t len;
4871 struct sample smp;
4872
4873 MAY_LJMP(check_args(L, 2, "get_var"));
4874
4875 /* It is useles to retrieve the stream, but this function
4876 * runs only in a stream context.
4877 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004878 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004879 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004880 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004881
4882 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004883 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004884 lua_pushnil(L);
4885 return 1;
4886 }
4887
4888 return hlua_smp2lua(L, &smp);
4889}
4890
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004891__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4892{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004893 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4894 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004895 struct hlua *hlua;
4896
4897 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004898 if (!s->hlua)
4899 return 0;
4900 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004901
4902 MAY_LJMP(check_args(L, 2, "set_priv"));
4903
4904 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004905 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004906
4907 /* Get and store new value. */
4908 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4909 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4910
4911 return 0;
4912}
4913
4914__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4915{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004916 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4917 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004918 struct hlua *hlua;
4919
4920 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004921 if (!s->hlua) {
4922 lua_pushnil(L);
4923 return 1;
4924 }
4925 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004926
4927 /* Push configuration index in the stack. */
4928 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4929
4930 return 1;
4931}
4932
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004933/* If expected data not yet available, it returns a yield. This function
4934 * consumes the data in the buffer. It returns a string containing the
4935 * data. This string can be empty.
4936 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004937__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004938{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004939 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004940 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004941 struct channel *req = si_oc(si);
4942 struct htx *htx;
4943 struct htx_blk *blk;
4944 size_t count;
4945 int stop = 0;
4946
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004947 htx = htx_from_buf(&req->buf);
4948 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004949 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004950
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004951 while (count && !stop && blk) {
4952 enum htx_blk_type type = htx_get_blk_type(blk);
4953 uint32_t sz = htx_get_blksz(blk);
4954 struct ist v;
4955 uint32_t vlen;
4956 char *nl;
4957
4958 vlen = sz;
4959 if (vlen > count) {
4960 if (type != HTX_BLK_DATA)
4961 break;
4962 vlen = count;
4963 }
4964
4965 switch (type) {
4966 case HTX_BLK_UNUSED:
4967 break;
4968
4969 case HTX_BLK_DATA:
4970 v = htx_get_blk_value(htx, blk);
4971 v.len = vlen;
4972 nl = istchr(v, '\n');
4973 if (nl != NULL) {
4974 stop = 1;
4975 vlen = nl - v.ptr + 1;
4976 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004977 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004978 break;
4979
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004980 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004981 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004982 stop = 1;
4983 break;
4984
4985 default:
4986 break;
4987 }
4988
4989 co_set_data(req, co_data(req) - vlen);
4990 count -= vlen;
4991 if (sz == vlen)
4992 blk = htx_remove_blk(htx, blk);
4993 else {
4994 htx_cut_data_blk(htx, blk, vlen);
4995 break;
4996 }
4997 }
4998
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004999 /* The message was fully consumed and no more data are expected
5000 * (EOM flag set).
5001 */
5002 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5003 stop = 1;
5004
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005005 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005006 if (!stop) {
5007 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005008 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005009 }
5010
5011 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005012 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005013 return 1;
5014}
5015
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005016
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005017/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005018__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005019{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005020 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005021
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005022 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005023 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005024
Christopher Fauleta2097962019-07-15 16:25:33 +02005025 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005026}
5027
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005028/* If expected data not yet available, it returns a yield. This function
5029 * consumes the data in the buffer. It returns a string containing the
5030 * data. This string can be empty.
5031 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005032__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005033{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005034 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005035 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005036 struct channel *req = si_oc(si);
5037 struct htx *htx;
5038 struct htx_blk *blk;
5039 size_t count;
5040 int len;
5041
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005042 htx = htx_from_buf(&req->buf);
5043 len = MAY_LJMP(luaL_checkinteger(L, 2));
5044 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005045 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005046 while (count && len && blk) {
5047 enum htx_blk_type type = htx_get_blk_type(blk);
5048 uint32_t sz = htx_get_blksz(blk);
5049 struct ist v;
5050 uint32_t vlen;
5051
5052 vlen = sz;
5053 if (len > 0 && vlen > len)
5054 vlen = len;
5055 if (vlen > count) {
5056 if (type != HTX_BLK_DATA)
5057 break;
5058 vlen = count;
5059 }
5060
5061 switch (type) {
5062 case HTX_BLK_UNUSED:
5063 break;
5064
5065 case HTX_BLK_DATA:
5066 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005067 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005068 break;
5069
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005070 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005071 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005072 len = 0;
5073 break;
5074
5075 default:
5076 break;
5077 }
5078
5079 co_set_data(req, co_data(req) - vlen);
5080 count -= vlen;
5081 if (len > 0)
5082 len -= vlen;
5083 if (sz == vlen)
5084 blk = htx_remove_blk(htx, blk);
5085 else {
5086 htx_cut_data_blk(htx, blk, vlen);
5087 break;
5088 }
5089 }
5090
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005091 /* The message was fully consumed and no more data are expected
5092 * (EOM flag set).
5093 */
5094 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5095 len = 0;
5096
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005097 htx_to_buf(htx, &req->buf);
5098
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005099 /* If we are no other data available, yield waiting for new data. */
5100 if (len) {
5101 if (len > 0) {
5102 lua_pushinteger(L, len);
5103 lua_replace(L, 2);
5104 }
5105 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005106 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005107 }
5108
5109 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005110 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005111 return 1;
5112}
5113
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005114/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005115__LJMP static int hlua_applet_http_recv(lua_State *L)
5116{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005117 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005118 int len = -1;
5119
5120 /* Check arguments. */
5121 if (lua_gettop(L) > 2)
5122 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5123 if (lua_gettop(L) >= 2) {
5124 len = MAY_LJMP(luaL_checkinteger(L, 2));
5125 lua_pop(L, 1);
5126 }
5127
Christopher Fauleta2097962019-07-15 16:25:33 +02005128 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005129
Christopher Fauleta2097962019-07-15 16:25:33 +02005130 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005131 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005132
Christopher Fauleta2097962019-07-15 16:25:33 +02005133 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005134}
5135
5136/* Append data in the output side of the buffer. This data is immediately
5137 * sent. The function returns the amount of data written. If the buffer
5138 * cannot contain the data, the function yields. The function returns -1
5139 * if the channel is closed.
5140 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005141__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005142{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005143 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005144 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005145 struct channel *res = si_ic(si);
5146 struct htx *htx = htx_from_buf(&res->buf);
5147 const char *data;
5148 size_t len;
5149 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5150 int max;
5151
Christopher Faulet9060fc02019-07-03 11:39:30 +02005152 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005153 if (!max)
5154 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005155
5156 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5157
5158 /* Get the max amount of data which can write as input in the channel. */
5159 if (max > (len - l))
5160 max = len - l;
5161
5162 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005163 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005164 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005165
5166 /* update counters. */
5167 l += max;
5168 lua_pop(L, 1);
5169 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005170
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005171 /* If some data is not send, declares the situation to the
5172 * applet, and returns a yield.
5173 */
5174 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005175 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005176 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005177 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005178 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005179 }
5180
Christopher Fauleta2097962019-07-15 16:25:33 +02005181 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005182 return 1;
5183}
5184
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005185/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005186 * yield the LUA process, and resume it without checking the
5187 * input arguments.
5188 */
5189__LJMP static int hlua_applet_http_send(lua_State *L)
5190{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005191 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005192
5193 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005194 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005195 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5196 WILL_LJMP(lua_error(L));
5197 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005198
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005199 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005200 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005201
Christopher Fauleta2097962019-07-15 16:25:33 +02005202 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005203}
5204
5205__LJMP static int hlua_applet_http_addheader(lua_State *L)
5206{
5207 const char *name;
5208 int ret;
5209
5210 MAY_LJMP(hlua_checkapplet_http(L, 1));
5211 name = MAY_LJMP(luaL_checkstring(L, 2));
5212 MAY_LJMP(luaL_checkstring(L, 3));
5213
5214 /* Push in the stack the "response" entry. */
5215 ret = lua_getfield(L, 1, "response");
5216 if (ret != LUA_TTABLE) {
5217 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5218 "is expected as an array. %s found", lua_typename(L, ret));
5219 WILL_LJMP(lua_error(L));
5220 }
5221
5222 /* check if the header is already registered if it is not
5223 * the case, register it.
5224 */
5225 ret = lua_getfield(L, -1, name);
5226 if (ret == LUA_TNIL) {
5227
5228 /* Entry not found. */
5229 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5230
5231 /* Insert the new header name in the array in the top of the stack.
5232 * It left the new array in the top of the stack.
5233 */
5234 lua_newtable(L);
5235 lua_pushvalue(L, 2);
5236 lua_pushvalue(L, -2);
5237 lua_settable(L, -4);
5238
5239 } else if (ret != LUA_TTABLE) {
5240
5241 /* corruption error. */
5242 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5243 "is expected as an array. %s found", name, lua_typename(L, ret));
5244 WILL_LJMP(lua_error(L));
5245 }
5246
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005247 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005248 * the header value as new entry.
5249 */
5250 lua_pushvalue(L, 3);
5251 ret = lua_rawlen(L, -2);
5252 lua_rawseti(L, -2, ret + 1);
5253 lua_pushboolean(L, 1);
5254 return 1;
5255}
5256
5257__LJMP static int hlua_applet_http_status(lua_State *L)
5258{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005259 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005260 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005261 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005262
5263 if (status < 100 || status > 599) {
5264 lua_pushboolean(L, 0);
5265 return 1;
5266 }
5267
Willy Tarreau7e702d12021-04-28 17:59:21 +02005268 luactx->appctx->ctx.hlua_apphttp.status = status;
5269 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005270 lua_pushboolean(L, 1);
5271 return 1;
5272}
5273
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005274
Christopher Fauleta2097962019-07-15 16:25:33 +02005275__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005276{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005277 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005278 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005279 struct channel *res = si_ic(si);
5280 struct htx *htx;
5281 struct htx_sl *sl;
5282 struct h1m h1m;
5283 const char *status, *reason;
5284 const char *name, *value;
5285 size_t nlen, vlen;
5286 unsigned int flags;
5287
5288 /* Send the message at once. */
5289 htx = htx_from_buf(&res->buf);
5290 h1m_init_res(&h1m);
5291
5292 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005293 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5294 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005295 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005296 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5297 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005298 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5299 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5300 }
5301 else {
5302 flags = HTX_SL_F_IS_RESP;
5303 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5304 }
5305 if (!sl) {
5306 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005307 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005308 WILL_LJMP(lua_error(L));
5309 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005310 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005311
5312 /* Get the array associated to the field "response" in the object AppletHTTP. */
5313 lua_pushvalue(L, 0);
5314 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5315 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005316 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005317 WILL_LJMP(lua_error(L));
5318 }
5319
5320 /* Browse the list of headers. */
5321 lua_pushnil(L);
5322 while(lua_next(L, -2) != 0) {
5323 /* We expect a string as -2. */
5324 if (lua_type(L, -2) != LUA_TSTRING) {
5325 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005326 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005327 lua_typename(L, lua_type(L, -2)));
5328 WILL_LJMP(lua_error(L));
5329 }
5330 name = lua_tolstring(L, -2, &nlen);
5331
5332 /* We expect an array as -1. */
5333 if (lua_type(L, -1) != LUA_TTABLE) {
5334 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 +02005335 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005336 name,
5337 lua_typename(L, lua_type(L, -1)));
5338 WILL_LJMP(lua_error(L));
5339 }
5340
5341 /* Browse the table who is on the top of the stack. */
5342 lua_pushnil(L);
5343 while(lua_next(L, -2) != 0) {
5344 int id;
5345
5346 /* We expect a number as -2. */
5347 if (lua_type(L, -2) != LUA_TNUMBER) {
5348 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 +02005349 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005350 name,
5351 lua_typename(L, lua_type(L, -2)));
5352 WILL_LJMP(lua_error(L));
5353 }
5354 id = lua_tointeger(L, -2);
5355
5356 /* We expect a string as -2. */
5357 if (lua_type(L, -1) != LUA_TSTRING) {
5358 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 +02005359 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005360 name, id,
5361 lua_typename(L, lua_type(L, -1)));
5362 WILL_LJMP(lua_error(L));
5363 }
5364 value = lua_tolstring(L, -1, &vlen);
5365
5366 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005367 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5368 int ret;
5369
5370 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5371 if (ret < 0) {
5372 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5373 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5374 name);
5375 WILL_LJMP(lua_error(L));
5376 }
5377 else if (ret == 0)
5378 goto next; /* Skip it */
5379 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005380 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5381 struct ist v = ist2(value, vlen);
5382 int ret;
5383
5384 ret = h1_parse_cont_len_header(&h1m, &v);
5385 if (ret < 0) {
5386 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005387 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005388 name);
5389 WILL_LJMP(lua_error(L));
5390 }
5391 else if (ret == 0)
5392 goto next; /* Skip it */
5393 }
5394
5395 /* Add a new header */
5396 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5397 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005398 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005399 name);
5400 WILL_LJMP(lua_error(L));
5401 }
5402 next:
5403 /* Remove the array from the stack, and get next element with a remaining string. */
5404 lua_pop(L, 1);
5405 }
5406
5407 /* Remove the array from the stack, and get next element with a remaining string. */
5408 lua_pop(L, 1);
5409 }
5410
5411 if (h1m.flags & H1_MF_CHNK)
5412 h1m.flags &= ~H1_MF_CLEN;
5413 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5414 h1m.flags |= H1_MF_XFER_LEN;
5415
5416 /* Uset HTX start-line flags */
5417 if (h1m.flags & H1_MF_XFER_ENC)
5418 flags |= HTX_SL_F_XFER_ENC;
5419 if (h1m.flags & H1_MF_XFER_LEN) {
5420 flags |= HTX_SL_F_XFER_LEN;
5421 if (h1m.flags & H1_MF_CHNK)
5422 flags |= HTX_SL_F_CHNK;
5423 else if (h1m.flags & H1_MF_CLEN)
5424 flags |= HTX_SL_F_CLEN;
5425 if (h1m.body_len == 0)
5426 flags |= HTX_SL_F_BODYLESS;
5427 }
5428 sl->flags |= flags;
5429
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005430 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005431 * and the status code implies the presence of a message body, we must
5432 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005433 * for the keepalive compliance. If the applet announces a transfer-encoding
5434 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005435 */
5436 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005437 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5438 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5439 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005440 /* Add a new header */
5441 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5442 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5443 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005444 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005445 WILL_LJMP(lua_error(L));
5446 }
5447 }
5448
5449 /* Finalize headers. */
5450 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5451 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005452 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005453 WILL_LJMP(lua_error(L));
5454 }
5455
5456 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5457 b_reset(&res->buf);
5458 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5459 WILL_LJMP(lua_error(L));
5460 }
5461
5462 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005463 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005464
5465 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005466 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005467 return 0;
5468
5469}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005470/* We will build the status line and the headers of the HTTP response.
5471 * We will try send at once if its not possible, we give back the hand
5472 * waiting for more room.
5473 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005474__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005475{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005476 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005477 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005478 struct channel *res = si_ic(si);
5479
5480 if (co_data(res)) {
5481 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005482 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005483 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005484 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005485}
5486
5487
Christopher Fauleta2097962019-07-15 16:25:33 +02005488__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005489{
Christopher Fauleta2097962019-07-15 16:25:33 +02005490 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005491}
5492
Christopher Fauleta2097962019-07-15 16:25:33 +02005493/*
5494 *
5495 *
5496 * Class HTTP
5497 *
5498 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005499 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005500
5501/* Returns a struct hlua_txn if the stack entry "ud" is
5502 * a class stream, otherwise it throws an error.
5503 */
5504__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005505{
Christopher Fauleta2097962019-07-15 16:25:33 +02005506 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5507}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005508
Christopher Fauleta2097962019-07-15 16:25:33 +02005509/* This function creates and push in the stack a HTTP object
5510 * according with a current TXN.
5511 */
5512static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5513{
5514 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005515
Christopher Fauleta2097962019-07-15 16:25:33 +02005516 /* Check stack size. */
5517 if (!lua_checkstack(L, 3))
5518 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005519
Christopher Fauleta2097962019-07-15 16:25:33 +02005520 /* Create the object: obj[0] = userdata.
5521 * Note that the base of the Converters object is the
5522 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005523 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005524 lua_newtable(L);
5525 htxn = lua_newuserdata(L, sizeof(*htxn));
5526 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005527
5528 htxn->s = txn->s;
5529 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005530 htxn->dir = txn->dir;
5531 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005532
5533 /* Pop a class stream metatable and affect it to the table. */
5534 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5535 lua_setmetatable(L, -2);
5536
5537 return 1;
5538}
5539
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005540/* This function creates and returns an array containing the status-line
5541 * elements. This function does not fails.
5542 */
5543__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5544{
5545 /* Create the table. */
5546 lua_newtable(L);
5547
5548 if (sl->flags & HTX_SL_F_IS_RESP) {
5549 lua_pushstring(L, "version");
5550 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5551 lua_settable(L, -3);
5552 lua_pushstring(L, "code");
5553 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5554 lua_settable(L, -3);
5555 lua_pushstring(L, "reason");
5556 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5557 lua_settable(L, -3);
5558 }
5559 else {
5560 lua_pushstring(L, "method");
5561 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5562 lua_settable(L, -3);
5563 lua_pushstring(L, "uri");
5564 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5565 lua_settable(L, -3);
5566 lua_pushstring(L, "version");
5567 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5568 lua_settable(L, -3);
5569 }
5570 return 1;
5571}
5572
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005573/* This function creates ans returns an array of HTTP headers.
5574 * This function does not fails. It is used as wrapper with the
5575 * 2 following functions.
5576 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005577__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005578{
Christopher Fauleta2097962019-07-15 16:25:33 +02005579 struct htx *htx;
5580 int32_t pos;
5581
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005582 /* Create the table. */
5583 lua_newtable(L);
5584
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005585
Christopher Fauleta2097962019-07-15 16:25:33 +02005586 htx = htxbuf(&msg->chn->buf);
5587 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5588 struct htx_blk *blk = htx_get_blk(htx, pos);
5589 enum htx_blk_type type = htx_get_blk_type(blk);
5590 struct ist n, v;
5591 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005592
Christopher Fauleta2097962019-07-15 16:25:33 +02005593 if (type == HTX_BLK_HDR) {
5594 n = htx_get_blk_name(htx,blk);
5595 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005596 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005597 else if (type == HTX_BLK_EOH)
5598 break;
5599 else
5600 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005601
Christopher Fauleta2097962019-07-15 16:25:33 +02005602 /* Check for existing entry:
5603 * assume that the table is on the top of the stack, and
5604 * push the key in the stack, the function lua_gettable()
5605 * perform the lookup.
5606 */
5607 lua_pushlstring(L, n.ptr, n.len);
5608 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005609
Christopher Fauleta2097962019-07-15 16:25:33 +02005610 switch (lua_type(L, -1)) {
5611 case LUA_TNIL:
5612 /* Table not found, create it. */
5613 lua_pop(L, 1); /* remove the nil value. */
5614 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5615 lua_newtable(L); /* create and push empty table. */
5616 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5617 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5618 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005619 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005620
Christopher Fauleta2097962019-07-15 16:25:33 +02005621 case LUA_TTABLE:
5622 /* Entry found: push the value in the table. */
5623 len = lua_rawlen(L, -1);
5624 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5625 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5626 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5627 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005628
Christopher Fauleta2097962019-07-15 16:25:33 +02005629 default:
5630 /* Other cases are errors. */
5631 hlua_pusherror(L, "internal error during the parsing of headers.");
5632 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005633 }
5634 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005635 return 1;
5636}
5637
5638__LJMP static int hlua_http_req_get_headers(lua_State *L)
5639{
5640 struct hlua_txn *htxn;
5641
5642 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5643 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5644
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005645 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005646 WILL_LJMP(lua_error(L));
5647
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005648 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005649}
5650
5651__LJMP static int hlua_http_res_get_headers(lua_State *L)
5652{
5653 struct hlua_txn *htxn;
5654
5655 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5656 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5657
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005658 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005659 WILL_LJMP(lua_error(L));
5660
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005661 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005662}
5663
5664/* This function replace full header, or just a value in
5665 * the request or in the response. It is a wrapper fir the
5666 * 4 following functions.
5667 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005668__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005669{
5670 size_t name_len;
5671 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5672 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5673 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005674 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005675 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005676
Dragan Dosen26743032019-04-30 15:54:36 +02005677 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005678 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5679
Christopher Fauleta2097962019-07-15 16:25:33 +02005680 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005681 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005682 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005683 return 0;
5684}
5685
5686__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5687{
5688 struct hlua_txn *htxn;
5689
5690 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5691 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5692
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005693 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005694 WILL_LJMP(lua_error(L));
5695
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005696 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005697}
5698
5699__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5700{
5701 struct hlua_txn *htxn;
5702
5703 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5704 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5705
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005706 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005707 WILL_LJMP(lua_error(L));
5708
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005709 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005710}
5711
5712__LJMP static int hlua_http_req_rep_val(lua_State *L)
5713{
5714 struct hlua_txn *htxn;
5715
5716 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5717 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5718
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005719 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005720 WILL_LJMP(lua_error(L));
5721
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005722 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005723}
5724
5725__LJMP static int hlua_http_res_rep_val(lua_State *L)
5726{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005727 struct hlua_txn *htxn;
5728
5729 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5730 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5731
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005732 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005733 WILL_LJMP(lua_error(L));
5734
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005735 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005736}
5737
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005738/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005739 * It is a wrapper for the 2 following functions.
5740 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005741__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005742{
5743 size_t len;
5744 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005745 struct htx *htx = htxbuf(&msg->chn->buf);
5746 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005747
Christopher Fauleta2097962019-07-15 16:25:33 +02005748 ctx.blk = NULL;
5749 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5750 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005751 return 0;
5752}
5753
5754__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5755{
5756 struct hlua_txn *htxn;
5757
5758 MAY_LJMP(check_args(L, 2, "req_del_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 Fauletd31c7b32020-02-25 09:37:57 +01005764 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005765}
5766
5767__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5768{
5769 struct hlua_txn *htxn;
5770
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005771 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005772 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 Fauletd31c7b32020-02-25 09:37:57 +01005777 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005778}
5779
5780/* This function adds an header. It is a wrapper used by
5781 * the 2 following functions.
5782 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005783__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005784{
5785 size_t name_len;
5786 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5787 size_t value_len;
5788 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005789 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005790
Christopher Fauleta2097962019-07-15 16:25:33 +02005791 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5792 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005793 return 0;
5794}
5795
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005796__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5797{
5798 struct hlua_txn *htxn;
5799
5800 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5801 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5802
5803 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5804 WILL_LJMP(lua_error(L));
5805
5806 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5807}
5808
5809__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5810{
5811 struct hlua_txn *htxn;
5812
5813 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5814 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5815
5816 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5817 WILL_LJMP(lua_error(L));
5818
5819 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5820}
5821
5822static int hlua_http_req_set_hdr(lua_State *L)
5823{
5824 struct hlua_txn *htxn;
5825
5826 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5827 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5828
5829 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5830 WILL_LJMP(lua_error(L));
5831
5832 hlua_http_del_hdr(L, &htxn->s->txn->req);
5833 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5834}
5835
5836static int hlua_http_res_set_hdr(lua_State *L)
5837{
5838 struct hlua_txn *htxn;
5839
5840 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5841 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5842
5843 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5844 WILL_LJMP(lua_error(L));
5845
5846 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5847 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5848}
5849
5850/* This function set the method. */
5851static int hlua_http_req_set_meth(lua_State *L)
5852{
5853 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5854 size_t name_len;
5855 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5856
5857 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5858 WILL_LJMP(lua_error(L));
5859
5860 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5861 return 1;
5862}
5863
5864/* This function set the method. */
5865static int hlua_http_req_set_path(lua_State *L)
5866{
5867 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5868 size_t name_len;
5869 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5870
5871 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5872 WILL_LJMP(lua_error(L));
5873
5874 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5875 return 1;
5876}
5877
5878/* This function set the query-string. */
5879static int hlua_http_req_set_query(lua_State *L)
5880{
5881 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5882 size_t name_len;
5883 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5884
5885 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5886 WILL_LJMP(lua_error(L));
5887
5888 /* Check length. */
5889 if (name_len > trash.size - 1) {
5890 lua_pushboolean(L, 0);
5891 return 1;
5892 }
5893
5894 /* Add the mark question as prefix. */
5895 chunk_reset(&trash);
5896 trash.area[trash.data++] = '?';
5897 memcpy(trash.area + trash.data, name, name_len);
5898 trash.data += name_len;
5899
5900 lua_pushboolean(L,
5901 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5902 return 1;
5903}
5904
5905/* This function set the uri. */
5906static int hlua_http_req_set_uri(lua_State *L)
5907{
5908 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5909 size_t name_len;
5910 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5911
5912 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5913 WILL_LJMP(lua_error(L));
5914
5915 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5916 return 1;
5917}
5918
5919/* This function set the response code & optionally reason. */
5920static int hlua_http_res_set_status(lua_State *L)
5921{
5922 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5923 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5924 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5925 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5926
5927 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5928 WILL_LJMP(lua_error(L));
5929
5930 http_res_set_status(code, reason, htxn->s);
5931 return 0;
5932}
5933
5934/*
5935 *
5936 *
5937 * Class HTTPMessage
5938 *
5939 *
5940 */
5941
5942/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5943 * otherwise it throws an error.
5944 */
5945__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5946{
5947 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5948}
5949
5950/* Creates and pushes on the stack a HTTP object according with a current TXN.
5951 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005952static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005953{
5954 /* Check stack size. */
5955 if (!lua_checkstack(L, 3))
5956 return 0;
5957
5958 lua_newtable(L);
5959 lua_pushlightuserdata(L, msg);
5960 lua_rawseti(L, -2, 0);
5961
5962 /* Create the "channel" field that contains the request channel object. */
5963 lua_pushstring(L, "channel");
5964 if (!hlua_channel_new(L, msg->chn))
5965 return 0;
5966 lua_rawset(L, -3);
5967
5968 /* Pop a class stream metatable and affect it to the table. */
5969 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5970 lua_setmetatable(L, -2);
5971
5972 return 1;
5973}
5974
5975/* Helper function returning a filter attached to the HTTP message at the
5976 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05005977 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005978 * filled with output and input length respectively.
5979 */
5980static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5981{
5982 struct channel *chn = msg->chn;
5983 struct htx *htx = htxbuf(&chn->buf);
5984 struct filter *filter = NULL;
5985
5986 *offset = co_data(msg->chn);
5987 *len = htx->data - co_data(msg->chn);
5988
5989 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5990 filter = lua_touserdata (L, -1);
5991 if (msg->msg_state >= HTTP_MSG_DATA) {
5992 struct hlua_flt_ctx *flt_ctx = filter->ctx;
5993
5994 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
5995 *len = flt_ctx->cur_len[CHN_IDX(chn)];
5996 }
5997 }
5998
5999 lua_pop(L, 1);
6000 return filter;
6001}
6002
6003/* Returns true if the channel attached to the HTTP message is the response
6004 * channel.
6005 */
6006__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6007{
6008 struct http_msg *msg;
6009
6010 MAY_LJMP(check_args(L, 1, "is_resp"));
6011 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6012
6013 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6014 return 1;
6015}
6016
6017/* Returns an array containing the elements status-line of the HTTP message. It relies
6018 * on hlua_http_get_stline().
6019 */
6020__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6021{
6022 struct http_msg *msg;
6023 struct htx *htx;
6024 struct htx_sl *sl;
6025
6026 MAY_LJMP(check_args(L, 1, "get_stline"));
6027 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6028
6029 if (msg->msg_state > HTTP_MSG_BODY)
6030 WILL_LJMP(lua_error(L));
6031
6032 htx = htxbuf(&msg->chn->buf);
6033 sl = http_get_stline(htx);
6034 if (!sl)
6035 return 0;
6036 return hlua_http_get_stline(L, sl);
6037}
6038
6039/* Returns an array containing all headers of the HTTP message. it relies on
6040 * hlua_http_get_headers().
6041 */
6042__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6043{
6044 struct http_msg *msg;
6045
6046 MAY_LJMP(check_args(L, 1, "get_headers"));
6047 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6048
6049 if (msg->msg_state > HTTP_MSG_BODY)
6050 WILL_LJMP(lua_error(L));
6051
6052 return hlua_http_get_headers(L, msg);
6053}
6054
6055/* Deletes all occurrences of an header in the HTTP message matching on its
6056 * name. It relies on hlua_http_del_hdr().
6057 */
6058__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6059{
6060 struct http_msg *msg;
6061
6062 MAY_LJMP(check_args(L, 2, "del_header"));
6063 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6064
6065 if (msg->msg_state > HTTP_MSG_BODY)
6066 WILL_LJMP(lua_error(L));
6067
6068 return hlua_http_del_hdr(L, msg);
6069}
6070
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006071/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006072 * message given its name against a regex and replaces it if it matches. It
6073 * relies on hlua_http_rep_hdr().
6074 */
6075__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6076{
6077 struct http_msg *msg;
6078
6079 MAY_LJMP(check_args(L, 4, "rep_header"));
6080 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6081
6082 if (msg->msg_state > HTTP_MSG_BODY)
6083 WILL_LJMP(lua_error(L));
6084
6085 return hlua_http_rep_hdr(L, msg, 1);
6086}
6087
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006088/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006089 * message given its name against a regex and replaces it if it matches. It
6090 * relies on hlua_http_rep_hdr().
6091 */
6092__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6093{
6094 struct http_msg *msg;
6095
6096 MAY_LJMP(check_args(L, 4, "rep_value"));
6097 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6098
6099 if (msg->msg_state > HTTP_MSG_BODY)
6100 WILL_LJMP(lua_error(L));
6101
6102 return hlua_http_rep_hdr(L, msg, 0);
6103}
6104
6105/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6106__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6107{
6108 struct http_msg *msg;
6109
6110 MAY_LJMP(check_args(L, 3, "add_header"));
6111 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6112
6113 if (msg->msg_state > HTTP_MSG_BODY)
6114 WILL_LJMP(lua_error(L));
6115
6116 return hlua_http_add_hdr(L, msg);
6117}
6118
6119/* Add an header in the HTTP message removing existing headers with the same
6120 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6121 */
6122__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6123{
6124 struct http_msg *msg;
6125
6126 MAY_LJMP(check_args(L, 3, "set_header"));
6127 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6128
6129 if (msg->msg_state > HTTP_MSG_BODY)
6130 WILL_LJMP(lua_error(L));
6131
6132 hlua_http_del_hdr(L, msg);
6133 return hlua_http_add_hdr(L, msg);
6134}
6135
6136/* Rewrites the request method. It relies on http_req_replace_stline(). */
6137__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6138{
6139 struct stream *s;
6140 struct http_msg *msg;
6141 const char *name;
6142 size_t name_len;
6143
6144 MAY_LJMP(check_args(L, 2, "set_method"));
6145 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6146 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6147
6148 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6149 WILL_LJMP(lua_error(L));
6150
6151 s = chn_strm(msg->chn);
6152 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6153 return 1;
6154}
6155
6156/* Rewrites the request path. It relies on http_req_replace_stline(). */
6157__LJMP static int hlua_http_msg_set_path(lua_State *L)
6158{
6159 struct stream *s;
6160 struct http_msg *msg;
6161 const char *name;
6162 size_t name_len;
6163
6164 MAY_LJMP(check_args(L, 2, "set_path"));
6165 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6166 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6167
6168 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6169 WILL_LJMP(lua_error(L));
6170
6171 s = chn_strm(msg->chn);
6172 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6173 return 1;
6174}
6175
6176/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6177__LJMP static int hlua_http_msg_set_query(lua_State *L)
6178{
6179 struct stream *s;
6180 struct http_msg *msg;
6181 const char *name;
6182 size_t name_len;
6183
6184 MAY_LJMP(check_args(L, 2, "set_query"));
6185 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6186 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6187
6188 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6189 WILL_LJMP(lua_error(L));
6190
6191 /* Check length. */
6192 if (name_len > trash.size - 1) {
6193 lua_pushboolean(L, 0);
6194 return 1;
6195 }
6196
6197 /* Add the mark question as prefix. */
6198 chunk_reset(&trash);
6199 trash.area[trash.data++] = '?';
6200 memcpy(trash.area + trash.data, name, name_len);
6201 trash.data += name_len;
6202
6203 s = chn_strm(msg->chn);
6204 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6205 return 1;
6206}
6207
6208/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6209__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6210{
6211 struct stream *s;
6212 struct http_msg *msg;
6213 const char *name;
6214 size_t name_len;
6215
6216 MAY_LJMP(check_args(L, 2, "set_uri"));
6217 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6218 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6219
6220 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6221 WILL_LJMP(lua_error(L));
6222
6223 s = chn_strm(msg->chn);
6224 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6225 return 1;
6226}
6227
6228/* Rewrites the response status code. It relies on http_res_set_status(). */
6229__LJMP static int hlua_http_msg_set_status(lua_State *L)
6230{
6231 struct http_msg *msg;
6232 unsigned int code;
6233 const char *reason;
6234 size_t reason_len;
6235
6236 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6237 code = MAY_LJMP(luaL_checkinteger(L, 2));
6238 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6239
6240 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6241 WILL_LJMP(lua_error(L));
6242
6243 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6244 return 1;
6245}
6246
6247/* Returns true if the HTTP message is full. */
6248__LJMP static int hlua_http_msg_is_full(lua_State *L)
6249{
6250 struct http_msg *msg;
6251
6252 MAY_LJMP(check_args(L, 1, "is_full"));
6253 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6254 lua_pushboolean(L, channel_full(msg->chn, 0));
6255 return 1;
6256}
6257
6258/* Returns true if the HTTP message may still receive data. */
6259__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6260{
6261 struct http_msg *msg;
6262 struct htx *htx;
6263
6264 MAY_LJMP(check_args(L, 1, "may_recv"));
6265 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6266 htx = htxbuf(&msg->chn->buf);
6267 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6268 return 1;
6269}
6270
6271/* Returns true if the HTTP message EOM was received */
6272__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6273{
6274 struct http_msg *msg;
6275 struct htx *htx;
6276
6277 MAY_LJMP(check_args(L, 1, "may_recv"));
6278 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6279 htx = htxbuf(&msg->chn->buf);
6280 lua_pushboolean(L, !htx_expect_more(htx));
6281 return 1;
6282}
6283
6284/* Returns the number of bytes available in the input side of the HTTP
6285 * message. This function never fails.
6286 */
6287__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6288{
6289 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006290 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006291
6292 MAY_LJMP(check_args(L, 1, "input"));
6293 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006294 hlua_http_msg_filter(L, 1, msg, &output, &input);
6295 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006296 return 1;
6297}
6298
6299/* Returns the number of bytes available in the output side of the HTTP
6300 * message. This function never fails.
6301 */
6302__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6303{
6304 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006305 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006306
6307 MAY_LJMP(check_args(L, 1, "output"));
6308 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006309 hlua_http_msg_filter(L, 1, msg, &output, &input);
6310 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006311 return 1;
6312}
6313
6314/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6315 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006316 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006317 * block. This function is called during the payload filtering, so the headers
6318 * are already scheduled for output (from the filter point of view).
6319 */
6320static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6321{
6322 struct htx *htx = htxbuf(&msg->chn->buf);
6323 struct htx_blk *blk;
6324 struct htx_ret htxret;
6325 luaL_Buffer b;
6326 int ret = 0;
6327
6328 luaL_buffinit(L, &b);
6329 htxret = htx_find_offset(htx, offset);
6330 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6331 enum htx_blk_type type = htx_get_blk_type(blk);
6332 struct ist v;
6333
6334 switch (type) {
6335 case HTX_BLK_UNUSED:
6336 break;
6337
6338 case HTX_BLK_DATA:
6339 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006340 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006341 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006342
6343 luaL_addlstring(&b, v.ptr, v.len);
6344 ret += v.len;
6345 break;
6346
6347 default:
vishnu0af4bd72021-10-24 06:46:24 +05306348 if (!ret)
6349 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006350 goto end;
6351 }
6352 offset = 0;
6353 }
6354
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006355end:
vishnu0af4bd72021-10-24 06:46:24 +05306356 if (!ret && (htx->flags & HTX_FL_EOM))
6357 goto no_data;
6358 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006359 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306360
6361 no_data:
6362 /* Remove the empty string and push nil on the stack */
6363 lua_pop(L, 1);
6364 lua_pushnil(L);
6365 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006366}
6367
6368/* Copies the string <str> to the HTTP message <msg> at the offset
6369 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006370 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006371 * the filter context.
6372 */
6373static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6374{
6375 struct htx *htx = htx_from_buf(&msg->chn->buf);
6376 struct htx_ret htxret;
6377 int /*max, */ret = 0;
6378
6379 /* Nothing to do, just return */
6380 if (unlikely(istlen(str) == 0))
6381 goto end;
6382
6383 if (istlen(str) > htx_free_data_space(htx)) {
6384 ret = -1;
6385 goto end;
6386 }
6387
6388 htxret = htx_find_offset(htx, offset);
6389 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6390 if (!htx_add_last_data(htx, str))
6391 goto end;
6392 }
6393 else {
6394 struct ist v = htx_get_blk_value(htx, htxret.blk);
6395 v.ptr += htxret.ret;
6396 v.len = 0;
6397 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6398 goto end;
6399 }
6400 ret = str.len;
6401 if (ret) {
6402 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6403 flt_update_offsets(filter, msg->chn, ret);
6404 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6405 }
6406
6407 end:
6408 htx_to_buf(htx, &msg->chn->buf);
6409 return ret;
6410}
6411
6412/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6413 * position <offset>. It stops on the first non-DATA HTX block. This function is
6414 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006415 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006416 * update the filter context.
6417 */
6418static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6419{
6420 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6421 struct htx *htx = htx_from_buf(&msg->chn->buf);
6422 struct htx_blk *blk;
6423 struct htx_ret htxret;
6424 size_t ret = 0;
6425
6426 /* Be sure <len> is always the amount of DATA to remove */
6427 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6428 htx_truncate(htx, offset);
6429 ret = len;
6430 goto end;
6431 }
6432
6433 htxret = htx_find_offset(htx, offset);
6434 blk = htxret.blk;
6435 if (htxret.ret) {
6436 struct ist v;
6437
6438 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6439 goto end;
6440 v = htx_get_blk_value(htx, blk);
6441 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006442 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006443 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006444 len -= v.len;
6445 ret += v.len;
6446 }
6447
6448
6449 while (blk && len) {
6450 enum htx_blk_type type = htx_get_blk_type(blk);
6451 uint32_t sz = htx_get_blksz(blk);
6452
6453 switch (type) {
6454 case HTX_BLK_UNUSED:
6455 break;
6456
6457 case HTX_BLK_DATA:
6458 if (len < sz) {
6459 htx_cut_data_blk(htx, blk, len);
6460 ret += len;
6461 goto end;
6462 }
6463 break;
6464
6465 default:
6466 goto end;
6467 }
6468
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006469 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006470 len -= sz;
6471 ret += sz;
6472 blk = htx_remove_blk(htx, blk);
6473 }
6474
6475end:
6476 flt_update_offsets(filter, msg->chn, -ret);
6477 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6478 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6479 * to loose the EOM flag if the message is empty.
6480 */
6481}
6482
6483/* Copies input data found in an HTTP message. Unlike the channel function used
6484 * to duplicate raw data, this one can only be called inside a filter, from
6485 * http_payload callback. So it cannot yield. An exception is returned if it is
6486 * called from another callback. If nothing was copied, a nil value is pushed on
6487 * the stack.
6488 */
6489__LJMP static int hlua_http_msg_get_body(lua_State *L)
6490{
6491 struct http_msg *msg;
6492 struct filter *filter;
6493 size_t output, input;
6494 int offset, len;
6495
6496 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6497 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6498 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6499
6500 if (msg->msg_state < HTTP_MSG_DATA)
6501 WILL_LJMP(lua_error(L));
6502
6503 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6504 if (!filter || !hlua_filter_from_payload(filter))
6505 WILL_LJMP(lua_error(L));
6506
6507 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6508 lua_pushnil(L);
6509 return 1;
6510 }
6511
6512 offset = output;
6513 if (lua_gettop(L) > 1) {
6514 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6515 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006516 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006517 offset += output;
6518 if (offset < output || offset > input + output) {
6519 lua_pushfstring(L, "offset out of range.");
6520 WILL_LJMP(lua_error(L));
6521 }
6522 }
6523 len = output + input - offset;
6524 if (lua_gettop(L) == 3) {
6525 len = MAY_LJMP(luaL_checkinteger(L, 3));
6526 if (!len)
6527 goto dup;
6528 if (len == -1)
6529 len = global.tune.bufsize;
6530 if (len < 0) {
6531 lua_pushfstring(L, "length out of range.");
6532 WILL_LJMP(lua_error(L));
6533 }
6534 }
6535
6536 dup:
6537 _hlua_http_msg_dup(msg, L, offset, len);
6538 return 1;
6539}
6540
6541/* Appends a string to the HTTP message, after all existing DATA blocks but
6542 * before the trailers, if any. It returns the amount of data written or -1 if
6543 * nothing was copied. Unlike the channel function used to append data, this one
6544 * can only be called inside a filter, from http_payload callback. So it cannot
6545 * yield. An exception is returned if it is called from another callback.
6546 */
6547__LJMP static int hlua_http_msg_append(lua_State *L)
6548{
6549 struct http_msg *msg;
6550 struct filter *filter;
6551 const char *str;
6552 size_t offset, len, sz;
6553 int ret;
6554
6555 MAY_LJMP(check_args(L, 2, "append"));
6556 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6557
6558 if (msg->msg_state < HTTP_MSG_DATA)
6559 WILL_LJMP(lua_error(L));
6560
6561 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6562 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6563 if (!filter || !hlua_filter_from_payload(filter))
6564 WILL_LJMP(lua_error(L));
6565
6566 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6567 lua_pushinteger(L, ret);
6568 return 1;
6569}
6570
6571/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6572 * returns the amount of data written or -1 if nothing was copied. Unlike the
6573 * channel function used to prepend data, this one can only be called inside a
6574 * filter, from http_payload callback. So it cannot yield. An exception is
6575 * returned if it is called from another callback.
6576 */
6577__LJMP static int hlua_http_msg_prepend(lua_State *L)
6578{
6579 struct http_msg *msg;
6580 struct filter *filter;
6581 const char *str;
6582 size_t offset, len, sz;
6583 int ret;
6584
6585 MAY_LJMP(check_args(L, 2, "prepend"));
6586 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006587
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006588 if (msg->msg_state < HTTP_MSG_DATA)
6589 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006590
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006591 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6592 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6593 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006594 WILL_LJMP(lua_error(L));
6595
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006596 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6597 lua_pushinteger(L, ret);
6598 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006599}
6600
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006601/* Inserts a string to the HTTP message at a given offset. By default the string
6602 * is appended at the end of DATA blocks. It returns the amount of data written
6603 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6604 * this one can only be called inside a filter, from http_payload callback. So
6605 * it cannot yield. An exception is returned if it is called from another
6606 * callback.
6607 */
6608__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006609{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006610 struct http_msg *msg;
6611 struct filter *filter;
6612 const char *str;
6613 size_t input, output, sz;
6614 int offset;
6615 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006616
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006617 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6618 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6619 MAY_LJMP(check_args(L, 2, "insert"));
6620 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006621
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006622 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006623 WILL_LJMP(lua_error(L));
6624
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006625 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6626 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6627 if (!filter || !hlua_filter_from_payload(filter))
6628 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006629
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006630 offset = input + output;
6631 if (lua_gettop(L) > 2) {
6632 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6633 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006634 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006635 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006636 if (offset < output || offset > output + input) {
6637 lua_pushfstring(L, "offset out of range.");
6638 WILL_LJMP(lua_error(L));
6639 }
6640 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006641
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006642 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6643 lua_pushinteger(L, ret);
6644 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006645}
6646
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006647/* Removes a given amount of data from the HTTP message at a given offset. By
6648 * default all DATA blocks are removed. It returns the amount of data
6649 * removed. Unlike the channel function used to remove data, this one can only
6650 * be called inside a filter, from http_payload callback. So it cannot yield. An
6651 * exception is returned if it is called from another callback.
6652 */
6653__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006654{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006655 struct http_msg *msg;
6656 struct filter *filter;
6657 size_t input, output;
6658 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006659
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006660 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6661 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6662 MAY_LJMP(check_args(L, 2, "insert"));
6663 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006664
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006665 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006666 WILL_LJMP(lua_error(L));
6667
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006668 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 len = output + input - offset;
6685 if (lua_gettop(L) == 4) {
6686 len = MAY_LJMP(luaL_checkinteger(L, 4));
6687 if (!len)
6688 goto end;
6689 if (len == -1)
6690 len = output + input - offset;
6691 if (len < 0 || offset + len > output + input) {
6692 lua_pushfstring(L, "length out of range.");
6693 WILL_LJMP(lua_error(L));
6694 }
6695 }
6696
6697 _hlua_http_msg_delete(msg, filter, offset, len);
6698
6699 end:
6700 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006701 return 1;
6702}
6703
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006704/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006705 * all remaining data are removed, accordingly to the filter context. It returns
6706 * the amount of data written or -1 if nothing was copied. Unlike the channel
6707 * function used to replace data, this one can only be called inside a filter,
6708 * from http_payload callback. So it cannot yield. An exception is returned if
6709 * it is called from another callback.
6710 */
6711__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006712{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006713 struct http_msg *msg;
6714 struct filter *filter;
6715 struct htx *htx;
6716 const char *str;
6717 size_t input, output, sz;
6718 int offset, len;
6719 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006720
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006721 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6722 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6723 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6724
6725 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006726 WILL_LJMP(lua_error(L));
6727
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006728 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6729 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6730 if (!filter || !hlua_filter_from_payload(filter))
6731 WILL_LJMP(lua_error(L));
6732
6733 offset = output;
6734 if (lua_gettop(L) > 2) {
6735 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6736 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006737 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006738 offset += output;
6739 if (offset < output || offset > input + output) {
6740 lua_pushfstring(L, "offset out of range.");
6741 WILL_LJMP(lua_error(L));
6742 }
6743 }
6744
6745 len = output + input - offset;
6746 if (lua_gettop(L) == 4) {
6747 len = MAY_LJMP(luaL_checkinteger(L, 4));
6748 if (!len)
6749 goto set;
6750 if (len == -1)
6751 len = output + input - offset;
6752 if (len < 0 || offset + len > output + input) {
6753 lua_pushfstring(L, "length out of range.");
6754 WILL_LJMP(lua_error(L));
6755 }
6756 }
6757
6758 set:
6759 /* Be sure we can copied the string once input data will be removed. */
6760 htx = htx_from_buf(&msg->chn->buf);
6761 if (sz > htx_free_data_space(htx) + len)
6762 lua_pushinteger(L, -1);
6763 else {
6764 _hlua_http_msg_delete(msg, filter, offset, len);
6765 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6766 lua_pushinteger(L, ret);
6767 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006768 return 1;
6769}
6770
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006771/* Prepends data into an HTTP message and forward it, from the filter point of
6772 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6773 * the channel function used to send data, this one can only be called inside a
6774 * filter, from http_payload callback. So it cannot yield. An exception is
6775 * returned if it is called from another callback.
6776 */
6777__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006778{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006779 struct http_msg *msg;
6780 struct filter *filter;
6781 struct htx *htx;
6782 const char *str;
6783 size_t offset, len, sz;
6784 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006785
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006786 MAY_LJMP(check_args(L, 2, "send"));
6787 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6788
6789 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006790 WILL_LJMP(lua_error(L));
6791
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006792 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6793 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6794 if (!filter || !hlua_filter_from_payload(filter))
6795 WILL_LJMP(lua_error(L));
6796
6797 /* Return an error if the channel's output is closed */
6798 if (unlikely(channel_output_closed(msg->chn))) {
6799 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006800 return 1;
6801 }
6802
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006803 htx = htx_from_buf(&msg->chn->buf);
6804 if (sz > htx_free_data_space(htx)) {
6805 lua_pushinteger(L, -1);
6806 return 1;
6807 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006808
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6810 if (ret > 0) {
6811 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6812
6813 FLT_OFF(filter, msg->chn) += ret;
6814 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6815 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6816 }
6817
6818 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006819 return 1;
6820}
6821
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006822/* Forwards a given amount of bytes. It return -1 if the channel's output is
6823 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6824 * channel function used to forward data, this one can only be called inside a
6825 * filter, from http_payload callback. So it cannot yield. An exception is
6826 * returned if it is called from another callback. All other functions deal with
6827 * DATA block, this one not.
6828*/
6829__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006830{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006831 struct http_msg *msg;
6832 struct filter *filter;
6833 size_t offset, len;
6834 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006835
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006836 MAY_LJMP(check_args(L, 2, "forward"));
6837 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6838
6839 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006840 WILL_LJMP(lua_error(L));
6841
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006842 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6843 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6844 if (!filter || !hlua_filter_from_payload(filter))
6845 WILL_LJMP(lua_error(L));
6846
6847 /* Nothing to do, just return */
6848 if (!fwd)
6849 goto end;
6850
6851 /* Return an error if the channel's output is closed */
6852 if (unlikely(channel_output_closed(msg->chn))) {
6853 ret = -1;
6854 goto end;
6855 }
6856
6857 ret = fwd;
6858 if (ret > len)
6859 ret = len;
6860
6861 if (ret) {
6862 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6863
6864 FLT_OFF(filter, msg->chn) += ret;
6865 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6866 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6867 }
6868
6869 end:
6870 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006871 return 1;
6872}
6873
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006874/* Set EOM flag on the HTX message.
6875 *
6876 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6877 * really know how to do without this feature.
6878 */
6879__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006880{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006881 struct http_msg *msg;
6882 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006883
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006884 MAY_LJMP(check_args(L, 1, "set_eom"));
6885 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6886 htx = htxbuf(&msg->chn->buf);
6887 htx->flags |= HTX_FL_EOM;
6888 return 0;
6889}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006890
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006891/* Unset EOM flag on the HTX message.
6892 *
6893 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6894 * really know how to do without this feature.
6895 */
6896__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6897{
6898 struct http_msg *msg;
6899 struct htx *htx;
6900
6901 MAY_LJMP(check_args(L, 1, "set_eom"));
6902 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6903 htx = htxbuf(&msg->chn->buf);
6904 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006905 return 0;
6906}
6907
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006908/*
6909 *
6910 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006911 * Class HTTPClient
6912 *
6913 *
6914 */
6915__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6916{
6917 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6918}
6919
William Lallemandf77f1de2021-09-28 19:10:38 +02006920
6921/* stops the httpclient and ask it to kill itself */
6922__LJMP static int hlua_httpclient_gc(lua_State *L)
6923{
6924 struct hlua_httpclient *hlua_hc;
6925
6926 MAY_LJMP(check_args(L, 1, "__gc"));
6927
6928 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6929
6930 httpclient_stop_and_destroy(hlua_hc->hc);
6931
6932 hlua_hc->hc = NULL;
6933
6934
6935 return 0;
6936}
6937
6938
William Lallemand3956c4e2021-09-21 16:25:15 +02006939__LJMP static int hlua_httpclient_new(lua_State *L)
6940{
6941 struct hlua_httpclient *hlua_hc;
6942 struct hlua *hlua;
6943
6944 /* Get hlua struct, or NULL if we execute from main lua state */
6945 hlua = hlua_gethlua(L);
6946 if (!hlua)
6947 return 0;
6948
6949 /* Check stack size. */
6950 if (!lua_checkstack(L, 3)) {
6951 hlua_pusherror(L, "httpclient: full stack");
6952 goto err;
6953 }
6954 /* Create the object: obj[0] = userdata. */
6955 lua_newtable(L);
6956 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6957 lua_rawseti(L, -2, 0);
6958 memset(hlua_hc, 0, sizeof(*hlua_hc));
6959
6960 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6961 if (!hlua_hc->hc)
6962 goto err;
6963
6964 /* Pop a class stream metatable and affect it to the userdata. */
6965 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6966 lua_setmetatable(L, -2);
6967
6968 return 1;
6969
6970 err:
6971 WILL_LJMP(lua_error(L));
6972 return 0;
6973}
6974
6975
6976/*
6977 * Callback of the httpclient, this callback wakes the lua task up, once the
6978 * httpclient receives some data
6979 *
6980 */
6981
William Lallemandbd5739e2021-10-28 15:41:38 +02006982static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02006983{
6984 struct hlua *hlua = hc->caller;
6985
6986 if (!hlua || !hlua->task)
6987 return;
6988
6989 task_wakeup(hlua->task, TASK_WOKEN_MSG);
6990}
6991
6992/*
William Lallemandd7df73a2021-09-23 17:54:00 +02006993 * Fill the lua stack with headers from the httpclient response
6994 * This works the same way as the hlua_http_get_headers() function
6995 */
6996__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
6997{
6998 struct http_hdr *hdr;
6999
7000 lua_newtable(L);
7001
William Lallemandef574b22021-10-05 16:19:31 +02007002 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007003 struct ist n, v;
7004 int len;
7005
7006 n = hdr->n;
7007 v = hdr->v;
7008
7009 /* Check for existing entry:
7010 * assume that the table is on the top of the stack, and
7011 * push the key in the stack, the function lua_gettable()
7012 * perform the lookup.
7013 */
7014
7015 lua_pushlstring(L, n.ptr, n.len);
7016 lua_gettable(L, -2);
7017
7018 switch (lua_type(L, -1)) {
7019 case LUA_TNIL:
7020 /* Table not found, create it. */
7021 lua_pop(L, 1); /* remove the nil value. */
7022 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7023 lua_newtable(L); /* create and push empty table. */
7024 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7025 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7026 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7027 break;
7028
7029 case LUA_TTABLE:
7030 /* Entry found: push the value in the table. */
7031 len = lua_rawlen(L, -1);
7032 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7033 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7034 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7035 break;
7036
7037 default:
7038 /* Other cases are errors. */
7039 hlua_pusherror(L, "internal error during the parsing of headers.");
7040 WILL_LJMP(lua_error(L));
7041 }
7042 }
7043 return 1;
7044}
7045
7046/*
William Lallemand746e6f32021-10-06 10:57:44 +02007047 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7048 *
7049 * Caller must free the result
7050 */
7051struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7052{
7053 struct http_hdr hdrs[global.tune.max_http_hdr];
7054 struct http_hdr *result = NULL;
7055 uint32_t hdr_num = 0;
7056
7057 lua_pushnil(L);
7058 while (lua_next(L, -2) != 0) {
7059 struct ist name, value;
7060 const char *n, *v;
7061 size_t nlen, vlen;
7062
7063 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7064 /* Skip element if the key is not a string or if the value is not a table */
7065 goto next_hdr;
7066 }
7067
7068 n = lua_tolstring(L, -2, &nlen);
7069 name = ist2(n, nlen);
7070
7071 /* Loop on header's values */
7072 lua_pushnil(L);
7073 while (lua_next(L, -2)) {
7074 if (!lua_isstring(L, -1)) {
7075 /* Skip the value if it is not a string */
7076 goto next_value;
7077 }
7078
7079 v = lua_tolstring(L, -1, &vlen);
7080 value = ist2(v, vlen);
7081 name = ist2(n, nlen);
7082
7083 hdrs[hdr_num].n = istdup(name);
7084 hdrs[hdr_num].v = istdup(value);
7085
7086 hdr_num++;
7087
7088 next_value:
7089 lua_pop(L, 1);
7090 }
7091
7092 next_hdr:
7093 lua_pop(L, 1);
7094
7095 }
7096
7097 if (hdr_num) {
7098 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007099 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007100 if (!result)
7101 goto skip_headers;
7102 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7103
7104 result[hdr_num].n = IST_NULL;
7105 result[hdr_num].v = IST_NULL;
7106 }
7107
7108skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007109
7110 return result;
7111}
7112
7113
William Lallemandbd5739e2021-10-28 15:41:38 +02007114/*
7115 * For each yield, checks if there is some data in the httpclient and push them
7116 * in the lua buffer, once the httpclient finished its job, push the result on
7117 * the stack
7118 */
7119__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7120{
7121 struct buffer *tr;
7122 int res;
7123 struct hlua *hlua = hlua_gethlua(L);
7124 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7125
7126
7127 tr = get_trash_chunk();
7128
7129 res = httpclient_res_xfer(hlua_hc->hc, tr);
7130 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7131
7132 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7133
7134 luaL_pushresult(&hlua_hc->b);
7135 lua_settable(L, -3);
7136
7137 lua_pushstring(L, "status");
7138 lua_pushinteger(L, hlua_hc->hc->res.status);
7139 lua_settable(L, -3);
7140
7141
7142 lua_pushstring(L, "reason");
7143 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7144 lua_settable(L, -3);
7145
7146 lua_pushstring(L, "headers");
7147 hlua_httpclient_get_headers(L, hlua_hc);
7148 lua_settable(L, -3);
7149
7150 return 1;
7151 }
7152
7153 if (httpclient_data(hlua_hc->hc))
7154 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7155
7156 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7157
7158 return 0;
7159}
7160
7161/*
7162 * Call this when trying to stream a body during a request
7163 */
7164__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7165{
7166 struct hlua *hlua;
7167 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7168 const char *body_str = NULL;
7169 int ret;
7170 int end = 0;
7171 size_t buf_len;
7172 size_t to_send = 0;
7173
7174 hlua = hlua_gethlua(L);
7175
7176 if (!hlua || !hlua->task)
7177 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7178 "'frontend', 'backend' or 'task'"));
7179
7180 ret = lua_getfield(L, -1, "body");
7181 if (ret != LUA_TSTRING)
7182 goto rcv;
7183
7184 body_str = lua_tolstring(L, -1, &buf_len);
7185 lua_pop(L, 1);
7186
Christopher Fauletfc591292022-01-12 14:46:03 +01007187 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007188
7189 if ((hlua_hc->sent + to_send) >= buf_len)
7190 end = 1;
7191
7192 /* the end flag is always set since we are using the whole remaining size */
7193 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7194
7195 if (buf_len > hlua_hc->sent) {
7196 /* still need to process the buffer */
7197 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7198 } else {
7199 goto rcv;
7200 /* we sent the whole request buffer we can recv */
7201 }
7202 return 0;
7203
7204rcv:
7205
7206 /* we return a "res" object */
7207 lua_newtable(L);
7208
William Lallemandbd5739e2021-10-28 15:41:38 +02007209 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007210 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007211
William Lallemand933fe392021-11-04 09:45:58 +01007212 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007213 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7214
7215 return 1;
7216}
William Lallemand746e6f32021-10-06 10:57:44 +02007217
William Lallemand3956c4e2021-09-21 16:25:15 +02007218/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007219 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007220 */
7221
William Lallemanddc2cc902021-10-26 11:43:26 +02007222__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007223{
7224 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007225 struct http_hdr *hdrs = NULL;
7226 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007227 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007228 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007229 const char *body_str = NULL;
William Lallemandb4a4ef62022-02-23 14:18:16 +01007230 int timeout;
William Lallemandbd5739e2021-10-28 15:41:38 +02007231 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007232 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007233
7234 hlua = hlua_gethlua(L);
7235
7236 if (!hlua || !hlua->task)
7237 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7238 "'frontend', 'backend' or 'task'"));
7239
William Lallemand746e6f32021-10-06 10:57:44 +02007240 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7241 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7242
William Lallemand4f4f2b72022-02-17 20:00:23 +01007243 hlua_hc = hlua_checkhttpclient(L, 1);
7244
7245 ret = lua_getfield(L, -1, "dst");
7246 if (ret == LUA_TSTRING) {
7247 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7248 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
7249 }
7250 lua_pop(L, 1);
7251
William Lallemand746e6f32021-10-06 10:57:44 +02007252 ret = lua_getfield(L, -1, "url");
7253 if (ret == LUA_TSTRING) {
7254 url_str = lua_tostring(L, -1);
7255 }
7256 lua_pop(L, 1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007257
William Lallemandb4a4ef62022-02-23 14:18:16 +01007258 ret = lua_getfield(L, -1, "timeout");
7259 if (ret == LUA_TNUMBER) {
7260 timeout = lua_tointeger(L, -1);
7261 httpclient_set_timeout(hlua_hc->hc, timeout);
7262 }
William Lallemandab90ee82022-02-23 15:16:08 +01007263 lua_pop(L, 1);
William Lallemandb4a4ef62022-02-23 14:18:16 +01007264
William Lallemand746e6f32021-10-06 10:57:44 +02007265 ret = lua_getfield(L, -1, "headers");
7266 if (ret == LUA_TTABLE) {
7267 hdrs = hlua_httpclient_table_to_hdrs(L);
7268 }
7269 lua_pop(L, 1);
William Lallemand79416cb2021-09-24 14:51:44 +02007270
William Lallemanddec25c32021-10-25 19:48:37 +02007271 ret = lua_getfield(L, -1, "body");
7272 if (ret == LUA_TSTRING) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007273 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemanddec25c32021-10-25 19:48:37 +02007274 }
William Lallemandbd5739e2021-10-28 15:41:38 +02007275
William Lallemanddec25c32021-10-25 19:48:37 +02007276 lua_pop(L, 1);
7277
William Lallemand746e6f32021-10-06 10:57:44 +02007278 if (!url_str) {
7279 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7280 return 0;
7281 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007282
William Lallemand3956c4e2021-09-21 16:25:15 +02007283
7284 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007285 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007286
7287 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007288 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7289 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7290 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007291
William Lallemandbd5739e2021-10-28 15:41:38 +02007292 /* a body is available, it will use the request callback */
7293 if (body_str) {
7294 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7295 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007296
William Lallemandbd5739e2021-10-28 15:41:38 +02007297 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007298
William Lallemand746e6f32021-10-06 10:57:44 +02007299 /* free the temporary headers array */
7300 hdrs_i = hdrs;
7301 while (hdrs_i && isttest(hdrs_i->n)) {
7302 istfree(&hdrs_i->n);
7303 istfree(&hdrs_i->v);
7304 hdrs_i++;
7305 }
7306 ha_free(&hdrs);
7307
7308
William Lallemand6137a9e2021-10-26 15:01:53 +02007309 if (ret != ERR_NONE) {
7310 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7311 return 0;
7312 }
7313
William Lallemand6137a9e2021-10-26 15:01:53 +02007314 httpclient_start(hlua_hc->hc);
7315
William Lallemandbd5739e2021-10-28 15:41:38 +02007316 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007317
William Lallemand3956c4e2021-09-21 16:25:15 +02007318 return 0;
7319}
7320
7321/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007322 * Sends an HTTP HEAD request and wait for a response
7323 *
7324 * httpclient:head(url, headers, payload)
7325 */
7326__LJMP static int hlua_httpclient_head(lua_State *L)
7327{
7328 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7329}
7330
7331/*
7332 * Send an HTTP GET request and wait for a response
7333 *
7334 * httpclient:get(url, headers, payload)
7335 */
7336__LJMP static int hlua_httpclient_get(lua_State *L)
7337{
7338 return hlua_httpclient_send(L, HTTP_METH_GET);
7339
7340}
7341
7342/*
7343 * Sends an HTTP PUT request and wait for a response
7344 *
7345 * httpclient:put(url, headers, payload)
7346 */
7347__LJMP static int hlua_httpclient_put(lua_State *L)
7348{
7349 return hlua_httpclient_send(L, HTTP_METH_PUT);
7350}
7351
7352/*
7353 * Send an HTTP POST request and wait for a response
7354 *
7355 * httpclient:post(url, headers, payload)
7356 */
7357__LJMP static int hlua_httpclient_post(lua_State *L)
7358{
7359 return hlua_httpclient_send(L, HTTP_METH_POST);
7360}
7361
7362
7363/*
7364 * Sends an HTTP DELETE request and wait for a response
7365 *
7366 * httpclient:delete(url, headers, payload)
7367 */
7368__LJMP static int hlua_httpclient_delete(lua_State *L)
7369{
7370 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7371}
7372
7373/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007374 *
7375 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007376 * Class TXN
7377 *
7378 *
7379 */
7380
7381/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007382 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007383 */
7384__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7385{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007386 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007387}
7388
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007389__LJMP static int hlua_set_var(lua_State *L)
7390{
7391 struct hlua_txn *htxn;
7392 const char *name;
7393 size_t len;
7394 struct sample smp;
7395
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007396 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7397 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007398
7399 /* It is useles to retrieve the stream, but this function
7400 * runs only in a stream context.
7401 */
7402 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7403 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7404
7405 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007406 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007407 hlua_lua2smp(L, 3, &smp);
7408
7409 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007410 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007411
7412 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7413 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7414 else
7415 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7416
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007417 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007418}
7419
Christopher Faulet85d79c92016-11-09 16:54:56 +01007420__LJMP static int hlua_unset_var(lua_State *L)
7421{
7422 struct hlua_txn *htxn;
7423 const char *name;
7424 size_t len;
7425 struct sample smp;
7426
7427 MAY_LJMP(check_args(L, 2, "unset_var"));
7428
7429 /* It is useles to retrieve the stream, but this function
7430 * runs only in a stream context.
7431 */
7432 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7433 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7434
7435 /* Unset the variable. */
7436 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007437 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7438 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007439}
7440
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007441__LJMP static int hlua_get_var(lua_State *L)
7442{
7443 struct hlua_txn *htxn;
7444 const char *name;
7445 size_t len;
7446 struct sample smp;
7447
7448 MAY_LJMP(check_args(L, 2, "get_var"));
7449
7450 /* It is useles to retrieve the stream, but this function
7451 * runs only in a stream context.
7452 */
7453 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7454 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7455
Willy Tarreau7560dd42016-03-10 16:28:58 +01007456 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007457 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007458 lua_pushnil(L);
7459 return 1;
7460 }
7461
7462 return hlua_smp2lua(L, &smp);
7463}
7464
Willy Tarreau59551662015-03-10 14:23:13 +01007465__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007466{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007467 struct hlua *hlua;
7468
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007469 MAY_LJMP(check_args(L, 2, "set_priv"));
7470
Willy Tarreau87b09662015-04-03 00:22:06 +02007471 /* It is useles to retrieve the stream, but this function
7472 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007473 */
7474 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007475
7476 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007477 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007478 if (!hlua)
7479 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007480
7481 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007482 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007483
7484 /* Get and store new value. */
7485 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7486 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7487
7488 return 0;
7489}
7490
Willy Tarreau59551662015-03-10 14:23:13 +01007491__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007492{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007493 struct hlua *hlua;
7494
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007495 MAY_LJMP(check_args(L, 1, "get_priv"));
7496
Willy Tarreau87b09662015-04-03 00:22:06 +02007497 /* It is useles to retrieve the stream, but this function
7498 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007499 */
7500 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007501
7502 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007503 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007504 if (!hlua) {
7505 lua_pushnil(L);
7506 return 1;
7507 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007508
7509 /* Push configuration index in the stack. */
7510 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7511
7512 return 1;
7513}
7514
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007515/* Create stack entry containing a class TXN. This function
7516 * return 0 if the stack does not contains free slots,
7517 * otherwise it returns 1.
7518 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007519static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007520{
Willy Tarreaude491382015-04-06 11:04:28 +02007521 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007522
7523 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007524 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007525 return 0;
7526
7527 /* NOTE: The allocation never fails. The failure
7528 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007529 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007530 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007531 /* Create the object: obj[0] = userdata. */
7532 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007533 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007534 lua_rawseti(L, -2, 0);
7535
Willy Tarreaude491382015-04-06 11:04:28 +02007536 htxn->s = s;
7537 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007538 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007539 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007540
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007541 /* Create the "f" field that contains a list of fetches. */
7542 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007543 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007544 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007545 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007546
7547 /* Create the "sf" field that contains a list of stringsafe fetches. */
7548 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007549 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007550 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007551 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007552
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007553 /* Create the "c" field that contains a list of converters. */
7554 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007555 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007556 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007557 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007558
7559 /* Create the "sc" field that contains a list of stringsafe converters. */
7560 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007561 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007562 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007563 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007564
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007565 /* Create the "req" field that contains the request channel object. */
7566 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007567 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007568 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007569 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007570
7571 /* Create the "res" field that contains the response channel object. */
7572 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007573 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007574 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007575 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007576
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007577 /* Creates the HTTP object is the current proxy allows http. */
7578 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007579 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007580 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007581 return 0;
7582 }
7583 else
7584 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007585 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007586
Christopher Faulet78c35472020-02-26 17:14:08 +01007587 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7588 /* HTTPMessage object are created when a lua TXN is created from
7589 * a filter context only
7590 */
7591
7592 /* Creates the HTTP-Request object is the current proxy allows http. */
7593 lua_pushstring(L, "http_req");
7594 if (p->mode == PR_MODE_HTTP) {
7595 if (!hlua_http_msg_new(L, &s->txn->req))
7596 return 0;
7597 }
7598 else
7599 lua_pushnil(L);
7600 lua_rawset(L, -3);
7601
7602 /* Creates the HTTP-Response object is the current proxy allows http. */
7603 lua_pushstring(L, "http_res");
7604 if (p->mode == PR_MODE_HTTP) {
7605 if (!hlua_http_msg_new(L, &s->txn->rsp))
7606 return 0;
7607 }
7608 else
7609 lua_pushnil(L);
7610 lua_rawset(L, -3);
7611 }
7612
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007613 /* Pop a class sesison metatable and affect it to the userdata. */
7614 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7615 lua_setmetatable(L, -2);
7616
7617 return 1;
7618}
7619
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007620__LJMP static int hlua_txn_deflog(lua_State *L)
7621{
7622 const char *msg;
7623 struct hlua_txn *htxn;
7624
7625 MAY_LJMP(check_args(L, 2, "deflog"));
7626 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7627 msg = MAY_LJMP(luaL_checkstring(L, 2));
7628
7629 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7630 return 0;
7631}
7632
7633__LJMP static int hlua_txn_log(lua_State *L)
7634{
7635 int level;
7636 const char *msg;
7637 struct hlua_txn *htxn;
7638
7639 MAY_LJMP(check_args(L, 3, "log"));
7640 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7641 level = MAY_LJMP(luaL_checkinteger(L, 2));
7642 msg = MAY_LJMP(luaL_checkstring(L, 3));
7643
7644 if (level < 0 || level >= NB_LOG_LEVELS)
7645 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7646
7647 hlua_sendlog(htxn->s->be, level, msg);
7648 return 0;
7649}
7650
7651__LJMP static int hlua_txn_log_debug(lua_State *L)
7652{
7653 const char *msg;
7654 struct hlua_txn *htxn;
7655
7656 MAY_LJMP(check_args(L, 2, "Debug"));
7657 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7658 msg = MAY_LJMP(luaL_checkstring(L, 2));
7659 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7660 return 0;
7661}
7662
7663__LJMP static int hlua_txn_log_info(lua_State *L)
7664{
7665 const char *msg;
7666 struct hlua_txn *htxn;
7667
7668 MAY_LJMP(check_args(L, 2, "Info"));
7669 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7670 msg = MAY_LJMP(luaL_checkstring(L, 2));
7671 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7672 return 0;
7673}
7674
7675__LJMP static int hlua_txn_log_warning(lua_State *L)
7676{
7677 const char *msg;
7678 struct hlua_txn *htxn;
7679
7680 MAY_LJMP(check_args(L, 2, "Warning"));
7681 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7682 msg = MAY_LJMP(luaL_checkstring(L, 2));
7683 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7684 return 0;
7685}
7686
7687__LJMP static int hlua_txn_log_alert(lua_State *L)
7688{
7689 const char *msg;
7690 struct hlua_txn *htxn;
7691
7692 MAY_LJMP(check_args(L, 2, "Alert"));
7693 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7694 msg = MAY_LJMP(luaL_checkstring(L, 2));
7695 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7696 return 0;
7697}
7698
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007699__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7700{
7701 struct hlua_txn *htxn;
7702 int ll;
7703
7704 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7705 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7706 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7707
7708 if (ll < 0 || ll > 7)
7709 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7710
7711 htxn->s->logs.level = ll;
7712 return 0;
7713}
7714
7715__LJMP static int hlua_txn_set_tos(lua_State *L)
7716{
7717 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007718 int tos;
7719
7720 MAY_LJMP(check_args(L, 2, "set_tos"));
7721 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7722 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7723
Willy Tarreau1a18b542018-12-11 16:37:42 +01007724 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007725 return 0;
7726}
7727
7728__LJMP static int hlua_txn_set_mark(lua_State *L)
7729{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007730 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007731 int mark;
7732
7733 MAY_LJMP(check_args(L, 2, "set_mark"));
7734 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7735 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7736
Lukas Tribus579e3e32019-08-11 18:03:45 +02007737 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007738 return 0;
7739}
7740
Patrick Hemmer268a7072018-05-11 12:52:31 -04007741__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7742{
7743 struct hlua_txn *htxn;
7744
7745 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7746 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7747 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7748 return 0;
7749}
7750
7751__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7752{
7753 struct hlua_txn *htxn;
7754
7755 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7756 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7757 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7758 return 0;
7759}
7760
Christopher Faulet700d9e82020-01-31 12:21:52 +01007761/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007762 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007763 * message and terminate the transaction. It returns 1 on success and 0 on
7764 * error. The Reply must be on top of the stack.
7765 */
7766__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7767{
7768 struct htx *htx;
7769 struct htx_sl *sl;
7770 struct h1m h1m;
7771 const char *status, *reason, *body;
7772 size_t status_len, reason_len, body_len;
7773 int ret, code, flags;
7774
7775 code = 200;
7776 status = "200";
7777 status_len = 3;
7778 ret = lua_getfield(L, -1, "status");
7779 if (ret == LUA_TNUMBER) {
7780 code = lua_tointeger(L, -1);
7781 status = lua_tolstring(L, -1, &status_len);
7782 }
7783 lua_pop(L, 1);
7784
7785 reason = http_get_reason(code);
7786 reason_len = strlen(reason);
7787 ret = lua_getfield(L, -1, "reason");
7788 if (ret == LUA_TSTRING)
7789 reason = lua_tolstring(L, -1, &reason_len);
7790 lua_pop(L, 1);
7791
7792 body = NULL;
7793 body_len = 0;
7794 ret = lua_getfield(L, -1, "body");
7795 if (ret == LUA_TSTRING)
7796 body = lua_tolstring(L, -1, &body_len);
7797 lua_pop(L, 1);
7798
7799 /* Prepare the response before inserting the headers */
7800 h1m_init_res(&h1m);
7801 htx = htx_from_buf(&s->res.buf);
7802 channel_htx_truncate(&s->res, htx);
7803 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7804 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7805 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7806 ist2(status, status_len), ist2(reason, reason_len));
7807 }
7808 else {
7809 flags = HTX_SL_F_IS_RESP;
7810 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7811 ist2(status, status_len), ist2(reason, reason_len));
7812 }
7813 if (!sl)
7814 goto fail;
7815 sl->info.res.status = code;
7816
7817 /* Push in the stack the "headers" entry. */
7818 ret = lua_getfield(L, -1, "headers");
7819 if (ret != LUA_TTABLE)
7820 goto skip_headers;
7821
7822 lua_pushnil(L);
7823 while (lua_next(L, -2) != 0) {
7824 struct ist name, value;
7825 const char *n, *v;
7826 size_t nlen, vlen;
7827
7828 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7829 /* Skip element if the key is not a string or if the value is not a table */
7830 goto next_hdr;
7831 }
7832
7833 n = lua_tolstring(L, -2, &nlen);
7834 name = ist2(n, nlen);
7835 if (isteqi(name, ist("content-length"))) {
7836 /* Always skip content-length header. It will be added
7837 * later with the correct len
7838 */
7839 goto next_hdr;
7840 }
7841
7842 /* Loop on header's values */
7843 lua_pushnil(L);
7844 while (lua_next(L, -2)) {
7845 if (!lua_isstring(L, -1)) {
7846 /* Skip the value if it is not a string */
7847 goto next_value;
7848 }
7849
7850 v = lua_tolstring(L, -1, &vlen);
7851 value = ist2(v, vlen);
7852
7853 if (isteqi(name, ist("transfer-encoding")))
7854 h1_parse_xfer_enc_header(&h1m, value);
7855 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7856 goto fail;
7857
7858 next_value:
7859 lua_pop(L, 1);
7860 }
7861
7862 next_hdr:
7863 lua_pop(L, 1);
7864 }
7865 skip_headers:
7866 lua_pop(L, 1);
7867
7868 /* Update h1m flags: CLEN is set if CHNK is not present */
7869 if (!(h1m.flags & H1_MF_CHNK)) {
7870 const char *clen = ultoa(body_len);
7871
7872 h1m.flags |= H1_MF_CLEN;
7873 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7874 goto fail;
7875 }
7876 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7877 h1m.flags |= H1_MF_XFER_LEN;
7878
7879 /* Update HTX start-line flags */
7880 if (h1m.flags & H1_MF_XFER_ENC)
7881 flags |= HTX_SL_F_XFER_ENC;
7882 if (h1m.flags & H1_MF_XFER_LEN) {
7883 flags |= HTX_SL_F_XFER_LEN;
7884 if (h1m.flags & H1_MF_CHNK)
7885 flags |= HTX_SL_F_CHNK;
7886 else if (h1m.flags & H1_MF_CLEN)
7887 flags |= HTX_SL_F_CLEN;
7888 if (h1m.body_len == 0)
7889 flags |= HTX_SL_F_BODYLESS;
7890 }
7891 sl->flags |= flags;
7892
7893
7894 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007895 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007896 goto fail;
7897
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007898 htx->flags |= HTX_FL_EOM;
7899
Christopher Faulet700d9e82020-01-31 12:21:52 +01007900 /* Now, forward the response and terminate the transaction */
7901 s->txn->status = code;
7902 htx_to_buf(htx, &s->res.buf);
7903 if (!http_forward_proxy_resp(s, 1))
7904 goto fail;
7905
7906 return 1;
7907
7908 fail:
7909 channel_htx_truncate(&s->res, htx);
7910 return 0;
7911}
7912
7913/* Terminate a transaction if called from a lua action. For TCP streams,
7914 * processing is just aborted. Nothing is returned to the client and all
7915 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7916 * is forwarded to the client before terminating the transaction. On success,
7917 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7918 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7919 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007920 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007921__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007922{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007923 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007924 struct stream *s;
7925 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007926
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007927 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007928
Christopher Faulet700d9e82020-01-31 12:21:52 +01007929 /* If the flags NOTERM is set, we cannot terminate the session, so we
7930 * just end the execution of the current lua code. */
7931 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007932 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007933
Christopher Faulet700d9e82020-01-31 12:21:52 +01007934 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007935 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007936 struct channel *req = &s->req;
7937 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007938
Christopher Faulet700d9e82020-01-31 12:21:52 +01007939 channel_auto_read(req);
7940 channel_abort(req);
7941 channel_auto_close(req);
7942 channel_erase(req);
7943
7944 res->wex = tick_add_ifset(now_ms, res->wto);
7945 channel_auto_read(res);
7946 channel_auto_close(res);
7947 channel_shutr_now(res);
7948
7949 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7950 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007951 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007952
Christopher Faulet700d9e82020-01-31 12:21:52 +01007953 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7954 /* No reply or invalid reply */
7955 s->txn->status = 0;
7956 http_reply_and_close(s, 0, NULL);
7957 }
7958 else {
7959 /* Remove extra args to have the reply on top of the stack */
7960 if (lua_gettop(L) > 2)
7961 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007962
Christopher Faulet700d9e82020-01-31 12:21:52 +01007963 if (!hlua_txn_forward_reply(L, s)) {
7964 if (!(s->flags & SF_ERR_MASK))
7965 s->flags |= SF_ERR_PRXCOND;
7966 lua_pushinteger(L, ACT_RET_ERR);
7967 WILL_LJMP(hlua_done(L));
7968 return 0; /* Never reached */
7969 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007970 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007971
Christopher Faulet700d9e82020-01-31 12:21:52 +01007972 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7973 if (htxn->dir == SMP_OPT_DIR_REQ) {
7974 /* let's log the request time */
7975 s->logs.tv_request = now;
7976 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007977 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007978 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007979
Christopher Faulet700d9e82020-01-31 12:21:52 +01007980 done:
7981 if (!(s->flags & SF_ERR_MASK))
7982 s->flags |= SF_ERR_LOCAL;
7983 if (!(s->flags & SF_FINST_MASK))
7984 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007985
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007986 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7987 lua_pushinteger(L, -1);
7988 else
7989 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007990 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007991 return 0;
7992}
7993
Christopher Faulet700d9e82020-01-31 12:21:52 +01007994/*
7995 *
7996 *
7997 * Class REPLY
7998 *
7999 *
8000 */
8001
8002/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8003 * free slots, the function fails and returns 0;
8004 */
8005static int hlua_txn_reply_new(lua_State *L)
8006{
8007 struct hlua_txn *htxn;
8008 const char *reason, *body = NULL;
8009 int ret, status;
8010
8011 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008012 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008013 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8014 WILL_LJMP(lua_error(L));
8015 }
8016
8017 /* Default value */
8018 status = 200;
8019 reason = http_get_reason(status);
8020
8021 if (lua_istable(L, 2)) {
8022 /* load status and reason from the table argument at index 2 */
8023 ret = lua_getfield(L, 2, "status");
8024 if (ret == LUA_TNIL)
8025 goto reason;
8026 else if (ret != LUA_TNUMBER) {
8027 /* invalid status: ignore the reason */
8028 goto body;
8029 }
8030 status = lua_tointeger(L, -1);
8031
8032 reason:
8033 lua_pop(L, 1); /* restore the stack: remove status */
8034 ret = lua_getfield(L, 2, "reason");
8035 if (ret == LUA_TSTRING)
8036 reason = lua_tostring(L, -1);
8037
8038 body:
8039 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8040 ret = lua_getfield(L, 2, "body");
8041 if (ret == LUA_TSTRING)
8042 body = lua_tostring(L, -1);
8043 lua_pop(L, 1); /* restore the stack: remove body */
8044 }
8045
8046 /* Create the Reply table */
8047 lua_newtable(L);
8048
8049 /* Add status element */
8050 lua_pushstring(L, "status");
8051 lua_pushinteger(L, status);
8052 lua_settable(L, -3);
8053
8054 /* Add reason element */
8055 reason = http_get_reason(status);
8056 lua_pushstring(L, "reason");
8057 lua_pushstring(L, reason);
8058 lua_settable(L, -3);
8059
8060 /* Add body element, nil if undefined */
8061 lua_pushstring(L, "body");
8062 if (body)
8063 lua_pushstring(L, body);
8064 else
8065 lua_pushnil(L);
8066 lua_settable(L, -3);
8067
8068 /* Add headers element */
8069 lua_pushstring(L, "headers");
8070 lua_newtable(L);
8071
8072 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8073 if (lua_istable(L, 2)) {
8074 /* load headers from the table argument at index 2. If it is a table, copy it. */
8075 ret = lua_getfield(L, 2, "headers");
8076 if (ret == LUA_TTABLE) {
8077 /* stack: [ ... <headers:table>, <table> ] */
8078 lua_pushnil(L);
8079 while (lua_next(L, -2) != 0) {
8080 /* stack: [ ... <headers:table>, <table>, k, v] */
8081 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8082 /* invalid value type, skip it */
8083 lua_pop(L, 1);
8084 continue;
8085 }
8086
8087
8088 /* Duplicate the key and swap it with the value. */
8089 lua_pushvalue(L, -2);
8090 lua_insert(L, -2);
8091 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8092
8093 lua_newtable(L);
8094 lua_insert(L, -2);
8095 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8096
8097 if (lua_isstring(L, -1)) {
8098 /* push the value in the inner table */
8099 lua_rawseti(L, -2, 1);
8100 }
8101 else { /* table */
8102 lua_pushnil(L);
8103 while (lua_next(L, -2) != 0) {
8104 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8105 if (!lua_isstring(L, -1)) {
8106 /* invalid value type, skip it*/
8107 lua_pop(L, 1);
8108 continue;
8109 }
8110 /* push the value in the inner table */
8111 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8112 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8113 }
8114 lua_pop(L, 1);
8115 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8116 }
8117
8118 /* push (k,v) on the stack in the headers table:
8119 * stack: [ ... <headers:table>, <table>, k, k, v ]
8120 */
8121 lua_settable(L, -5);
8122 /* stack: [ ... <headers:table>, <table>, k ] */
8123 }
8124 }
8125 lua_pop(L, 1);
8126 }
8127 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8128 lua_settable(L, -3);
8129 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8130
8131 /* Pop a class sesison metatable and affect it to the userdata. */
8132 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8133 lua_setmetatable(L, -2);
8134 return 1;
8135}
8136
8137/* Set the reply status code, and optionally the reason. If no reason is
8138 * provided, the default one corresponding to the status code is used.
8139 */
8140__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8141{
8142 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8143 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8144
8145 /* First argument (self) must be a table */
8146 luaL_checktype(L, 1, LUA_TTABLE);
8147
8148 if (status < 100 || status > 599) {
8149 lua_pushboolean(L, 0);
8150 return 1;
8151 }
8152 if (!reason)
8153 reason = http_get_reason(status);
8154
8155 lua_pushinteger(L, status);
8156 lua_setfield(L, 1, "status");
8157
8158 lua_pushstring(L, reason);
8159 lua_setfield(L, 1, "reason");
8160
8161 lua_pushboolean(L, 1);
8162 return 1;
8163}
8164
8165/* Add a header into the reply object. Each header name is associated to an
8166 * array of values in the "headers" table. If the header name is not found, a
8167 * new entry is created.
8168 */
8169__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8170{
8171 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8172 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8173 int ret;
8174
8175 /* First argument (self) must be a table */
8176 luaL_checktype(L, 1, LUA_TTABLE);
8177
8178 /* Push in the stack the "headers" entry. */
8179 ret = lua_getfield(L, 1, "headers");
8180 if (ret != LUA_TTABLE) {
8181 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8182 WILL_LJMP(lua_error(L));
8183 }
8184
8185 /* check if the header is already registered. If not, register it. */
8186 ret = lua_getfield(L, -1, name);
8187 if (ret == LUA_TNIL) {
8188 /* Entry not found. */
8189 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8190
8191 /* Insert the new header name in the array in the top of the stack.
8192 * It left the new array in the top of the stack.
8193 */
8194 lua_newtable(L);
8195 lua_pushstring(L, name);
8196 lua_pushvalue(L, -2);
8197 lua_settable(L, -4);
8198 }
8199 else if (ret != LUA_TTABLE) {
8200 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8201 WILL_LJMP(lua_error(L));
8202 }
8203
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008204 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008205 * the header value as new entry.
8206 */
8207 lua_pushstring(L, value);
8208 ret = lua_rawlen(L, -2);
8209 lua_rawseti(L, -2, ret + 1);
8210
8211 lua_pushboolean(L, 1);
8212 return 1;
8213}
8214
8215/* Remove all occurrences of a given header name. */
8216__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8217{
8218 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8219 int ret;
8220
8221 /* First argument (self) must be a table */
8222 luaL_checktype(L, 1, LUA_TTABLE);
8223
8224 /* Push in the stack the "headers" entry. */
8225 ret = lua_getfield(L, 1, "headers");
8226 if (ret != LUA_TTABLE) {
8227 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8228 WILL_LJMP(lua_error(L));
8229 }
8230
8231 lua_pushstring(L, name);
8232 lua_pushnil(L);
8233 lua_settable(L, -3);
8234
8235 lua_pushboolean(L, 1);
8236 return 1;
8237}
8238
8239/* Set the reply's body. Overwrite any existing entry. */
8240__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8241{
8242 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8243
8244 /* First argument (self) must be a table */
8245 luaL_checktype(L, 1, LUA_TTABLE);
8246
8247 lua_pushstring(L, payload);
8248 lua_setfield(L, 1, "body");
8249
8250 lua_pushboolean(L, 1);
8251 return 1;
8252}
8253
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008254__LJMP static int hlua_log(lua_State *L)
8255{
8256 int level;
8257 const char *msg;
8258
8259 MAY_LJMP(check_args(L, 2, "log"));
8260 level = MAY_LJMP(luaL_checkinteger(L, 1));
8261 msg = MAY_LJMP(luaL_checkstring(L, 2));
8262
8263 if (level < 0 || level >= NB_LOG_LEVELS)
8264 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8265
8266 hlua_sendlog(NULL, level, msg);
8267 return 0;
8268}
8269
8270__LJMP static int hlua_log_debug(lua_State *L)
8271{
8272 const char *msg;
8273
8274 MAY_LJMP(check_args(L, 1, "debug"));
8275 msg = MAY_LJMP(luaL_checkstring(L, 1));
8276 hlua_sendlog(NULL, LOG_DEBUG, msg);
8277 return 0;
8278}
8279
8280__LJMP static int hlua_log_info(lua_State *L)
8281{
8282 const char *msg;
8283
8284 MAY_LJMP(check_args(L, 1, "info"));
8285 msg = MAY_LJMP(luaL_checkstring(L, 1));
8286 hlua_sendlog(NULL, LOG_INFO, msg);
8287 return 0;
8288}
8289
8290__LJMP static int hlua_log_warning(lua_State *L)
8291{
8292 const char *msg;
8293
8294 MAY_LJMP(check_args(L, 1, "warning"));
8295 msg = MAY_LJMP(luaL_checkstring(L, 1));
8296 hlua_sendlog(NULL, LOG_WARNING, msg);
8297 return 0;
8298}
8299
8300__LJMP static int hlua_log_alert(lua_State *L)
8301{
8302 const char *msg;
8303
8304 MAY_LJMP(check_args(L, 1, "alert"));
8305 msg = MAY_LJMP(luaL_checkstring(L, 1));
8306 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008307 return 0;
8308}
8309
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008310__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008311{
8312 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008313 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008314 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008315 return 0;
8316}
8317
8318__LJMP static int hlua_sleep(lua_State *L)
8319{
8320 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008321 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008322
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008323 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008324
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008325 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008326 wakeup_ms = tick_add(now_ms, delay);
8327 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008328
Willy Tarreau9635e032018-10-16 17:52:55 +02008329 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008330 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008331}
8332
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008333__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008334{
8335 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008336 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008337
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008338 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008339
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008340 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008341 wakeup_ms = tick_add(now_ms, delay);
8342 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008343
Willy Tarreau9635e032018-10-16 17:52:55 +02008344 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008345 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008346}
8347
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008348/* This functionis an LUA binding. it permits to give back
8349 * the hand at the HAProxy scheduler. It is used when the
8350 * LUA processing consumes a lot of time.
8351 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008352__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008353{
8354 return 0;
8355}
8356
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008357__LJMP static int hlua_yield(lua_State *L)
8358{
Willy Tarreau9635e032018-10-16 17:52:55 +02008359 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008360 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008361}
8362
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008363/* This function change the nice of the currently executed
8364 * task. It is used set low or high priority at the current
8365 * task.
8366 */
Willy Tarreau59551662015-03-10 14:23:13 +01008367__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008368{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008369 struct hlua *hlua;
8370 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008371
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008372 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008373 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008374
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008375 /* Get hlua struct, or NULL if we execute from main lua state */
8376 hlua = hlua_gethlua(L);
8377
8378 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008379 if (!hlua || !hlua->task)
8380 return 0;
8381
8382 if (nice < -1024)
8383 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008384 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008385 nice = 1024;
8386
8387 hlua->task->nice = nice;
8388 return 0;
8389}
8390
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008391/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008392 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8393 * return an E_AGAIN signal, the emmiter of this signal must set a
8394 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008395 *
8396 * Task wrapper are longjmp safe because the only one Lua code
8397 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008398 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008399struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008400{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008401 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008402 enum hlua_exec status;
8403
Christopher Faulet5bc99722018-04-25 10:34:45 +02008404 if (task->thread_mask == MAX_THREADS_MASK)
8405 task_set_affinity(task, tid_bit);
8406
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008407 /* If it is the first call to the task, we must initialize the
8408 * execution timeouts.
8409 */
8410 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008411 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008412
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008413 /* Execute the Lua code. */
8414 status = hlua_ctx_resume(hlua, 1);
8415
8416 switch (status) {
8417 /* finished or yield */
8418 case HLUA_E_OK:
8419 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008420 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008421 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008422 break;
8423
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008424 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008425 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008426 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008427 break;
8428
8429 /* finished with error. */
8430 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008431 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008432 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008433 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008434 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008435 break;
8436
8437 case HLUA_E_ERR:
8438 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008439 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008440 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008441 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008442 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008443 break;
8444 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008445 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008446}
8447
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008448/* This function is an LUA binding that register LUA function to be
8449 * executed after the HAProxy configuration parsing and before the
8450 * HAProxy scheduler starts. This function expect only one LUA
8451 * argument that is a function. This function returns nothing, but
8452 * throws if an error is encountered.
8453 */
8454__LJMP static int hlua_register_init(lua_State *L)
8455{
8456 struct hlua_init_function *init;
8457 int ref;
8458
8459 MAY_LJMP(check_args(L, 1, "register_init"));
8460
8461 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8462
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008463 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008464 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008465 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008466
8467 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008468 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008469 return 0;
8470}
8471
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008472/* This functio is an LUA binding. It permits to register a task
8473 * executed in parallel of the main HAroxy activity. The task is
8474 * created and it is set in the HAProxy scheduler. It can be called
8475 * from the "init" section, "post init" or during the runtime.
8476 *
8477 * Lua prototype:
8478 *
8479 * <none> core.register_task(<function>)
8480 */
8481static int hlua_register_task(lua_State *L)
8482{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008483 struct hlua *hlua = NULL;
8484 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008485 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008486 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008487
8488 MAY_LJMP(check_args(L, 1, "register_task"));
8489
8490 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8491
Thierry Fournier75fc0292020-11-28 13:18:56 +01008492 /* Get the reference state. If the reference is NULL, L is the master
8493 * state, otherwise hlua->T is.
8494 */
8495 hlua = hlua_gethlua(L);
8496 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008497 /* we are in runtime processing */
8498 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008499 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008500 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008501 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008502
Willy Tarreaubafbe012017-11-24 17:34:44 +01008503 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008504 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008505 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008506 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008507
Thierry Fournier59f11be2020-11-29 00:37:41 +01008508 /* We are in the common lua state, execute the task anywhere,
8509 * otherwise, inherit the current thread identifier
8510 */
8511 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008512 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008513 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008514 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008515 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008516 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008517
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008518 task->context = hlua;
8519 task->process = hlua_process_task;
8520
Thierry Fournier021d9862020-11-28 23:42:03 +01008521 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008522 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008523
8524 /* Restore the function in the stack. */
8525 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8526 hlua->nargs = 0;
8527
8528 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008529 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008530
8531 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008532
8533 alloc_error:
8534 task_destroy(task);
8535 hlua_ctx_destroy(hlua);
8536 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8537 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008538}
8539
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008540/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8541 * doesn't allow "yield" functions because the HAProxy engine cannot
8542 * resume converters.
8543 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008544static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008545{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008546 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008547 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008548 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008549
Willy Tarreaube508f12016-03-10 11:47:01 +01008550 if (!stream)
8551 return 0;
8552
Willy Tarreau87b09662015-04-03 00:22:06 +02008553 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008554 * Lua context can be not initialized. This behavior
8555 * permits to save performances because a systematic
8556 * Lua initialization cause 5% performances loss.
8557 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008558 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008559 struct hlua *hlua;
8560
8561 hlua = pool_alloc(pool_head_hlua);
8562 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008563 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8564 return 0;
8565 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008566 HLUA_INIT(hlua);
8567 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008568 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008569 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8570 return 0;
8571 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008572 }
8573
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008574 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008575 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008576
8577 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008578 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008579 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8580 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008581 else
8582 error = "critical error";
8583 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008584 return 0;
8585 }
8586
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008587 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008588 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008589 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008590 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008591 return 0;
8592 }
8593
8594 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008595 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008596
8597 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008598 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008599 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008600 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008601 return 0;
8602 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008603 hlua_smp2lua(stream->hlua->T, smp);
8604 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008605
8606 /* push keywords in the stack. */
8607 if (arg_p) {
8608 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008609 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008610 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008611 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008612 return 0;
8613 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008614 hlua_arg2lua(stream->hlua->T, arg_p);
8615 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008616 }
8617 }
8618
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008619 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008620 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008621
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008622 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008623 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008624 }
8625
8626 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008627 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008628 /* finished. */
8629 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008630 /* If the stack is empty, the function fails. */
8631 if (lua_gettop(stream->hlua->T) <= 0)
8632 return 0;
8633
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008634 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008635 hlua_lua2smp(stream->hlua->T, -1, smp);
8636 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008637 return 1;
8638
8639 /* yield. */
8640 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008641 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008642 return 0;
8643
8644 /* finished with error. */
8645 case HLUA_E_ERRMSG:
8646 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008647 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008648 fcn->name, lua_tostring(stream->hlua->T, -1));
8649 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008650 return 0;
8651
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008652 case HLUA_E_ETMOUT:
8653 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8654 return 0;
8655
8656 case HLUA_E_NOMEM:
8657 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8658 return 0;
8659
8660 case HLUA_E_YIELD:
8661 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8662 return 0;
8663
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008664 case HLUA_E_ERR:
8665 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008666 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008667 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008668
8669 default:
8670 return 0;
8671 }
8672}
8673
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008674/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8675 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008676 * resume sample-fetches. This function will be called by the sample
8677 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008678 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008679static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8680 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008681{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008682 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008683 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008684 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008685 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008686
Willy Tarreaube508f12016-03-10 11:47:01 +01008687 if (!stream)
8688 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008689
Willy Tarreau87b09662015-04-03 00:22:06 +02008690 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008691 * Lua context can be not initialized. This behavior
8692 * permits to save performances because a systematic
8693 * Lua initialization cause 5% performances loss.
8694 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008695 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008696 struct hlua *hlua;
8697
8698 hlua = pool_alloc(pool_head_hlua);
8699 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008700 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8701 return 0;
8702 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008703 hlua->T = NULL;
8704 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008705 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008706 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8707 return 0;
8708 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008709 }
8710
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008711 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008712 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008713
8714 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008715 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008716 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8717 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008718 else
8719 error = "critical error";
8720 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008721 return 0;
8722 }
8723
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008724 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008725 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008726 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008727 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008728 return 0;
8729 }
8730
8731 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008732 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008733
8734 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008735 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008736 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008737 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008738 return 0;
8739 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008740 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008741
8742 /* push keywords in the stack. */
8743 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8744 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008745 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008746 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008747 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008748 return 0;
8749 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008750 hlua_arg2lua(stream->hlua->T, arg_p);
8751 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008752 }
8753
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008754 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008755 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008756
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008757 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008758 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008759 }
8760
8761 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008762 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008763 /* finished. */
8764 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008765 /* If the stack is empty, the function fails. */
8766 if (lua_gettop(stream->hlua->T) <= 0)
8767 return 0;
8768
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008769 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008770 hlua_lua2smp(stream->hlua->T, -1, smp);
8771 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008772
8773 /* Set the end of execution flag. */
8774 smp->flags &= ~SMP_F_MAY_CHANGE;
8775 return 1;
8776
8777 /* yield. */
8778 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008779 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008780 return 0;
8781
8782 /* finished with error. */
8783 case HLUA_E_ERRMSG:
8784 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008785 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008786 fcn->name, lua_tostring(stream->hlua->T, -1));
8787 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008788 return 0;
8789
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008790 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008791 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8792 return 0;
8793
8794 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008795 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8796 return 0;
8797
8798 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008799 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8800 return 0;
8801
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008802 case HLUA_E_ERR:
8803 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008804 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008805 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008806
8807 default:
8808 return 0;
8809 }
8810}
8811
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008812/* This function is an LUA binding used for registering
8813 * "sample-conv" functions. It expects a converter name used
8814 * in the haproxy configuration file, and an LUA function.
8815 */
8816__LJMP static int hlua_register_converters(lua_State *L)
8817{
8818 struct sample_conv_kw_list *sck;
8819 const char *name;
8820 int ref;
8821 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008822 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008823 struct sample_conv *sc;
8824 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008825
8826 MAY_LJMP(check_args(L, 2, "register_converters"));
8827
8828 /* First argument : converter name. */
8829 name = MAY_LJMP(luaL_checkstring(L, 1));
8830
8831 /* Second argument : lua function. */
8832 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8833
Thierry Fournierf67442e2020-11-28 20:41:07 +01008834 /* Check if the converter is already registered */
8835 trash = get_trash_chunk();
8836 chunk_printf(trash, "lua.%s", name);
8837 sc = find_sample_conv(trash->area, trash->data);
8838 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008839 fcn = sc->private;
8840 if (fcn->function_ref[hlua_state_id] != -1) {
8841 ha_warning("Trying to register converter 'lua.%s' more than once. "
8842 "This will become a hard error in version 2.5.\n", name);
8843 }
8844 fcn->function_ref[hlua_state_id] = ref;
8845 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008846 }
8847
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008848 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008849 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008850 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008851 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008852 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008853 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008854 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008855
8856 /* Fill fcn. */
8857 fcn->name = strdup(name);
8858 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008859 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008860 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008861
8862 /* List head */
8863 sck->list.n = sck->list.p = NULL;
8864
8865 /* converter keyword. */
8866 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008867 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008868 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008869 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008870
8871 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8872 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008873 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 +01008874 sck->kw[0].val_args = NULL;
8875 sck->kw[0].in_type = SMP_T_STR;
8876 sck->kw[0].out_type = SMP_T_STR;
8877 sck->kw[0].private = fcn;
8878
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008879 /* Register this new converter */
8880 sample_register_convs(sck);
8881
8882 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008883
8884 alloc_error:
8885 release_hlua_function(fcn);
8886 ha_free(&sck);
8887 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8888 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008889}
8890
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008891/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008892 * "sample-fetch" functions. It expects a converter name used
8893 * in the haproxy configuration file, and an LUA function.
8894 */
8895__LJMP static int hlua_register_fetches(lua_State *L)
8896{
8897 const char *name;
8898 int ref;
8899 int len;
8900 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008901 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008902 struct sample_fetch *sf;
8903 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008904
8905 MAY_LJMP(check_args(L, 2, "register_fetches"));
8906
8907 /* First argument : sample-fetch name. */
8908 name = MAY_LJMP(luaL_checkstring(L, 1));
8909
8910 /* Second argument : lua function. */
8911 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8912
Thierry Fournierf67442e2020-11-28 20:41:07 +01008913 /* Check if the sample-fetch is already registered */
8914 trash = get_trash_chunk();
8915 chunk_printf(trash, "lua.%s", name);
8916 sf = find_sample_fetch(trash->area, trash->data);
8917 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008918 fcn = sf->private;
8919 if (fcn->function_ref[hlua_state_id] != -1) {
8920 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8921 "This will become a hard error in version 2.5.\n", name);
8922 }
8923 fcn->function_ref[hlua_state_id] = ref;
8924 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008925 }
8926
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008927 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008928 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008929 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008930 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008931 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008932 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008933 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008934
8935 /* Fill fcn. */
8936 fcn->name = strdup(name);
8937 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008938 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008939 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008940
8941 /* List head */
8942 sfk->list.n = sfk->list.p = NULL;
8943
8944 /* sample-fetch keyword. */
8945 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008946 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008947 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008948 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008949
8950 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8951 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008952 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 +01008953 sfk->kw[0].val_args = NULL;
8954 sfk->kw[0].out_type = SMP_T_STR;
8955 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8956 sfk->kw[0].val = 0;
8957 sfk->kw[0].private = fcn;
8958
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008959 /* Register this new fetch. */
8960 sample_register_fetches(sfk);
8961
8962 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008963
8964 alloc_error:
8965 release_hlua_function(fcn);
8966 ha_free(&sfk);
8967 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8968 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008969}
8970
Christopher Faulet501465d2020-02-26 14:54:16 +01008971/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008972 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008973__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008974{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008975 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008976 unsigned int delay;
8977 unsigned int wakeup_ms;
8978
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008979 /* Get hlua struct, or NULL if we execute from main lua state */
8980 hlua = hlua_gethlua(L);
8981 if (!hlua) {
8982 return 0;
8983 }
8984
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008985 MAY_LJMP(check_args(L, 1, "wake_time"));
8986
8987 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8988 wakeup_ms = tick_add(now_ms, delay);
8989 hlua->wake_time = wakeup_ms;
8990 return 0;
8991}
8992
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008993/* This function is a wrapper to execute each LUA function declared as an action
8994 * wrapper during the initialisation period. This function may return any
8995 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8996 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8997 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008998 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008999static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009000 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009001{
9002 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009003 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009004 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009005 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009006
9007 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009008 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9009 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9010 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9011 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009012 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009013 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009014 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009015 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009016
Willy Tarreau87b09662015-04-03 00:22:06 +02009017 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009018 * Lua context can be not initialized. This behavior
9019 * permits to save performances because a systematic
9020 * Lua initialization cause 5% performances loss.
9021 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009022 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009023 struct hlua *hlua;
9024
9025 hlua = pool_alloc(pool_head_hlua);
9026 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009027 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009028 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009029 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009030 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009031 HLUA_INIT(hlua);
9032 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009033 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 +01009034 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009035 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009036 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009037 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009038 }
9039
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009040 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009041 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009042
9043 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009044 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009045 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9046 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009047 else
9048 error = "critical error";
9049 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009050 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009051 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009052 }
9053
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009054 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009055 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009056 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009057 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009058 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009059 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009060 }
9061
9062 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009063 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 +01009064
Willy Tarreau87b09662015-04-03 00:22:06 +02009065 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009066 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009067 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009068 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009069 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009070 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009071 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009072 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009073
9074 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009075 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009076 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009077 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009078 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009079 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009080 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009081 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009082 lua_pushstring(s->hlua->T, *arg);
9083 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009084 }
9085
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009086 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009087 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009088
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009089 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009090 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009091 }
9092
9093 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009094 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009095 /* finished. */
9096 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009097 /* Catch the return value */
9098 if (lua_gettop(s->hlua->T) > 0)
9099 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009100
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009101 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009102 if (act_ret == ACT_RET_YIELD) {
9103 if (flags & ACT_OPT_FINAL)
9104 goto err_yield;
9105
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009106 if (dir == SMP_OPT_DIR_REQ)
9107 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9108 s->hlua->wake_time);
9109 else
9110 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9111 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009112 }
9113 goto end;
9114
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009115 /* yield. */
9116 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009117 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009118 if (dir == SMP_OPT_DIR_REQ)
9119 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9120 s->hlua->wake_time);
9121 else
9122 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9123 s->hlua->wake_time);
9124
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009125 /* Some actions can be wake up when a "write" event
9126 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009127 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009128 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009129 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009130 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009131 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009132 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009133 act_ret = ACT_RET_YIELD;
9134 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009135
9136 /* finished with error. */
9137 case HLUA_E_ERRMSG:
9138 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009139 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009140 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009141 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009142 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009143
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009144 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009145 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009146 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009147
9148 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009149 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009150 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009151
9152 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009153 err_yield:
9154 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009155 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009156 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009157 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009158
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009159 case HLUA_E_ERR:
9160 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009161 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009162 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009163
9164 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009165 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009166 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009167
9168 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009169 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009170 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009171 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009172}
9173
Willy Tarreau144f84a2021-03-02 16:09:26 +01009174struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009175{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009176 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009177
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009178 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009179 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009180 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009181}
9182
9183static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
9184{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009185 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009186 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009187 struct task *task;
9188 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009189 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009190
Willy Tarreaubafbe012017-11-24 17:34:44 +01009191 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009192 if (!hlua) {
9193 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009194 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009195 return 0;
9196 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009197 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009198 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009199 ctx->ctx.hlua_apptcp.flags = 0;
9200
9201 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009202 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009203 if (!task) {
9204 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009205 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009206 return 0;
9207 }
9208 task->nice = 0;
9209 task->context = ctx;
9210 task->process = hlua_applet_wakeup;
9211 ctx->ctx.hlua_apptcp.task = task;
9212
9213 /* In the execution wrappers linked with a stream, the
9214 * Lua context can be not initialized. This behavior
9215 * permits to save performances because a systematic
9216 * Lua initialization cause 5% performances loss.
9217 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009218 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009219 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009220 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009221 return 0;
9222 }
9223
9224 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009225 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009226
9227 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009228 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009229 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9230 error = lua_tostring(hlua->T, -1);
9231 else
9232 error = "critical error";
9233 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009234 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009235 return 0;
9236 }
9237
9238 /* Check stack available size. */
9239 if (!lua_checkstack(hlua->T, 1)) {
9240 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009241 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009242 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009243 return 0;
9244 }
9245
9246 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009247 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009248
9249 /* Create and and push object stream in the stack. */
9250 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
9251 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009252 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009253 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009254 return 0;
9255 }
9256 hlua->nargs = 1;
9257
9258 /* push keywords in the stack. */
9259 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9260 if (!lua_checkstack(hlua->T, 1)) {
9261 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009262 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009263 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009264 return 0;
9265 }
9266 lua_pushstring(hlua->T, *arg);
9267 hlua->nargs++;
9268 }
9269
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009270 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009271
9272 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009273 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01009274 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009275
9276 return 1;
9277}
9278
Willy Tarreau60409db2019-08-21 14:14:50 +02009279void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009280{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009281 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009282 struct stream *strm = si_strm(si);
9283 struct channel *res = si_ic(si);
9284 struct act_rule *rule = ctx->rule;
9285 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009286 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009287
9288 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02009289 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
9290 /* eat the whole request */
9291 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009292 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009293 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009294
9295 /* If the stream is disconnect or closed, ldo nothing. */
9296 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9297 return;
9298
9299 /* Execute the function. */
9300 switch (hlua_ctx_resume(hlua, 1)) {
9301 /* finished. */
9302 case HLUA_E_OK:
9303 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9304
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009305 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02009306 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009307 res->flags |= CF_READ_NULL;
9308 si_shutr(si);
9309 return;
9310
9311 /* yield. */
9312 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009313 if (hlua->wake_time != TICK_ETERNITY)
9314 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009315 return;
9316
9317 /* finished with error. */
9318 case HLUA_E_ERRMSG:
9319 /* Display log. */
9320 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009321 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009322 lua_pop(hlua->T, 1);
9323 goto error;
9324
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009325 case HLUA_E_ETMOUT:
9326 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009327 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009328 goto error;
9329
9330 case HLUA_E_NOMEM:
9331 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009332 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009333 goto error;
9334
9335 case HLUA_E_YIELD: /* unexpected */
9336 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009337 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009338 goto error;
9339
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009340 case HLUA_E_ERR:
9341 /* Display log. */
9342 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009343 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009344 goto error;
9345
9346 default:
9347 goto error;
9348 }
9349
9350error:
9351
9352 /* For all other cases, just close the stream. */
9353 si_shutw(si);
9354 si_shutr(si);
9355 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9356}
9357
9358static void hlua_applet_tcp_release(struct appctx *ctx)
9359{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009360 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009361 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009362 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009363 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009364}
9365
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009366/* The function returns 1 if the initialisation is complete, 0 if
9367 * an errors occurs and -1 if more data are required for initializing
9368 * the applet.
9369 */
9370static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
9371{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009372 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009373 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009374 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009375 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009376 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009377 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009378
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009379 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009380 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009381 if (!hlua) {
9382 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009383 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009384 return 0;
9385 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009386 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009387 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009388 ctx->ctx.hlua_apphttp.left_bytes = -1;
9389 ctx->ctx.hlua_apphttp.flags = 0;
9390
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009391 if (txn->req.flags & HTTP_MSGF_VER_11)
9392 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
9393
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009394 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009395 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009396 if (!task) {
9397 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009398 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009399 return 0;
9400 }
9401 task->nice = 0;
9402 task->context = ctx;
9403 task->process = hlua_applet_wakeup;
9404 ctx->ctx.hlua_apphttp.task = task;
9405
9406 /* In the execution wrappers linked with a stream, the
9407 * Lua context can be not initialized. This behavior
9408 * permits to save performances because a systematic
9409 * Lua initialization cause 5% performances loss.
9410 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009411 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009412 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009413 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009414 return 0;
9415 }
9416
9417 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009418 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009419
9420 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009421 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009422 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9423 error = lua_tostring(hlua->T, -1);
9424 else
9425 error = "critical error";
9426 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009427 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009428 return 0;
9429 }
9430
9431 /* Check stack available size. */
9432 if (!lua_checkstack(hlua->T, 1)) {
9433 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009434 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009435 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009436 return 0;
9437 }
9438
9439 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009440 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009441
9442 /* Create and and push object stream in the stack. */
9443 if (!hlua_applet_http_new(hlua->T, ctx)) {
9444 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009445 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009446 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009447 return 0;
9448 }
9449 hlua->nargs = 1;
9450
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009451 /* push keywords in the stack. */
9452 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9453 if (!lua_checkstack(hlua->T, 1)) {
9454 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009455 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009456 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009457 return 0;
9458 }
9459 lua_pushstring(hlua->T, *arg);
9460 hlua->nargs++;
9461 }
9462
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009463 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009464
9465 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009466 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009467
9468 return 1;
9469}
9470
Willy Tarreau60409db2019-08-21 14:14:50 +02009471void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009472{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009473 struct stream_interface *si = cs_si(ctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009474 struct stream *strm = si_strm(si);
9475 struct channel *req = si_oc(si);
9476 struct channel *res = si_ic(si);
9477 struct act_rule *rule = ctx->rule;
9478 struct proxy *px = strm->be;
9479 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
9480 struct htx *req_htx, *res_htx;
9481
9482 res_htx = htx_from_buf(&res->buf);
9483
9484 /* If the stream is disconnect or closed, ldo nothing. */
9485 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9486 goto out;
9487
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009488 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009489 if (!b_size(&res->buf)) {
9490 si_rx_room_blk(si);
9491 goto out;
9492 }
9493 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009494 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009495 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9496
9497 /* Set the currently running flag. */
9498 if (!HLUA_IS_RUNNING(hlua) &&
9499 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009500 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009501 si_cant_get(si);
9502 goto out;
9503 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009504 }
9505
9506 /* Executes The applet if it is not done. */
9507 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9508
9509 /* Execute the function. */
9510 switch (hlua_ctx_resume(hlua, 1)) {
9511 /* finished. */
9512 case HLUA_E_OK:
9513 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9514 break;
9515
9516 /* yield. */
9517 case HLUA_E_AGAIN:
9518 if (hlua->wake_time != TICK_ETERNITY)
9519 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009520 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009521
9522 /* finished with error. */
9523 case HLUA_E_ERRMSG:
9524 /* Display log. */
9525 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009526 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009527 lua_pop(hlua->T, 1);
9528 goto error;
9529
9530 case HLUA_E_ETMOUT:
9531 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009532 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009533 goto error;
9534
9535 case HLUA_E_NOMEM:
9536 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009537 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009538 goto error;
9539
9540 case HLUA_E_YIELD: /* unexpected */
9541 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009542 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009543 goto error;
9544
9545 case HLUA_E_ERR:
9546 /* Display log. */
9547 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009548 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009549 goto error;
9550
9551 default:
9552 goto error;
9553 }
9554 }
9555
9556 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009557 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9558 goto done;
9559
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009560 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9561 goto error;
9562
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009563 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
9564 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009565 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9566 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009567 }
9568
9569 done:
9570 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009571 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009572 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009573 si_shutr(si);
9574 }
9575
9576 /* eat the whole request */
9577 if (co_data(req)) {
9578 req_htx = htx_from_buf(&req->buf);
9579 co_htx_skip(req, req_htx, co_data(req));
9580 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009581 }
9582 }
9583
9584 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009585 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009586 return;
9587
9588 error:
9589
9590 /* If we are in HTTP mode, and we are not send any
9591 * data, return a 500 server error in best effort:
9592 * if there is no room available in the buffer,
9593 * just close the connection.
9594 */
9595 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009596 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009597
9598 channel_erase(res);
9599 res->buf.data = b_data(err);
9600 memcpy(res->buf.area, b_head(err), b_data(err));
9601 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009602 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009603 }
9604 if (!(strm->flags & SF_ERR_MASK))
9605 strm->flags |= SF_ERR_RESOURCE;
9606 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9607 goto done;
9608}
9609
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009610static void hlua_applet_http_release(struct appctx *ctx)
9611{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009612 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009613 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009614 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009615 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009616}
9617
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009618/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009619 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009620 *
9621 * This function can fail with an abort() due to an Lua critical error.
9622 * We are in the configuration parsing process of HAProxy, this abort() is
9623 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009624 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009625static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9626 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009627{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009628 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009629 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009630
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009631 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009632 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009633 if (!rule->arg.hlua_rule) {
9634 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009635 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009636 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009637
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009638 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009639 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9640 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009641 if (!rule->arg.hlua_rule->args) {
9642 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009643 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009644 }
9645
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009646 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009647 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009648
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009649 /* Expect some arguments */
9650 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009651 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009652 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009653 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009654 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009655 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009656 if (!rule->arg.hlua_rule->args[i]) {
9657 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009658 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009659 }
9660 (*cur_arg)++;
9661 }
9662 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009663
Thierry FOURNIER42148732015-09-02 17:17:33 +02009664 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009665 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009666 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009667
9668 error:
9669 if (rule->arg.hlua_rule) {
9670 if (rule->arg.hlua_rule->args) {
9671 for (i = 0; i < fcn->nargs; i++)
9672 ha_free(&rule->arg.hlua_rule->args[i]);
9673 ha_free(&rule->arg.hlua_rule->args);
9674 }
9675 ha_free(&rule->arg.hlua_rule);
9676 }
9677 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009678}
9679
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009680static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9681 struct act_rule *rule, char **err)
9682{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009683 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009684
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009685 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009686 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009687 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009688 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009689 * the call of this analyzer.
9690 */
9691 if (rule->from != ACT_F_HTTP_REQ) {
9692 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9693 return ACT_RET_PRS_ERR;
9694 }
9695
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009696 /* Memory for the rule. */
9697 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9698 if (!rule->arg.hlua_rule) {
9699 memprintf(err, "out of memory error");
9700 return ACT_RET_PRS_ERR;
9701 }
9702
9703 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009704 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009705
9706 /* TODO: later accept arguments. */
9707 rule->arg.hlua_rule->args = NULL;
9708
9709 /* Add applet pointer in the rule. */
9710 rule->applet.obj_type = OBJ_TYPE_APPLET;
9711 rule->applet.name = fcn->name;
9712 rule->applet.init = hlua_applet_http_init;
9713 rule->applet.fct = hlua_applet_http_fct;
9714 rule->applet.release = hlua_applet_http_release;
9715 rule->applet.timeout = hlua_timeout_applet;
9716
9717 return ACT_RET_PRS_OK;
9718}
9719
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009720/* This function is an LUA binding used for registering
9721 * "sample-conv" functions. It expects a converter name used
9722 * in the haproxy configuration file, and an LUA function.
9723 */
9724__LJMP static int hlua_register_action(lua_State *L)
9725{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009726 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009727 const char *name;
9728 int ref;
9729 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009730 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009731 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009732 struct buffer *trash;
9733 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009734
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009735 /* Initialise the number of expected arguments at 0. */
9736 nargs = 0;
9737
9738 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9739 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009740
9741 /* First argument : converter name. */
9742 name = MAY_LJMP(luaL_checkstring(L, 1));
9743
9744 /* Second argument : environment. */
9745 if (lua_type(L, 2) != LUA_TTABLE)
9746 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9747
9748 /* Third argument : lua function. */
9749 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9750
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009751 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009752 if (lua_gettop(L) >= 4)
9753 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9754
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009755 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009756 lua_pushnil(L);
9757 while (lua_next(L, 2) != 0) {
9758 if (lua_type(L, -1) != LUA_TSTRING)
9759 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9760
Thierry Fournierf67442e2020-11-28 20:41:07 +01009761 /* Check if action exists */
9762 trash = get_trash_chunk();
9763 chunk_printf(trash, "lua.%s", name);
9764 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9765 akw = tcp_req_cont_action(trash->area);
9766 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9767 akw = tcp_res_cont_action(trash->area);
9768 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9769 akw = action_http_req_custom(trash->area);
9770 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9771 akw = action_http_res_custom(trash->area);
9772 } else {
9773 akw = NULL;
9774 }
9775 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009776 fcn = akw->private;
9777 if (fcn->function_ref[hlua_state_id] != -1) {
9778 ha_warning("Trying to register action 'lua.%s' more than once. "
9779 "This will become a hard error in version 2.5.\n", name);
9780 }
9781 fcn->function_ref[hlua_state_id] = ref;
9782
9783 /* pop the environment string. */
9784 lua_pop(L, 1);
9785 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009786 }
9787
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009788 /* Check required environment. Only accepted "http" or "tcp". */
9789 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009790 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009791 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009792 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009793 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009794 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009795 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009796
9797 /* Fill fcn. */
9798 fcn->name = strdup(name);
9799 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009800 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009801 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009802
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009803 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009804 fcn->nargs = nargs;
9805
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009806 /* List head */
9807 akl->list.n = akl->list.p = NULL;
9808
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009809 /* action keyword. */
9810 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009811 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009812 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009813 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009814
9815 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9816
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009817 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009818 akl->kw[0].private = fcn;
9819 akl->kw[0].parse = action_register_lua;
9820
9821 /* select the action registering point. */
9822 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9823 tcp_req_cont_keywords_register(akl);
9824 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9825 tcp_res_cont_keywords_register(akl);
9826 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9827 http_req_keywords_register(akl);
9828 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9829 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009830 else {
9831 release_hlua_function(fcn);
9832 if (akl)
9833 ha_free((char **)&(akl->kw[0].kw));
9834 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009835 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009836 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9837 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009838 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009839
9840 /* pop the environment string. */
9841 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009842
9843 /* reset for next loop */
9844 akl = NULL;
9845 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009846 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009847 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009848
9849 alloc_error:
9850 release_hlua_function(fcn);
9851 ha_free(&akl);
9852 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9853 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009854}
9855
9856static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9857 struct act_rule *rule, char **err)
9858{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009859 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009860
Christopher Faulet280f85b2019-07-15 15:02:04 +02009861 if (px->mode == PR_MODE_HTTP) {
9862 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009863 return ACT_RET_PRS_ERR;
9864 }
9865
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009866 /* Memory for the rule. */
9867 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9868 if (!rule->arg.hlua_rule) {
9869 memprintf(err, "out of memory error");
9870 return ACT_RET_PRS_ERR;
9871 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009872
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009873 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009874 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009875
9876 /* TODO: later accept arguments. */
9877 rule->arg.hlua_rule->args = NULL;
9878
9879 /* Add applet pointer in the rule. */
9880 rule->applet.obj_type = OBJ_TYPE_APPLET;
9881 rule->applet.name = fcn->name;
9882 rule->applet.init = hlua_applet_tcp_init;
9883 rule->applet.fct = hlua_applet_tcp_fct;
9884 rule->applet.release = hlua_applet_tcp_release;
9885 rule->applet.timeout = hlua_timeout_applet;
9886
9887 return 0;
9888}
9889
9890/* This function is an LUA binding used for registering
9891 * "sample-conv" functions. It expects a converter name used
9892 * in the haproxy configuration file, and an LUA function.
9893 */
9894__LJMP static int hlua_register_service(lua_State *L)
9895{
9896 struct action_kw_list *akl;
9897 const char *name;
9898 const char *env;
9899 int ref;
9900 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009901 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009902 struct buffer *trash;
9903 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009904
9905 MAY_LJMP(check_args(L, 3, "register_service"));
9906
9907 /* First argument : converter name. */
9908 name = MAY_LJMP(luaL_checkstring(L, 1));
9909
9910 /* Second argument : environment. */
9911 env = MAY_LJMP(luaL_checkstring(L, 2));
9912
9913 /* Third argument : lua function. */
9914 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9915
Thierry Fournierf67442e2020-11-28 20:41:07 +01009916 /* Check for service already registered */
9917 trash = get_trash_chunk();
9918 chunk_printf(trash, "lua.%s", name);
9919 akw = service_find(trash->area);
9920 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009921 fcn = akw->private;
9922 if (fcn->function_ref[hlua_state_id] != -1) {
9923 ha_warning("Trying to register service 'lua.%s' more than once. "
9924 "This will become a hard error in version 2.5.\n", name);
9925 }
9926 fcn->function_ref[hlua_state_id] = ref;
9927 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009928 }
9929
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009930 /* Allocate and fill the sample fetch keyword struct. */
9931 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9932 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009933 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009934 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009935 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009936 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009937
9938 /* Fill fcn. */
9939 len = strlen("<lua.>") + strlen(name) + 1;
9940 fcn->name = calloc(1, len);
9941 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009942 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009943 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009944 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009945
9946 /* List head */
9947 akl->list.n = akl->list.p = NULL;
9948
9949 /* converter keyword. */
9950 len = strlen("lua.") + strlen(name) + 1;
9951 akl->kw[0].kw = calloc(1, len);
9952 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009953 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009954
9955 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9956
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009957 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009958 if (strcmp(env, "tcp") == 0)
9959 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009960 else if (strcmp(env, "http") == 0)
9961 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009962 else {
9963 release_hlua_function(fcn);
9964 if (akl)
9965 ha_free((char **)&(akl->kw[0].kw));
9966 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009967 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009968 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009969 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009970
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009971 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009972 akl->kw[0].private = fcn;
9973
9974 /* End of array. */
9975 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9976
9977 /* Register this new converter */
9978 service_keywords_register(akl);
9979
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009980 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009981
9982 alloc_error:
9983 release_hlua_function(fcn);
9984 ha_free(&akl);
9985 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9986 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009987}
9988
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009989/* This function initialises Lua cli handler. It copies the
9990 * arguments in the Lua stack and create channel IO objects.
9991 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02009992static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009993{
9994 struct hlua *hlua;
9995 struct hlua_function *fcn;
9996 int i;
9997 const char *error;
9998
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009999 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010000 appctx->ctx.hlua_cli.fcn = private;
10001
Willy Tarreaubafbe012017-11-24 17:34:44 +010010002 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010003 if (!hlua) {
10004 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010005 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010006 }
10007 HLUA_INIT(hlua);
10008 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010009
10010 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010011 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010012 * applet_http. It is absolutely compatible.
10013 */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010014 appctx->ctx.hlua_cli.task = task_new_here();
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010015 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010016 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010017 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010018 }
10019 appctx->ctx.hlua_cli.task->nice = 0;
10020 appctx->ctx.hlua_cli.task->context = appctx;
10021 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
10022
10023 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +010010024 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010025 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010026 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010027 }
10028
10029 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010030 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010031 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10032 error = lua_tostring(hlua->T, -1);
10033 else
10034 error = "critical error";
10035 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10036 goto error;
10037 }
10038
10039 /* Check stack available size. */
10040 if (!lua_checkstack(hlua->T, 2)) {
10041 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10042 goto error;
10043 }
10044
10045 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010046 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010047
10048 /* Once the arguments parsed, the CLI is like an AppletTCP,
10049 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010050 */
10051 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10052 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10053 goto error;
10054 }
10055 hlua->nargs = 1;
10056
10057 /* push keywords in the stack. */
10058 for (i = 0; *args[i]; i++) {
10059 /* Check stack available size. */
10060 if (!lua_checkstack(hlua->T, 1)) {
10061 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10062 goto error;
10063 }
10064 lua_pushstring(hlua->T, args[i]);
10065 hlua->nargs++;
10066 }
10067
10068 /* We must initialize the execution timeouts. */
10069 hlua->max_time = hlua_timeout_session;
10070
10071 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010072 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010073
10074 /* It's ok */
10075 return 0;
10076
10077 /* It's not ok. */
10078error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010079 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010080 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010081 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010082 return 1;
10083}
10084
10085static int hlua_cli_io_handler_fct(struct appctx *appctx)
10086{
10087 struct hlua *hlua;
10088 struct stream_interface *si;
10089 struct hlua_function *fcn;
10090
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010091 hlua = appctx->ctx.hlua_cli.hlua;
Christopher Faulet86e1c332021-12-20 17:09:39 +010010092 si = cs_si(appctx->owner);
Willy Tarreau8ae4f752016-12-14 15:41:45 +010010093 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010094
10095 /* If the stream is disconnect or closed, ldo nothing. */
10096 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
10097 return 1;
10098
10099 /* Execute the function. */
10100 switch (hlua_ctx_resume(hlua, 1)) {
10101
10102 /* finished. */
10103 case HLUA_E_OK:
10104 return 1;
10105
10106 /* yield. */
10107 case HLUA_E_AGAIN:
10108 /* We want write. */
10109 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +010010110 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010111 /* Set the timeout. */
10112 if (hlua->wake_time != TICK_ETERNITY)
10113 task_schedule(hlua->task, hlua->wake_time);
10114 return 0;
10115
10116 /* finished with error. */
10117 case HLUA_E_ERRMSG:
10118 /* Display log. */
10119 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10120 fcn->name, lua_tostring(hlua->T, -1));
10121 lua_pop(hlua->T, 1);
10122 return 1;
10123
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010124 case HLUA_E_ETMOUT:
10125 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10126 fcn->name);
10127 return 1;
10128
10129 case HLUA_E_NOMEM:
10130 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10131 fcn->name);
10132 return 1;
10133
10134 case HLUA_E_YIELD: /* unexpected */
10135 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10136 fcn->name);
10137 return 1;
10138
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010139 case HLUA_E_ERR:
10140 /* Display log. */
10141 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10142 fcn->name);
10143 return 1;
10144
10145 default:
10146 return 1;
10147 }
10148
10149 return 1;
10150}
10151
10152static void hlua_cli_io_release_fct(struct appctx *appctx)
10153{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010154 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010155 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010156}
10157
10158/* This function is an LUA binding used for registering
10159 * new keywords in the cli. It expects a list of keywords
10160 * which are the "path". It is limited to 5 keywords. A
10161 * description of the command, a function to be executed
10162 * for the parsing and a function for io handlers.
10163 */
10164__LJMP static int hlua_register_cli(lua_State *L)
10165{
10166 struct cli_kw_list *cli_kws;
10167 const char *message;
10168 int ref_io;
10169 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010170 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010171 int index;
10172 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010173 struct buffer *trash;
10174 const char *kw[5];
10175 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010176 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010177
10178 MAY_LJMP(check_args(L, 3, "register_cli"));
10179
10180 /* First argument : an array of maximum 5 keywords. */
10181 if (!lua_istable(L, 1))
10182 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10183
10184 /* Second argument : string with contextual message. */
10185 message = MAY_LJMP(luaL_checkstring(L, 2));
10186
10187 /* Third and fourth argument : lua function. */
10188 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10189
Thierry Fournierf67442e2020-11-28 20:41:07 +010010190 /* Check for CLI service already registered */
10191 trash = get_trash_chunk();
10192 index = 0;
10193 lua_pushnil(L);
10194 memset(kw, 0, sizeof(kw));
10195 while (lua_next(L, 1) != 0) {
10196 if (index >= CLI_PREFIX_KW_NB)
10197 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10198 if (lua_type(L, -1) != LUA_TSTRING)
10199 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10200 kw[index] = lua_tostring(L, -1);
10201 if (index == 0)
10202 chunk_printf(trash, "%s", kw[index]);
10203 else
10204 chunk_appendf(trash, " %s", kw[index]);
10205 index++;
10206 lua_pop(L, 1);
10207 }
10208 cli_kw = cli_find_kw_exact((char **)kw);
10209 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010210 fcn = cli_kw->private;
10211 if (fcn->function_ref[hlua_state_id] != -1) {
10212 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10213 "This will become a hard error in version 2.5.\n", trash->area);
10214 }
10215 fcn->function_ref[hlua_state_id] = ref_io;
10216 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010217 }
10218
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010219 /* Allocate and fill the sample fetch keyword struct. */
10220 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010221 if (!cli_kws) {
10222 errmsg = "Lua out of memory error.";
10223 goto error;
10224 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010225 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010226 if (!fcn) {
10227 errmsg = "Lua out of memory error.";
10228 goto error;
10229 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010230
10231 /* Fill path. */
10232 index = 0;
10233 lua_pushnil(L);
10234 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010235 if (index >= 5) {
10236 errmsg = "1st argument must be a table with a maximum of 5 entries";
10237 goto error;
10238 }
10239 if (lua_type(L, -1) != LUA_TSTRING) {
10240 errmsg = "1st argument must be a table filled with strings";
10241 goto error;
10242 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010243 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010244 if (!cli_kws->kw[0].str_kw[index]) {
10245 errmsg = "Lua out of memory error.";
10246 goto error;
10247 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010248 index++;
10249 lua_pop(L, 1);
10250 }
10251
10252 /* Copy help message. */
10253 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010254 if (!cli_kws->kw[0].usage) {
10255 errmsg = "Lua out of memory error.";
10256 goto error;
10257 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010258
10259 /* Fill fcn io handler. */
10260 len = strlen("<lua.cli>") + 1;
10261 for (i = 0; i < index; i++)
10262 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10263 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010264 if (!fcn->name) {
10265 errmsg = "Lua out of memory error.";
10266 goto error;
10267 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010268 strncat((char *)fcn->name, "<lua.cli", len);
10269 for (i = 0; i < index; i++) {
10270 strncat((char *)fcn->name, ".", len);
10271 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10272 }
10273 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010274 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010275
10276 /* Fill last entries. */
10277 cli_kws->kw[0].private = fcn;
10278 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10279 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10280 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10281
10282 /* Register this new converter */
10283 cli_register_kw(cli_kws);
10284
10285 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010286
10287 error:
10288 release_hlua_function(fcn);
10289 if (cli_kws) {
10290 for (i = 0; i < index; i++)
10291 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10292 ha_free((char **)&(cli_kws->kw[0].usage));
10293 }
10294 ha_free(&cli_kws);
10295 WILL_LJMP(luaL_error(L, errmsg));
10296 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010297}
10298
Christopher Faulet69c581a2021-05-31 08:54:04 +020010299static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10300{
10301 struct hlua_flt_config *conf = fconf->conf;
10302 lua_State *L;
10303 int error, pos, state_id, flt_ref;
10304
10305 state_id = reg_flt_to_stack_id(conf->reg);
10306 L = hlua_states[state_id];
10307 pos = lua_gettop(L);
10308
10309 /* The filter parsing function */
10310 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10311
10312 /* Push the filter class on the stack and resolve all callbacks */
10313 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10314
10315 /* Duplicate the filter class so each filter will have its own copy */
10316 lua_newtable(L);
10317 lua_pushnil(L);
10318
10319 while (lua_next(L, pos+2)) {
10320 lua_pushvalue(L, -2);
10321 lua_insert(L, -2);
10322 lua_settable(L, -4);
10323 }
10324 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10325
10326 /* Remove the original lua filter class from the stack */
10327 lua_pop(L, 1);
10328
10329 /* Push the copy on the stack */
10330 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10331
10332 /* extra args are pushed in a table */
10333 lua_newtable(L);
10334 for (pos = 0; conf->args[pos]; pos++) {
10335 /* Check stack available size. */
10336 if (!lua_checkstack(L, 1)) {
10337 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10338 goto error;
10339 }
10340 lua_pushstring(L, conf->args[pos]);
10341 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10342 }
10343
10344 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10345 switch (error) {
10346 case LUA_OK:
10347 /* replace the filter ref */
10348 conf->ref[state_id] = flt_ref;
10349 break;
10350 case LUA_ERRRUN:
10351 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10352 goto error;
10353 case LUA_ERRMEM:
10354 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10355 goto error;
10356 case LUA_ERRERR:
10357 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10358 goto error;
10359#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10360 case LUA_ERRGCMM:
10361 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10362 goto error;
10363#endif
10364 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010365 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010366 goto error;
10367 }
10368
10369 lua_settop(L, 0);
10370 return 0;
10371
10372 error:
10373 lua_settop(L, 0);
10374 return -1;
10375}
10376
10377static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10378{
10379 struct hlua_flt_config *conf = fconf->conf;
10380 lua_State *L;
10381 int state_id;
10382
10383 if (!conf)
10384 return;
10385
10386 state_id = reg_flt_to_stack_id(conf->reg);
10387 L = hlua_states[state_id];
10388 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10389}
10390
10391static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10392{
10393 struct hlua_flt_config *conf = fconf->conf;
10394 int state_id = reg_flt_to_stack_id(conf->reg);
10395
10396 /* Rely on per-thread init for global scripts */
10397 if (!state_id)
10398 return hlua_filter_init_per_thread(px, fconf);
10399 return 0;
10400}
10401
10402static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10403{
10404
10405 if (fconf->conf) {
10406 struct hlua_flt_config *conf = fconf->conf;
10407 int state_id = reg_flt_to_stack_id(conf->reg);
10408 int pos;
10409
10410 /* Rely on per-thread deinit for global scripts */
10411 if (!state_id)
10412 hlua_filter_deinit_per_thread(px, fconf);
10413
10414 for (pos = 0; conf->args[pos]; pos++)
10415 free(conf->args[pos]);
10416 free(conf->args);
10417 }
10418 ha_free(&fconf->conf);
10419 ha_free((char **)&fconf->id);
10420 ha_free(&fconf->ops);
10421}
10422
10423static int hlua_filter_new(struct stream *s, struct filter *filter)
10424{
10425 struct hlua_flt_config *conf = FLT_CONF(filter);
10426 struct hlua_flt_ctx *flt_ctx = NULL;
10427 int ret = 1;
10428
10429 /* In the execution wrappers linked with a stream, the
10430 * Lua context can be not initialized. This behavior
10431 * permits to save performances because a systematic
10432 * Lua initialization cause 5% performances loss.
10433 */
10434 if (!s->hlua) {
10435 struct hlua *hlua;
10436
10437 hlua = pool_alloc(pool_head_hlua);
10438 if (!hlua) {
10439 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10440 conf->reg->name);
10441 ret = 0;
10442 goto end;
10443 }
10444 HLUA_INIT(hlua);
10445 s->hlua = hlua;
10446 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10447 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10448 conf->reg->name);
10449 ret = 0;
10450 goto end;
10451 }
10452 }
10453
10454 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10455 if (!flt_ctx) {
10456 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10457 conf->reg->name);
10458 ret = 0;
10459 goto end;
10460 }
10461 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10462 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10463 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10464 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10465 conf->reg->name);
10466 ret = 0;
10467 goto end;
10468 }
10469 HLUA_INIT(flt_ctx->hlua[0]);
10470 HLUA_INIT(flt_ctx->hlua[1]);
10471 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10472 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10473 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10474 conf->reg->name);
10475 ret = 0;
10476 goto end;
10477 }
10478
10479 if (!HLUA_IS_RUNNING(s->hlua)) {
10480 /* The following Lua calls can fail. */
10481 if (!SET_SAFE_LJMP(s->hlua)) {
10482 const char *error;
10483
10484 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10485 error = lua_tostring(s->hlua->T, -1);
10486 else
10487 error = "critical error";
10488 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10489 ret = 0;
10490 goto end;
10491 }
10492
10493 /* Check stack size. */
10494 if (!lua_checkstack(s->hlua->T, 1)) {
10495 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010496 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010497 ret = 0;
10498 goto end;
10499 }
10500
10501 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10502 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10503 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10504 conf->reg->name);
10505 RESET_SAFE_LJMP(s->hlua);
10506 ret = 0;
10507 goto end;
10508 }
10509 lua_insert(s->hlua->T, -2);
10510
10511 /* Push the copy on the stack */
10512 s->hlua->nargs = 1;
10513
10514 /* We must initialize the execution timeouts. */
10515 s->hlua->max_time = hlua_timeout_session;
10516
10517 /* At this point the execution is safe. */
10518 RESET_SAFE_LJMP(s->hlua);
10519 }
10520
10521 switch (hlua_ctx_resume(s->hlua, 0)) {
10522 case HLUA_E_OK:
10523 /* Nothing returned or not a table, ignore the filter for current stream */
10524 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10525 ret = 0;
10526 goto end;
10527 }
10528
10529 /* Attached the filter pointer to the ctx */
10530 lua_pushstring(s->hlua->T, "__filter");
10531 lua_pushlightuserdata(s->hlua->T, filter);
10532 lua_settable(s->hlua->T, -3);
10533
10534 /* Save a ref on the filter ctx */
10535 lua_pushvalue(s->hlua->T, 1);
10536 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10537 filter->ctx = flt_ctx;
10538 break;
10539 case HLUA_E_ERRMSG:
10540 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10541 ret = -1;
10542 goto end;
10543 case HLUA_E_ETMOUT:
10544 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10545 ret = 0;
10546 goto end;
10547 case HLUA_E_NOMEM:
10548 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10549 ret = 0;
10550 goto end;
10551 case HLUA_E_AGAIN:
10552 case HLUA_E_YIELD:
10553 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10554 " are not allowed from 'new' function.\n", conf->reg->name);
10555 ret = 0;
10556 goto end;
10557 case HLUA_E_ERR:
10558 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10559 ret = 0;
10560 goto end;
10561 default:
10562 ret = 0;
10563 goto end;
10564 }
10565
10566 end:
10567 if (s->hlua)
10568 lua_settop(s->hlua->T, 0);
10569 if (ret <= 0) {
10570 if (flt_ctx) {
10571 hlua_ctx_destroy(flt_ctx->hlua[0]);
10572 hlua_ctx_destroy(flt_ctx->hlua[1]);
10573 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10574 }
10575 }
10576 return ret;
10577}
10578
10579static void hlua_filter_delete(struct stream *s, struct filter *filter)
10580{
10581 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10582
10583 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10584 hlua_ctx_destroy(flt_ctx->hlua[0]);
10585 hlua_ctx_destroy(flt_ctx->hlua[1]);
10586 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10587 filter->ctx = NULL;
10588}
10589
Christopher Faulet9f55a502020-02-25 15:21:02 +010010590static int hlua_filter_from_payload(struct filter *filter)
10591{
10592 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10593
10594 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10595}
10596
Christopher Fauletc404f112020-02-26 15:03:09 +010010597static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10598 int dir, unsigned int flags)
10599{
10600 struct hlua *flt_hlua;
10601 struct hlua_flt_config *conf = FLT_CONF(filter);
10602 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10603 unsigned int hflags = HLUA_TXN_FLT_CTX;
10604 int ret = 1;
10605
10606 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10607 if (!flt_hlua)
10608 goto end;
10609
10610 if (!HLUA_IS_RUNNING(flt_hlua)) {
10611 int extra_idx = lua_gettop(flt_hlua->T);
10612
10613 /* The following Lua calls can fail. */
10614 if (!SET_SAFE_LJMP(flt_hlua)) {
10615 const char *error;
10616
10617 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10618 error = lua_tostring(flt_hlua->T, -1);
10619 else
10620 error = "critical error";
10621 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10622 goto end;
10623 }
10624
10625 /* Check stack size. */
10626 if (!lua_checkstack(flt_hlua->T, 3)) {
10627 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10628 RESET_SAFE_LJMP(flt_hlua);
10629 goto end;
10630 }
10631
10632 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10633 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10634 RESET_SAFE_LJMP(flt_hlua);
10635 goto end;
10636 }
10637 lua_insert(flt_hlua->T, -2);
10638
10639 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10640 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10641 RESET_SAFE_LJMP(flt_hlua);
10642 goto end;
10643 }
10644 flt_hlua->nargs = 2;
10645
10646 if (flags & HLUA_FLT_CB_ARG_CHN) {
10647 if (dir == SMP_OPT_DIR_REQ)
10648 lua_getfield(flt_hlua->T, -1, "req");
10649 else
10650 lua_getfield(flt_hlua->T, -1, "res");
10651 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10652 lua_pushstring(flt_hlua->T, "__filter");
10653 lua_pushlightuserdata(flt_hlua->T, filter);
10654 lua_settable(flt_hlua->T, -3);
10655 }
10656 flt_hlua->nargs++;
10657 }
10658 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010659 if (dir == SMP_OPT_DIR_REQ)
10660 lua_getfield(flt_hlua->T, -1, "http_req");
10661 else
10662 lua_getfield(flt_hlua->T, -1, "http_res");
10663 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10664 lua_pushstring(flt_hlua->T, "__filter");
10665 lua_pushlightuserdata(flt_hlua->T, filter);
10666 lua_settable(flt_hlua->T, -3);
10667 }
10668 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010669 }
10670
10671 /* Check stack size. */
10672 if (!lua_checkstack(flt_hlua->T, 1)) {
10673 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10674 RESET_SAFE_LJMP(flt_hlua);
10675 goto end;
10676 }
10677
10678 while (extra_idx--) {
10679 lua_pushvalue(flt_hlua->T, 1);
10680 lua_remove(flt_hlua->T, 1);
10681 flt_hlua->nargs++;
10682 }
10683
10684 /* We must initialize the execution timeouts. */
10685 flt_hlua->max_time = hlua_timeout_session;
10686
10687 /* At this point the execution is safe. */
10688 RESET_SAFE_LJMP(flt_hlua);
10689 }
10690
10691 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10692 case HLUA_E_OK:
10693 /* Catch the return value if it required */
10694 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10695 ret = lua_tointeger(flt_hlua->T, -1);
10696 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10697 }
10698
10699 /* Set timeout in the required channel. */
10700 if (flt_hlua->wake_time != TICK_ETERNITY) {
10701 if (dir == SMP_OPT_DIR_REQ)
10702 s->req.analyse_exp = flt_hlua->wake_time;
10703 else
10704 s->res.analyse_exp = flt_hlua->wake_time;
10705 }
10706 break;
10707 case HLUA_E_AGAIN:
10708 /* Set timeout in the required channel. */
10709 if (flt_hlua->wake_time != TICK_ETERNITY) {
10710 if (dir == SMP_OPT_DIR_REQ)
10711 s->req.analyse_exp = flt_hlua->wake_time;
10712 else
10713 s->res.analyse_exp = flt_hlua->wake_time;
10714 }
10715 /* Some actions can be wake up when a "write" event
10716 * is detected on a response channel. This is useful
10717 * only for actions targeted on the requests.
10718 */
10719 if (HLUA_IS_WAKERESWR(flt_hlua))
10720 s->res.flags |= CF_WAKE_WRITE;
10721 if (HLUA_IS_WAKEREQWR(flt_hlua))
10722 s->req.flags |= CF_WAKE_WRITE;
10723 ret = 0;
10724 goto end;
10725 case HLUA_E_ERRMSG:
10726 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10727 ret = -1;
10728 goto end;
10729 case HLUA_E_ETMOUT:
10730 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10731 goto end;
10732 case HLUA_E_NOMEM:
10733 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10734 goto end;
10735 case HLUA_E_YIELD:
10736 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10737 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10738 goto end;
10739 case HLUA_E_ERR:
10740 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10741 goto end;
10742 default:
10743 goto end;
10744 }
10745
10746
10747 end:
10748 return ret;
10749}
10750
10751static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10752{
10753 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10754
10755 flt_ctx->flags = 0;
10756 return hlua_filter_callback(s, filter, "start_analyze",
10757 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10758 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10759}
10760
10761static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10762{
10763 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10764
10765 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10766 return hlua_filter_callback(s, filter, "end_analyze",
10767 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10768 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10769}
10770
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010771static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10772{
10773 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10774
10775 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10776 return hlua_filter_callback(s, filter, "http_headers",
10777 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10778 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10779}
10780
10781static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10782 unsigned int offset, unsigned int len)
10783{
10784 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10785 struct hlua *flt_hlua;
10786 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10787 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10788 int ret;
10789
10790 flt_hlua = flt_ctx->hlua[idx];
10791 flt_ctx->cur_off[idx] = offset;
10792 flt_ctx->cur_len[idx] = len;
10793 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10794 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10795 if (ret != -1) {
10796 ret = flt_ctx->cur_len[idx];
10797 if (lua_gettop(flt_hlua->T) > 0) {
10798 ret = lua_tointeger(flt_hlua->T, -1);
10799 if (ret > flt_ctx->cur_len[idx])
10800 ret = flt_ctx->cur_len[idx];
10801 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10802 }
10803 }
10804 return ret;
10805}
10806
10807static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10808{
10809 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10810
10811 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10812 return hlua_filter_callback(s, filter, "http_end",
10813 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10814 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10815}
10816
Christopher Fauletc404f112020-02-26 15:03:09 +010010817static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10818 unsigned int offset, unsigned int len)
10819{
10820 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10821 struct hlua *flt_hlua;
10822 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10823 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10824 int ret;
10825
10826 flt_hlua = flt_ctx->hlua[idx];
10827 flt_ctx->cur_off[idx] = offset;
10828 flt_ctx->cur_len[idx] = len;
10829 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10830 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10831 if (ret != -1) {
10832 ret = flt_ctx->cur_len[idx];
10833 if (lua_gettop(flt_hlua->T) > 0) {
10834 ret = lua_tointeger(flt_hlua->T, -1);
10835 if (ret > flt_ctx->cur_len[idx])
10836 ret = flt_ctx->cur_len[idx];
10837 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10838 }
10839 }
10840 return ret;
10841}
10842
Christopher Faulet69c581a2021-05-31 08:54:04 +020010843static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10844 struct flt_conf *fconf, char **err, void *private)
10845{
10846 struct hlua_reg_filter *reg_flt = private;
10847 lua_State *L;
10848 struct hlua_flt_config *conf = NULL;
10849 const char *flt_id = NULL;
10850 int state_id, pos, flt_flags = 0;
10851 struct flt_ops *hlua_flt_ops = NULL;
10852
10853 state_id = reg_flt_to_stack_id(reg_flt);
10854 L = hlua_states[state_id];
10855
10856 /* Initialize the filter ops with default callbacks */
10857 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010858 if (!hlua_flt_ops)
10859 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010860 hlua_flt_ops->init = hlua_filter_init;
10861 hlua_flt_ops->deinit = hlua_filter_deinit;
10862 if (state_id) {
10863 /* Set per-thread callback if script is loaded per-thread */
10864 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10865 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10866 }
10867 hlua_flt_ops->attach = hlua_filter_new;
10868 hlua_flt_ops->detach = hlua_filter_delete;
10869
10870 /* Push the filter class on the stack and resolve all callbacks */
10871 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10872
Christopher Fauletc404f112020-02-26 15:03:09 +010010873 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10874 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10875 lua_pop(L, 1);
10876 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10877 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10878 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010879 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10880 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10881 lua_pop(L, 1);
10882 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10883 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10884 lua_pop(L, 1);
10885 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10886 hlua_flt_ops->http_end = hlua_filter_http_end;
10887 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010888 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10889 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10890 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010891
10892 /* Get id and flags of the filter class */
10893 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10894 flt_id = lua_tostring(L, -1);
10895 lua_pop(L, 1);
10896 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10897 flt_flags = lua_tointeger(L, -1);
10898 lua_pop(L, 1);
10899
10900 /* Create the filter config */
10901 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010902 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010903 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010904 conf->reg = reg_flt;
10905
10906 /* duplicate args */
10907 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10908 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010909 if (!conf->args)
10910 goto error;
10911 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010912 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010913 if (!conf->args[pos])
10914 goto error;
10915 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010916 conf->args[pos] = NULL;
10917 *cur_arg += pos + 1;
10918
Christopher Fauletc86bb872021-08-13 08:33:57 +020010919 if (flt_id) {
10920 fconf->id = strdup(flt_id);
10921 if (!fconf->id)
10922 goto error;
10923 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010924 fconf->flags = flt_flags;
10925 fconf->conf = conf;
10926 fconf->ops = hlua_flt_ops;
10927
10928 lua_settop(L, 0);
10929 return 0;
10930
10931 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010932 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010933 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010934 if (conf && conf->args) {
10935 for (pos = 0; conf->args[pos]; pos++)
10936 free(conf->args[pos]);
10937 free(conf->args);
10938 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010939 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010940 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010941 lua_settop(L, 0);
10942 return -1;
10943}
10944
Christopher Fauletc404f112020-02-26 15:03:09 +010010945__LJMP static int hlua_register_data_filter(lua_State *L)
10946{
10947 struct filter *filter;
10948 struct channel *chn;
10949
10950 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10951 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10952 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10953
10954 lua_getfield(L, 1, "__filter");
10955 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10956 filter = lua_touserdata (L, -1);
10957 lua_pop(L, 1);
10958
10959 register_data_filter(chn_strm(chn), chn, filter);
10960 return 1;
10961}
10962
10963__LJMP static int hlua_unregister_data_filter(lua_State *L)
10964{
10965 struct filter *filter;
10966 struct channel *chn;
10967
10968 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10969 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10970 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10971
10972 lua_getfield(L, 1, "__filter");
10973 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10974 filter = lua_touserdata (L, -1);
10975 lua_pop(L, 1);
10976
10977 unregister_data_filter(chn_strm(chn), chn, filter);
10978 return 1;
10979}
10980
Christopher Faulet69c581a2021-05-31 08:54:04 +020010981/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010982 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020010983 * parse configuration arguments.
10984 */
10985__LJMP static int hlua_register_filter(lua_State *L)
10986{
10987 struct buffer *trash;
10988 struct flt_kw_list *fkl;
10989 struct flt_kw *fkw;
10990 const char *name;
10991 struct hlua_reg_filter *reg_flt= NULL;
10992 int flt_ref, fun_ref;
10993 int len;
10994
10995 MAY_LJMP(check_args(L, 3, "register_filter"));
10996
10997 /* First argument : filter name. */
10998 name = MAY_LJMP(luaL_checkstring(L, 1));
10999
11000 /* Second argument : The filter class */
11001 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11002
11003 /* Third argument : lua function. */
11004 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11005
11006 trash = get_trash_chunk();
11007 chunk_printf(trash, "lua.%s", name);
11008 fkw = flt_find_kw(trash->area);
11009 if (fkw != NULL) {
11010 reg_flt = fkw->private;
11011 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11012 ha_warning("Trying to register filter 'lua.%s' more than once. "
11013 "This will become a hard error in version 2.5.\n", name);
11014 }
11015 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11016 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11017 return 0;
11018 }
11019
11020 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11021 if (!fkl)
11022 goto alloc_error;
11023 fkl->scope = "HLUA";
11024
11025 reg_flt = new_hlua_reg_filter(name);
11026 if (!reg_flt)
11027 goto alloc_error;
11028
11029 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11030 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11031
11032 /* The filter keyword */
11033 len = strlen("lua.") + strlen(name) + 1;
11034 fkl->kw[0].kw = calloc(1, len);
11035 if (!fkl->kw[0].kw)
11036 goto alloc_error;
11037
11038 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11039
11040 fkl->kw[0].parse = hlua_filter_parse_fct;
11041 fkl->kw[0].private = reg_flt;
11042 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11043
11044 /* Register this new filter */
11045 flt_register_keywords(fkl);
11046
11047 return 0;
11048
11049 alloc_error:
11050 release_hlua_reg_filter(reg_flt);
11051 ha_free(&fkl);
11052 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11053 return 0; /* Never reached */
11054}
11055
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011056static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011057 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011058 char **err, unsigned int *timeout)
11059{
11060 const char *error;
11061
11062 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011063 if (error == PARSE_TIME_OVER) {
11064 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11065 args[1], args[0]);
11066 return -1;
11067 }
11068 else if (error == PARSE_TIME_UNDER) {
11069 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11070 args[1], args[0]);
11071 return -1;
11072 }
11073 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011074 memprintf(err, "%s: invalid timeout", args[0]);
11075 return -1;
11076 }
11077 return 0;
11078}
11079
11080static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011081 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011082 char **err)
11083{
11084 return hlua_read_timeout(args, section_type, curpx, defpx,
11085 file, line, err, &hlua_timeout_session);
11086}
11087
11088static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011089 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011090 char **err)
11091{
11092 return hlua_read_timeout(args, section_type, curpx, defpx,
11093 file, line, err, &hlua_timeout_task);
11094}
11095
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011096static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011097 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011098 char **err)
11099{
11100 return hlua_read_timeout(args, section_type, curpx, defpx,
11101 file, line, err, &hlua_timeout_applet);
11102}
11103
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011104static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011105 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011106 char **err)
11107{
11108 char *error;
11109
11110 hlua_nb_instruction = strtoll(args[1], &error, 10);
11111 if (*error != '\0') {
11112 memprintf(err, "%s: invalid number", args[0]);
11113 return -1;
11114 }
11115 return 0;
11116}
11117
Willy Tarreau32f61e22015-03-18 17:54:59 +010011118static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011119 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011120 char **err)
11121{
11122 char *error;
11123
11124 if (*(args[1]) == 0) {
11125 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11126 return -1;
11127 }
11128 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11129 if (*error != '\0') {
11130 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11131 return -1;
11132 }
11133 return 0;
11134}
11135
11136
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011137/* This function is called by the main configuration key "lua-load". It loads and
11138 * execute an lua file during the parsing of the HAProxy configuration file. It is
11139 * the main lua entry point.
11140 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011141 * This function runs with the HAProxy keywords API. It returns -1 if an error
11142 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011143 *
11144 * In some error case, LUA set an error message in top of the stack. This function
11145 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011146 *
11147 * This function can fail with an abort() due to an Lua critical error.
11148 * We are in the configuration parsing process of HAProxy, this abort() is
11149 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011150 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011151static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011152{
11153 int error;
11154
11155 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011156 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011157 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011158 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11159 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011160 return -1;
11161 }
11162
11163 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011164 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011165 switch (error) {
11166 case LUA_OK:
11167 break;
11168 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011169 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11170 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011171 return -1;
11172 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011173 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011174 return -1;
11175 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011176 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11177 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011178 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011179#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011180 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011181 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11182 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011183 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011184#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011185 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011186 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11187 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011188 return -1;
11189 }
11190
11191 return 0;
11192}
11193
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011194static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011195 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011196 char **err)
11197{
11198 if (*(args[1]) == 0) {
11199 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11200 return -1;
11201 }
11202
Thierry Fournier59f11be2020-11-29 00:37:41 +010011203 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011204 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011205 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011206 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011207}
11208
Thierry Fournier59f11be2020-11-29 00:37:41 +010011209static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011210 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011211 char **err)
11212{
11213 int len;
11214
11215 if (*(args[1]) == 0) {
11216 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11217 return -1;
11218 }
11219
11220 if (per_thread_load == NULL) {
11221 /* allocate the first entry large enough to store the final NULL */
11222 per_thread_load = calloc(1, sizeof(*per_thread_load));
11223 if (per_thread_load == NULL) {
11224 memprintf(err, "out of memory error");
11225 return -1;
11226 }
11227 }
11228
11229 /* count used entries */
11230 for (len = 0; per_thread_load[len] != NULL; len++)
11231 ;
11232
11233 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11234 if (per_thread_load == NULL) {
11235 memprintf(err, "out of memory error");
11236 return -1;
11237 }
11238
11239 per_thread_load[len] = strdup(args[1]);
11240 per_thread_load[len + 1] = NULL;
11241
11242 if (per_thread_load[len] == NULL) {
11243 memprintf(err, "out of memory error");
11244 return -1;
11245 }
11246
11247 /* loading for thread 1 only */
11248 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011249 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011250 return hlua_load_state(args[1], hlua_states[1], err);
11251}
11252
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011253/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11254 * in the given <ctx>.
11255 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011256static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011257{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011258 lua_getglobal(L, "package"); /* push package variable */
11259 lua_pushstring(L, path); /* push given path */
11260 lua_pushstring(L, ";"); /* push semicolon */
11261 lua_getfield(L, -3, type); /* push old path */
11262 lua_concat(L, 3); /* concatenate to new path */
11263 lua_setfield(L, -2, type); /* store new path */
11264 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011265
11266 return 0;
11267}
11268
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011269static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011270 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011271 char **err)
11272{
11273 char *path;
11274 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011275 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011276 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011277
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011278 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011279 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011280 }
11281
11282 if (!(*args[1])) {
11283 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011284 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011285 }
11286 path = args[1];
11287
11288 if (*args[2]) {
11289 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11290 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011291 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011292 }
11293 type = args[2];
11294 }
11295
Thierry Fournier59f11be2020-11-29 00:37:41 +010011296 p = calloc(1, sizeof(*p));
11297 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011298 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011299 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011300 }
11301 p->path = strdup(path);
11302 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011303 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011304 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011305 }
11306 p->type = strdup(type);
11307 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011308 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011309 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011310 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011311 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011312
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011313 /* Handle the global state and the per-thread state for the first
11314 * thread. The remaining threads will be initialized based on
11315 * prepend_path_list.
11316 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011317 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011318 lua_State *L = hlua_states[i];
11319 const char *error;
11320
11321 if (setjmp(safe_ljmp_env) != 0) {
11322 lua_atpanic(L, hlua_panic_safe);
11323 if (lua_type(L, -1) == LUA_TSTRING)
11324 error = lua_tostring(L, -1);
11325 else
11326 error = "critical error";
11327 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11328 exit(1);
11329 } else {
11330 lua_atpanic(L, hlua_panic_ljmp);
11331 }
11332
11333 hlua_prepend_path(L, type, path);
11334
11335 lua_atpanic(L, hlua_panic_safe);
11336 }
11337
Thierry Fournier59f11be2020-11-29 00:37:41 +010011338 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011339
11340err2:
11341 free(p->type);
11342 free(p->path);
11343err:
11344 free(p);
11345 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011346}
11347
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011348/* configuration keywords declaration */
11349static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011350 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011351 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011352 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011353 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11354 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011355 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011356 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011357 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011358 { 0, NULL, NULL },
11359}};
11360
Willy Tarreau0108d902018-11-25 19:14:37 +010011361INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11362
Christopher Fauletafd8f102018-11-08 11:34:21 +010011363
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011364/* This function can fail with an abort() due to an Lua critical error.
11365 * We are in the initialisation process of HAProxy, this abort() is
11366 * tolerated.
11367 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011368int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011369{
11370 struct hlua_init_function *init;
11371 const char *msg;
11372 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011373 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011374 const char *kind;
11375 const char *trace;
11376 int return_status = 1;
11377#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11378 int nres;
11379#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011380
Willy Tarreaucdb53462020-12-02 12:12:00 +010011381 /* disable memory limit checks if limit is not set */
11382 if (!hlua_global_allocator.limit)
11383 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11384
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011385 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011386 if (setjmp(safe_ljmp_env) != 0) {
11387 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011388 if (lua_type(L, -1) == LUA_TSTRING)
11389 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011390 else
11391 error = "critical error";
11392 fprintf(stderr, "Lua post-init: %s.\n", error);
11393 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011394 } else {
11395 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011396 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011397
Thierry Fournierb8cef172020-11-28 15:37:17 +010011398 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011399
Thierry Fournierc7492592020-11-28 23:57:24 +010011400 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011401 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011402
11403#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011404 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011405#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011406 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011407#endif
11408 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011409 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011410
11411 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011412 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011413 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011414
11415 case LUA_ERRERR:
11416 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011417 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011418 case LUA_ERRRUN:
11419 if (!kind)
11420 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011421 msg = lua_tostring(L, -1);
11422 lua_settop(L, 0); /* Empty the stack. */
11423 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011424 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011425 if (msg)
11426 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11427 else
11428 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11429 return_status = 0;
11430 break;
11431
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011432 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011433 /* Unknown error */
11434 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011435 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011436 case LUA_YIELD:
11437 /* yield is not configured at this step, this state doesn't happen */
11438 if (!kind)
11439 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011440 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011441 case LUA_ERRMEM:
11442 if (!kind)
11443 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011444 lua_settop(L, 0);
11445 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011446 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011447 ha_alert("Lua init: %s: %s\n", kind, trace);
11448 return_status = 0;
11449 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011450 }
Thierry Fournier670db242020-11-28 10:49:59 +010011451 if (!return_status)
11452 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011453 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011454
11455 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011456 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011457}
11458
Thierry Fournierb8cef172020-11-28 15:37:17 +010011459int hlua_post_init()
11460{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011461 int ret;
11462 int i;
11463 int errors;
11464 char *err = NULL;
11465 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011466 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011467
Willy Tarreaub1310492021-08-30 09:35:18 +020011468#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011469 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011470 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011471 int saved_used_backed = global.ssl_used_backend;
11472 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011473 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011474 global.ssl_used_backend = saved_used_backed;
11475 }
11476#endif
11477
Thierry Fournierc7492592020-11-28 23:57:24 +010011478 /* Perform post init of common thread */
11479 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011480 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011481 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11482 if (ret == 0)
11483 return 0;
11484
11485 /* init remaining lua states and load files */
11486 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11487
11488 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011489 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011490
11491 /* Init lua state */
11492 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11493
11494 /* Load lua files */
11495 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11496 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11497 if (ret != 0) {
11498 ha_alert("Lua init: %s\n", err);
11499 return 0;
11500 }
11501 }
11502 }
11503
11504 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011505 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011506
11507 /* Execute post init for all states */
11508 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11509
11510 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011511 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011512
11513 /* run post init */
11514 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11515 if (ret == 0)
11516 return 0;
11517 }
11518
11519 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011520 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011521
11522 /* control functions registering. Each function must have:
11523 * - only the function_ref[0] set positive and all other to -1
11524 * - only the function_ref[0] set to -1 and all other positive
11525 * This ensure a same reference is not used both in shared
11526 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011527 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011528 * complicated to found for the end user.
11529 */
11530 errors = 0;
11531 list_for_each_entry(fcn, &referenced_functions, l) {
11532 ret = 0;
11533 for (i = 1; i < global.nbthread + 1; i++) {
11534 if (fcn->function_ref[i] == -1)
11535 ret--;
11536 else
11537 ret++;
11538 }
11539 if (abs(ret) != global.nbthread) {
11540 ha_alert("Lua function '%s' is not referenced in all thread. "
11541 "Expect function in all thread or in none thread.\n", fcn->name);
11542 errors++;
11543 continue;
11544 }
11545
11546 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011547 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11548 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011549 "exclusive.\n", fcn->name);
11550 errors++;
11551 }
11552 }
11553
Christopher Faulet69c581a2021-05-31 08:54:04 +020011554 /* Do the same with registered filters */
11555 list_for_each_entry(reg_flt, &referenced_filters, l) {
11556 ret = 0;
11557 for (i = 1; i < global.nbthread + 1; i++) {
11558 if (reg_flt->flt_ref[i] == -1)
11559 ret--;
11560 else
11561 ret++;
11562 }
11563 if (abs(ret) != global.nbthread) {
11564 ha_alert("Lua filter '%s' is not referenced in all thread. "
11565 "Expect function in all thread or in none thread.\n", reg_flt->name);
11566 errors++;
11567 continue;
11568 }
11569
11570 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11571 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11572 "and per-thread Lua context (through lua-load-per-thread). these two context "
11573 "exclusive.\n", fcn->name);
11574 errors++;
11575 }
11576 }
11577
11578
Thierry Fournier59f11be2020-11-29 00:37:41 +010011579 if (errors > 0)
11580 return 0;
11581
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011582 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011583 * -1 in order to have probably a segfault if someone use it
11584 */
11585 hlua_state_id = -1;
11586
11587 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011588}
11589
Willy Tarreau32f61e22015-03-18 17:54:59 +010011590/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11591 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11592 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011593 * allocation. <nsize> is the requested new size. A new allocation is
11594 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011595 * zero. This one verifies that the limits are respected but is optimized
11596 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011597 *
11598 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11599 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11600 * that and will simply allocate zero as if it were the result of malloc(0),
11601 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11602 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011603 */
11604static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11605{
11606 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011607 size_t limit, old, new;
11608
11609 /* a limit of ~0 means unlimited and boot complete, so there's no need
11610 * for accounting anymore.
11611 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011612 if (likely(~zone->limit == 0)) {
11613 if (!nsize)
11614 ha_free(&ptr);
11615 else
11616 ptr = realloc(ptr, nsize);
11617 return ptr;
11618 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011619
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011620 if (!ptr)
11621 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011622
Willy Tarreaucdb53462020-12-02 12:12:00 +010011623 /* enforce strict limits across all threads */
11624 limit = zone->limit;
11625 old = _HA_ATOMIC_LOAD(&zone->allocated);
11626 do {
11627 new = old + nsize - osize;
11628 if (unlikely(nsize && limit && new > limit))
11629 return NULL;
11630 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011631
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011632 if (!nsize)
11633 ha_free(&ptr);
11634 else
11635 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011636
11637 if (unlikely(!ptr && nsize)) // failed
11638 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11639
11640 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011641 return ptr;
11642}
11643
Thierry Fournierecb83c22020-11-28 15:49:44 +010011644/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011645 * We are in the initialisation process of HAProxy, this abort() is
11646 * tolerated.
11647 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011648lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011649{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011650 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011651 int idx;
11652 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011653 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011654 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011655 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011656 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011657 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011658 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011659
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011660 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011661 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011662
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011663 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011664 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011665 *context = NULL;
11666
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011667 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011668 * the Lua function can fail with an abort. We are in the initialisation
11669 * process of HAProxy, this abort() is tolerated.
11670 */
11671
Thierry Fournier3c539322020-11-28 16:05:05 +010011672 /* Call post initialisation function in safe environment. */
11673 if (setjmp(safe_ljmp_env) != 0) {
11674 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011675 if (lua_type(L, -1) == LUA_TSTRING)
11676 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011677 else
11678 error_msg = "critical error";
11679 fprintf(stderr, "Lua init: %s.\n", error_msg);
11680 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011681 } else {
11682 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011683 }
11684
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011685 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011686 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011687#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11688#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11689#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011690 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011691#endif
11692#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011693 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011694#endif
11695#undef HLUA_PREPEND_PATH_TOSTRING
11696#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011697
Thierry Fournier59f11be2020-11-29 00:37:41 +010011698 /* Apply configured prepend path */
11699 list_for_each_entry(pp, &prepend_path_list, l)
11700 hlua_prepend_path(L, pp->type, pp->path);
11701
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011702 /*
11703 *
11704 * Create "core" object.
11705 *
11706 */
11707
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011708 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011709 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011710
Thierry Fournierecb83c22020-11-28 15:49:44 +010011711 /* set the thread id */
11712 hlua_class_const_int(L, "thread", thread_num);
11713
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011714 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011715 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011716 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011717
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011718 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011719 hlua_class_function(L, "register_init", hlua_register_init);
11720 hlua_class_function(L, "register_task", hlua_register_task);
11721 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11722 hlua_class_function(L, "register_converters", hlua_register_converters);
11723 hlua_class_function(L, "register_action", hlua_register_action);
11724 hlua_class_function(L, "register_service", hlua_register_service);
11725 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011726 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011727 hlua_class_function(L, "yield", hlua_yield);
11728 hlua_class_function(L, "set_nice", hlua_set_nice);
11729 hlua_class_function(L, "sleep", hlua_sleep);
11730 hlua_class_function(L, "msleep", hlua_msleep);
11731 hlua_class_function(L, "add_acl", hlua_add_acl);
11732 hlua_class_function(L, "del_acl", hlua_del_acl);
11733 hlua_class_function(L, "set_map", hlua_set_map);
11734 hlua_class_function(L, "del_map", hlua_del_map);
11735 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011736 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011737 hlua_class_function(L, "log", hlua_log);
11738 hlua_class_function(L, "Debug", hlua_log_debug);
11739 hlua_class_function(L, "Info", hlua_log_info);
11740 hlua_class_function(L, "Warning", hlua_log_warning);
11741 hlua_class_function(L, "Alert", hlua_log_alert);
11742 hlua_class_function(L, "done", hlua_done);
11743 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011744
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011745 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011746
11747 /*
11748 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011749 * Create "act" object.
11750 *
11751 */
11752
11753 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011754 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011755
11756 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011757 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11758 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11759 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11760 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11761 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11762 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11763 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11764 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011765
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011766 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011767
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011768 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011769
11770 /*
11771 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011772 * Create "Filter" object.
11773 *
11774 */
11775
11776 /* This table entry is the object "filter" base. */
11777 lua_newtable(L);
11778
11779 /* push flags and constants */
11780 hlua_class_const_int(L, "CONTINUE", 1);
11781 hlua_class_const_int(L, "WAIT", 0);
11782 hlua_class_const_int(L, "ERROR", -1);
11783
11784 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
11785
Christopher Fauletc404f112020-02-26 15:03:09 +010011786 hlua_class_function(L, "wake_time", hlua_set_wake_time);
11787 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
11788 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
11789
Christopher Faulet69c581a2021-05-31 08:54:04 +020011790 lua_setglobal(L, "filter");
11791
11792 /*
11793 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011794 * Register class Map
11795 *
11796 */
11797
11798 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011799 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011800
11801 /* register pattern types. */
11802 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011803 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011804 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011805 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011806 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011807 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011808
11809 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011810 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011811
11812 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011813 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011814
Ilya Shipitsind4259502020-04-08 01:07:56 +050011815 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011816 lua_pushstring(L, "__index");
11817 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011818
11819 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011820 hlua_class_function(L, "lookup", hlua_map_lookup);
11821 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011822
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011823 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011824
Thierry Fournier45e78d72016-02-19 18:34:46 +010011825 /* Register previous table in the registry with reference and named entry.
11826 * The function hlua_register_metatable() pops the stack, so we
11827 * previously create a copy of the table.
11828 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011829 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
11830 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011831
11832 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011833 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011834
11835 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011836 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011837
11838 /*
11839 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011840 * Register class Channel
11841 *
11842 */
11843
11844 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011845 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011846
Ilya Shipitsind4259502020-04-08 01:07:56 +050011847 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011848 lua_pushstring(L, "__index");
11849 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011850
11851 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011852 hlua_class_function(L, "data", hlua_channel_get_data);
11853 hlua_class_function(L, "line", hlua_channel_get_line);
11854 hlua_class_function(L, "set", hlua_channel_set_data);
11855 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011856 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011857 hlua_class_function(L, "prepend", hlua_channel_prepend);
11858 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011859 hlua_class_function(L, "send", hlua_channel_send);
11860 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011861 hlua_class_function(L, "input", hlua_channel_get_in_len);
11862 hlua_class_function(L, "output", hlua_channel_get_out_len);
11863 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011864 hlua_class_function(L, "is_full", hlua_channel_is_full);
11865 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011866
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011867 /* Deprecated API */
11868 hlua_class_function(L, "get", hlua_channel_get);
11869 hlua_class_function(L, "dup", hlua_channel_dup);
11870 hlua_class_function(L, "getline", hlua_channel_getline);
11871 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
11872 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
11873
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011874 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011875
11876 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011877 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011878
11879 /*
11880 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011881 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011882 *
11883 */
11884
11885 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011886 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011887
Ilya Shipitsind4259502020-04-08 01:07:56 +050011888 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011889 lua_pushstring(L, "__index");
11890 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011891
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011892 /* Browse existing fetches and create the associated
11893 * object method.
11894 */
11895 sf = NULL;
11896 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011897 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11898 * by an underscore.
11899 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011900 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011901 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011902 if (*p == '.' || *p == '-' || *p == '+')
11903 *p = '_';
11904
11905 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011906 lua_pushstring(L, trash.area);
11907 lua_pushlightuserdata(L, sf);
11908 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
11909 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011910 }
11911
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011912 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011913
11914 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011915 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011916
11917 /*
11918 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011919 * Register class Converters
11920 *
11921 */
11922
11923 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011924 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011925
11926 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011927 lua_pushstring(L, "__index");
11928 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011929
11930 /* Browse existing converters and create the associated
11931 * object method.
11932 */
11933 sc = NULL;
11934 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011935 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11936 * by an underscore.
11937 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011938 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011939 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011940 if (*p == '.' || *p == '-' || *p == '+')
11941 *p = '_';
11942
11943 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011944 lua_pushstring(L, trash.area);
11945 lua_pushlightuserdata(L, sc);
11946 lua_pushcclosure(L, hlua_run_sample_conv, 1);
11947 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011948 }
11949
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011950 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011951
11952 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011953 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011954
11955 /*
11956 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011957 * Register class HTTP
11958 *
11959 */
11960
11961 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011962 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011963
Ilya Shipitsind4259502020-04-08 01:07:56 +050011964 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011965 lua_pushstring(L, "__index");
11966 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011967
11968 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011969 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
11970 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
11971 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
11972 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
11973 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
11974 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
11975 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
11976 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
11977 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
11978 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011979
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011980 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
11981 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
11982 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
11983 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
11984 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
11985 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
11986 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011987
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011988 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011989
11990 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011991 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011992
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011993 /*
11994 *
11995 * Register class HTTPMessage
11996 *
11997 */
11998
11999 /* Create and fill the metatable. */
12000 lua_newtable(L);
12001
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012002 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012003 lua_pushstring(L, "__index");
12004 lua_newtable(L);
12005
12006 /* Register Lua functions. */
12007 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12008 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12009 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12010 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12011 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12012 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12013 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12014 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12015 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12016 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12017 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12018 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12019 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12020 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12021 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12022 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12023 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12024 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12025
12026 hlua_class_function(L, "body", hlua_http_msg_get_body);
12027 hlua_class_function(L, "set", hlua_http_msg_set_data);
12028 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12029 hlua_class_function(L, "append", hlua_http_msg_append);
12030 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12031 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12032 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12033 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12034
12035 hlua_class_function(L, "send", hlua_http_msg_send);
12036 hlua_class_function(L, "forward", hlua_http_msg_forward);
12037
12038 lua_rawset(L, -3);
12039
12040 /* Register previous table in the registry with reference and named entry. */
12041 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012042
12043 /*
12044 *
12045 * Register class HTTPClient
12046 *
12047 */
12048
12049 /* Create and fill the metatable. */
12050 lua_newtable(L);
12051 lua_pushstring(L, "__index");
12052 lua_newtable(L);
12053 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012054 hlua_class_function(L, "head", hlua_httpclient_head);
12055 hlua_class_function(L, "put", hlua_httpclient_put);
12056 hlua_class_function(L, "post", hlua_httpclient_post);
12057 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012058 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012059 /* Register the garbage collector entry. */
12060 lua_pushstring(L, "__gc");
12061 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12062 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12063
William Lallemand3956c4e2021-09-21 16:25:15 +020012064
12065
12066 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012067 /*
12068 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012069 * Register class AppletTCP
12070 *
12071 */
12072
12073 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012074 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012075
Ilya Shipitsind4259502020-04-08 01:07:56 +050012076 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012077 lua_pushstring(L, "__index");
12078 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012079
12080 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012081 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12082 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12083 hlua_class_function(L, "send", hlua_applet_tcp_send);
12084 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12085 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12086 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12087 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12088 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012089
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012090 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012091
12092 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012093 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012094
12095 /*
12096 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012097 * Register class AppletHTTP
12098 *
12099 */
12100
12101 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012102 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012103
Ilya Shipitsind4259502020-04-08 01:07:56 +050012104 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012105 lua_pushstring(L, "__index");
12106 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012107
12108 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012109 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12110 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12111 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12112 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12113 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12114 hlua_class_function(L, "getline", hlua_applet_http_getline);
12115 hlua_class_function(L, "receive", hlua_applet_http_recv);
12116 hlua_class_function(L, "send", hlua_applet_http_send);
12117 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12118 hlua_class_function(L, "set_status", hlua_applet_http_status);
12119 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012120
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012121 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012122
12123 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012124 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012125
12126 /*
12127 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012128 * Register class TXN
12129 *
12130 */
12131
12132 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012133 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012134
Ilya Shipitsind4259502020-04-08 01:07:56 +050012135 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012136 lua_pushstring(L, "__index");
12137 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012138
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012139 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012140 hlua_class_function(L, "set_priv", hlua_set_priv);
12141 hlua_class_function(L, "get_priv", hlua_get_priv);
12142 hlua_class_function(L, "set_var", hlua_set_var);
12143 hlua_class_function(L, "unset_var", hlua_unset_var);
12144 hlua_class_function(L, "get_var", hlua_get_var);
12145 hlua_class_function(L, "done", hlua_txn_done);
12146 hlua_class_function(L, "reply", hlua_txn_reply_new);
12147 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12148 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12149 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12150 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12151 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12152 hlua_class_function(L, "deflog", hlua_txn_deflog);
12153 hlua_class_function(L, "log", hlua_txn_log);
12154 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12155 hlua_class_function(L, "Info", hlua_txn_log_info);
12156 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12157 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012158
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012159 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012160
12161 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012162 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012163
12164 /*
12165 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012166 * Register class reply
12167 *
12168 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012169 lua_newtable(L);
12170 lua_pushstring(L, "__index");
12171 lua_newtable(L);
12172 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12173 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12174 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12175 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12176 lua_settable(L, -3); /* Sets the __index entry. */
12177 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012178
12179
12180 /*
12181 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012182 * Register class Socket
12183 *
12184 */
12185
12186 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012187 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012188
Ilya Shipitsind4259502020-04-08 01:07:56 +050012189 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012190 lua_pushstring(L, "__index");
12191 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012192
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012193#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012194 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012195#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012196 hlua_class_function(L, "connect", hlua_socket_connect);
12197 hlua_class_function(L, "send", hlua_socket_send);
12198 hlua_class_function(L, "receive", hlua_socket_receive);
12199 hlua_class_function(L, "close", hlua_socket_close);
12200 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12201 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12202 hlua_class_function(L, "setoption", hlua_socket_setoption);
12203 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012204
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012205 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012206
12207 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012208 lua_pushstring(L, "__gc");
12209 lua_pushcclosure(L, hlua_socket_gc, 0);
12210 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012211
12212 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012213 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012214
Thierry Fournieraafc7772020-12-04 11:47:47 +010012215 lua_atpanic(L, hlua_panic_safe);
12216
12217 return L;
12218}
12219
12220void hlua_init(void) {
12221 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012222 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012223#ifdef USE_OPENSSL
12224 struct srv_kw *kw;
12225 int tmp_error;
12226 char *error;
12227 char *args[] = { /* SSL client configuration. */
12228 "ssl",
12229 "verify",
12230 "none",
12231 NULL
12232 };
12233#endif
12234
12235 /* Init post init function list head */
12236 for (i = 0; i < MAX_THREADS + 1; i++)
12237 LIST_INIT(&hlua_init_functions[i]);
12238
12239 /* Init state for common/shared lua parts */
12240 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012241 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012242 hlua_states[0] = hlua_init_state(0);
12243
12244 /* Init state 1 for thread 0. We have at least one thread. */
12245 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012246 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012247 hlua_states[1] = hlua_init_state(1);
12248
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012249 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012250 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012251 if (!socket_proxy) {
12252 fprintf(stderr, "Lua init: %s\n", errmsg);
12253 exit(1);
12254 }
12255 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012256
12257 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012258 socket_tcp = new_server(socket_proxy);
12259 if (!socket_tcp) {
12260 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12261 exit(1);
12262 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012263
12264#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012265 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012266 socket_ssl = new_server(socket_proxy);
12267 if (!socket_ssl) {
12268 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12269 exit(1);
12270 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012271
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012272 socket_ssl->use_ssl = 1;
12273 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012274
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012275 for (i = 0; args[i] != NULL; i++) {
12276 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012277 /*
12278 *
12279 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012280 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012281 * features like client certificates and ssl_verify.
12282 *
12283 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012284 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012285 if (tmp_error != 0) {
12286 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12287 abort(); /* This must be never arrives because the command line
12288 not editable by the user. */
12289 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012290 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012291 }
12292 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012293#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012294
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012295}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012296
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012297static void hlua_deinit()
12298{
Willy Tarreau186f3762020-12-04 11:48:12 +010012299 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012300 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12301
12302 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12303 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012304
12305 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12306 if (hlua_states[thr])
12307 lua_close(hlua_states[thr]);
12308 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012309
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012310 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012311
Willy Tarreau0f143af2021-03-05 10:41:48 +010012312#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012313 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012314#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012315
12316 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012317}
12318
12319REGISTER_POST_DEINIT(hlua_deinit);
12320
Willy Tarreau80713382018-11-26 10:19:54 +010012321static void hlua_register_build_options(void)
12322{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012323 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012324
Willy Tarreaubb57d942016-12-21 19:04:56 +010012325 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12326 hap_register_build_opts(ptr, 1);
12327}
Willy Tarreau80713382018-11-26 10:19:54 +010012328
12329INITCALL0(STG_REGISTER, hlua_register_build_options);