blob: 0098d02b8fb54a687dc4ff9c4b1da0420ee94030 [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{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001908 struct stream_interface *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);
2104 si = appctx->owner;
2105 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);
2343 si = appctx->owner;
2344 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);
2576 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);
2617 si = appctx->owner;
2618 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002619
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002620 conn = cs_conn(objt_cs(s->si[1].end));
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);
2668 si = appctx->owner;
2669 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
Willy Tarreaue09101e2018-10-16 17:37:12 +02002687 appctx = __objt_appctx(s->si[0].end);
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);
2780 si = appctx->owner;
2781 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);
2836 si = appctx->owner;
2837 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);
2892 si = appctx->owner;
2893 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;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002919 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002920
2921 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002922 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002923 hlua_pusherror(L, "socket: full stack");
2924 goto out_fail_conf;
2925 }
2926
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002927 /* Create the object: obj[0] = userdata. */
2928 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002929 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002930 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002931 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002932 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002934 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002935 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002936 hlua_pusherror(L, "socket: uninitialized pools.");
2937 goto out_fail_conf;
2938 }
2939
Willy Tarreau87b09662015-04-03 00:22:06 +02002940 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002941 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2942 lua_setmetatable(L, -2);
2943
Willy Tarreaud420a972015-04-06 00:39:18 +02002944 /* Create the applet context */
Willy Tarreaue6124462021-09-13 10:07:38 +02002945 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002946 if (!appctx) {
2947 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002948 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002949 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002950
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002951 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002952 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002953 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2954 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002955
Willy Tarreaud420a972015-04-06 00:39:18 +02002956 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002957 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002958 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002959 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002960 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002961 }
2962
Christopher Faulet26256f82020-09-14 11:40:13 +02002963 strm = stream_new(sess, &appctx->obj_type, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002964 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002965 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002966 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002967 }
2968
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002969 /* Initialise cross reference between stream and Lua socket object. */
2970 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002971
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002972 /* Configure "right" stream interface. this "si" is used to connect
2973 * and retrieve data from the server. The connection is initialized
2974 * with the "struct server".
2975 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002976 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002977
2978 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002979 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002980 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002981
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002982 return 1;
2983
Willy Tarreaud420a972015-04-06 00:39:18 +02002984 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002985 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002986 out_fail_sess:
2987 appctx_free(appctx);
2988 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002989 WILL_LJMP(lua_error(L));
2990 return 0;
2991}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002992
2993/*
2994 *
2995 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002996 * Class Channel
2997 *
2998 *
2999 */
3000
3001/* Returns the struct hlua_channel join to the class channel in the
3002 * stack entry "ud" or throws an argument error.
3003 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003004__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003005{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003006 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003007}
3008
Willy Tarreau47860ed2015-03-10 14:07:50 +01003009/* Pushes the channel onto the top of the stack. If the stask does not have a
3010 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003011 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003012static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003013{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003014 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003015 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003016 return 0;
3017
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003018 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003019 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003020 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003021
3022 /* Pop a class sesison metatable and affect it to the userdata. */
3023 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3024 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003025 return 1;
3026}
3027
Christopher Faulet9f55a502020-02-25 15:21:02 +01003028/* Helper function returning a filter attached to a channel at the position <ud>
3029 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003030 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003031 * initialized.
3032 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003033static 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 +01003034{
3035 struct filter *filter = NULL;
3036
3037 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3038 struct hlua_flt_ctx *flt_ctx;
3039
3040 filter = lua_touserdata (L, -1);
3041 flt_ctx = filter->ctx;
3042 if (hlua_filter_from_payload(filter)) {
3043 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3044 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3045 }
3046 }
3047
3048 lua_pop(L, 1);
3049 return filter;
3050}
3051
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003052/* Copies <len> bytes of data present in the channel's buffer, starting at the
3053* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003054* responsibility to ensure <len> and <offset> are valid. It always return the
3055* length of the built string. <len> may be 0, in this case, an empty string is
3056* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003057*/
3058static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003059{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003060 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003061 luaL_Buffer b;
3062
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003063 block1 = len;
3064 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3065 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3066 block2 = len - block1;
3067
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003068 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003069 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3070 if (block2)
3071 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003072 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003073 return len;
3074}
3075
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003076/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3077 * function returns -1 if data cannot be copied. Otherwise, it returns the
3078 * number of bytes copied.
3079 */
3080static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3081{
3082 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003083
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003084 /* Nothing to do, just return */
3085 if (unlikely(istlen(str) == 0))
3086 goto end;
3087
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003088 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003089 ret = -1;
3090 goto end;
3091 }
3092 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3093
3094 end:
3095 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003096}
3097
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003098/* Removes <len> bytes of data at the absolute position <offset>.
3099 */
3100static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3101{
3102 size_t end = offset + len;
3103
3104 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3105 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3106 b_data(&chn->buf) - end, -len);
3107 b_sub(&chn->buf, len);
3108}
3109
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003110/* Copies input data in the channel's buffer. It is possible to set a specific
3111 * offset (0 by default) and a length (all remaining input data starting for the
3112 * offset by default). If there is not enough input data and more data can be
3113 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003114 *
3115 * From an action, All input data are considered. For a filter, the offset and
3116 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003117 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003118__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003119{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003120 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003121 struct filter *filter;
3122 size_t input, output;
3123 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003124
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003125 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003126
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003127 output = co_data(chn);
3128 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003129
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003130 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3131 if (filter && !hlua_filter_from_payload(filter))
3132 WILL_LJMP(lua_error(L));
3133
3134 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003135 if (lua_gettop(L) > 1) {
3136 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3137 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003138 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003139 offset += output;
3140 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003141 lua_pushfstring(L, "offset out of range.");
3142 WILL_LJMP(lua_error(L));
3143 }
3144 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003145 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003146 if (lua_gettop(L) == 3) {
3147 len = MAY_LJMP(luaL_checkinteger(L, 3));
3148 if (!len)
3149 goto dup;
3150 if (len == -1)
3151 len = global.tune.bufsize;
3152 if (len < 0) {
3153 lua_pushfstring(L, "length out of range.");
3154 WILL_LJMP(lua_error(L));
3155 }
3156 }
3157
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003158 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003159 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3160 /* Yield waiting for more data, as requested */
3161 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3162 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003163 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003164 }
3165
3166 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003167 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003168 return 1;
3169}
3170
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003171/* Copies the first line (including the trailing LF) of input data in the
3172 * channel's buffer. It is possible to set a specific offset (0 by default) and
3173 * a length (all remaining input data starting for the offset by default). If
3174 * there is not enough input data and more data can be received, the function
3175 * yields. If a length is explicitly specified, no more data are
3176 * copied. Otherwise, if no LF is found and more data can be received, this
3177 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003178 *
3179 * From an action, All input data are considered. For a filter, the offset and
3180 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003181 */
3182__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003183{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003184 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003185 struct filter *filter;
3186 size_t l, input, output;
3187 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003188
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003189 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003190 output = co_data(chn);
3191 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003192
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003193 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3194 if (filter && !hlua_filter_from_payload(filter))
3195 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003196
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003197 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003198 if (lua_gettop(L) > 1) {
3199 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3200 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003201 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003202 offset += output;
3203 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003204 lua_pushfstring(L, "offset out of range.");
3205 WILL_LJMP(lua_error(L));
3206 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003207 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003208
3209 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210 if (lua_gettop(L) == 3) {
3211 len = MAY_LJMP(luaL_checkinteger(L, 3));
3212 if (!len)
3213 goto dup;
3214 if (len == -1)
3215 len = global.tune.bufsize;
3216 if (len < 0) {
3217 lua_pushfstring(L, "length out of range.");
3218 WILL_LJMP(lua_error(L));
3219 }
3220 }
3221
3222 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003223 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003224 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003225 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003226 len = l+1;
3227 goto dup;
3228 }
3229 }
3230
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003231 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003232 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3233 /* Yield waiting for more data */
3234 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3235 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003236 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003237 }
3238
3239 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003240 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003241 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003242}
3243
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003244/* [ DEPRECATED ]
3245 *
3246 * Duplicate all input data foud in the channel's buffer. The data are not
3247 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003248 *
3249 * From an action, All input data are considered. For a filter, the offset and
3250 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003251 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003252__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003253{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003254 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003255 struct filter *filter;
3256 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003257
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003258 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003259 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003260 if (IS_HTX_STRM(chn_strm(chn))) {
3261 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3262 WILL_LJMP(lua_error(L));
3263 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003264
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003265 offset = co_data(chn);
3266 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003267
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003268 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3269 if (filter && !hlua_filter_from_payload(filter))
3270 WILL_LJMP(lua_error(L));
3271
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003272 if (!ci_data(chn) && channel_input_closed(chn)) {
3273 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003274 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003275 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003276
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003277 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003278 return 1;
3279}
3280
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003281/* [ DEPRECATED ]
3282 *
3283 * Get all input data foud in the channel's buffer. The data are removed from
3284 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3285 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003286 *
3287 * From an action, All input data are considered. For a filter, the offset and
3288 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003289 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003290__LJMP static int hlua_channel_get(lua_State *L)
3291{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003292 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003293 struct filter *filter;
3294 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003295 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003296
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003297 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003298 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3299 if (IS_HTX_STRM(chn_strm(chn))) {
3300 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3301 WILL_LJMP(lua_error(L));
3302 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003303
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003304 offset = co_data(chn);
3305 len = ci_data(chn);
3306
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003307 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3308 if (filter && !hlua_filter_from_payload(filter))
3309 WILL_LJMP(lua_error(L));
3310
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003311 if (!ci_data(chn) && channel_input_closed(chn)) {
3312 lua_pushnil(L);
3313 return 1;
3314 }
3315
3316 ret = _hlua_channel_dup(chn, L, offset, len);
3317 _hlua_channel_delete(chn, offset, ret);
3318 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003319}
3320
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003321/* This functions consumes and returns one line. If the channel is closed,
3322 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003323 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003324 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003325 *
3326 * From an action, All input data are considered. For a filter, the offset and
3327 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003328 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003329__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003330{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003331 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003332 struct filter *filter;
3333 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003334 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003335
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003336 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003337
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003338 offset = co_data(chn);
3339 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003340
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003341 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3342 if (filter && !hlua_filter_from_payload(filter))
3343 WILL_LJMP(lua_error(L));
3344
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003345 if (!ci_data(chn) && channel_input_closed(chn)) {
3346 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003347 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003348 }
3349
3350 for (l = 0; l < len; l++) {
3351 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3352 len = l+1;
3353 goto dup;
3354 }
3355 }
3356
3357 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3358 /* Yield waiting for more data */
3359 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3360 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003361
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003362 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003363 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003364 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003365 return 1;
3366}
3367
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003368/* [ DEPRECATED ]
3369 *
3370 * Check arguments for the function "hlua_channel_getline_yield".
3371 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003372__LJMP static int hlua_channel_getline(lua_State *L)
3373{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003374 struct channel *chn;
3375
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003376 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003377 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3378 if (IS_HTX_STRM(chn_strm(chn))) {
3379 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3380 WILL_LJMP(lua_error(L));
3381 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003382 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3383}
3384
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003385/* Retrieves a given amount of input data at the given offset. By default all
3386 * available input data are returned. The offset may be negactive to start from
3387 * the end of input data. The length may be -1 to set it to the maximum buffer
3388 * size.
3389 */
3390__LJMP static int hlua_channel_get_data(lua_State *L)
3391{
3392 struct channel *chn;
3393
3394 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3395 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3396 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3397 if (IS_HTX_STRM(chn_strm(chn))) {
3398 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3399 WILL_LJMP(lua_error(L));
3400 }
3401 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3402}
3403
3404/* Retrieves a given amount of input data at the given offset. By default all
3405 * available input data are returned. The offset may be negactive to start from
3406 * the end of input data. The length may be -1 to set it to the maximum buffer
3407 * size.
3408 */
3409__LJMP static int hlua_channel_get_line(lua_State *L)
3410{
3411 struct channel *chn;
3412
3413 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3414 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3415 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3416 if (IS_HTX_STRM(chn_strm(chn))) {
3417 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3418 WILL_LJMP(lua_error(L));
3419 }
3420 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3421}
3422
3423/* Appends a string into the input side of channel. It returns the length of the
3424 * written string, or -1 if the channel is closed or if the buffer size is too
3425 * little for the data. 0 may be returned if nothing is copied. This function
3426 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003427 *
3428 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003429 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003430__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003431{
Christopher Faulet23976d92021-08-06 09:59:49 +02003432 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003433 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003434 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003435 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003436 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003437
3438 MAY_LJMP(check_args(L, 2, "append"));
3439 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003440 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003441 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003442 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003443 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003444 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003445
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003446 offset = co_data(chn);
3447 len = ci_data(chn);
3448
3449 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3450 if (filter && !hlua_filter_from_payload(filter))
3451 WILL_LJMP(lua_error(L));
3452
3453 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3454 if (ret > 0 && filter) {
3455 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3456
3457 flt_update_offsets(filter, chn, ret);
3458 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3459 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003460 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003461 return 1;
3462}
3463
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003464/* Prepends a string into the input side of channel. It returns the length of the
3465 * written string, or -1 if the channel is closed or if the buffer size is too
3466 * little for the data. 0 may be returned if nothing is copied. This function
3467 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003468 *
3469 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003470 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003471__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003472{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003473 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003474 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003475 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003476 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003477 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003478
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003479 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003480 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003481 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3482 if (IS_HTX_STRM(chn_strm(chn))) {
3483 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3484 WILL_LJMP(lua_error(L));
3485 }
3486
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003487 offset = co_data(chn);
3488 len = ci_data(chn);
3489
3490 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3491 if (filter && !hlua_filter_from_payload(filter))
3492 WILL_LJMP(lua_error(L));
3493
3494 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3495 if (ret > 0 && filter) {
3496 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3497
3498 flt_update_offsets(filter, chn, ret);
3499 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3500 }
3501
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003502 lua_pushinteger(L, ret);
3503 return 1;
3504}
3505
3506/* Inserts a given amount of input data at the given offset by a string
3507 * content. By default the string is appended at the end of input data. It
3508 * returns the length of the written string, or -1 if the channel is closed or
3509 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003510 *
3511 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003512 */
3513__LJMP static int hlua_channel_insert_data(lua_State *L)
3514{
3515 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003516 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003517 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003518 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003519 int ret, offset;
3520
3521 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3522 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3523 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3524 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003525
3526 output = co_data(chn);
3527 input = ci_data(chn);
3528
3529 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3530 if (filter && !hlua_filter_from_payload(filter))
3531 WILL_LJMP(lua_error(L));
3532
3533 offset = input + output;
3534 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003535 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003536 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003537 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003538 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003539 if (offset < output || offset > output + input) {
3540 lua_pushfstring(L, "offset out of range.");
3541 WILL_LJMP(lua_error(L));
3542 }
3543 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003544 if (IS_HTX_STRM(chn_strm(chn))) {
3545 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3546 WILL_LJMP(lua_error(L));
3547 }
3548
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003549 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3550 if (ret > 0 && filter) {
3551 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003552
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003553 flt_update_offsets(filter, chn, ret);
3554 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003555 }
3556
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003557 lua_pushinteger(L, ret);
3558 return 1;
3559}
3560/* Replaces a given amount of input data at the given offset by a string
3561 * content. By default all remaining data are removed (offset = 0 and len =
3562 * -1). It returns the length of the written string, or -1 if the channel is
3563 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003564 *
3565 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566 */
3567__LJMP static int hlua_channel_set_data(lua_State *L)
3568{
3569 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003570 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003571 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003572 size_t sz, input, output;
3573 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003574
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003575 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3576 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3577 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3578 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003579
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003580 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003581 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003582 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003583 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003584
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003585 output = co_data(chn);
3586 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003587
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003588 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3589 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003590 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003591
3592 offset = output;
3593 if (lua_gettop(L) > 2) {
3594 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3595 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003596 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003597 offset += output;
3598 if (offset < output || offset > input + output) {
3599 lua_pushfstring(L, "offset out of range.");
3600 WILL_LJMP(lua_error(L));
3601 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003602 }
3603
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003604 len = output + input - offset;
3605 if (lua_gettop(L) == 4) {
3606 len = MAY_LJMP(luaL_checkinteger(L, 4));
3607 if (!len)
3608 goto set;
3609 if (len == -1)
3610 len = output + input - offset;
3611 if (len < 0 || offset + len > output + input) {
3612 lua_pushfstring(L, "length out of range.");
3613 WILL_LJMP(lua_error(L));
3614 }
3615 }
3616
3617 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003618 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003619 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003620 lua_pushinteger(L, -1);
3621 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003622 _hlua_channel_delete(chn, offset, len);
3623 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3624 if (filter) {
3625 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3626
3627 len -= (ret > 0 ? ret : 0);
3628 flt_update_offsets(filter, chn, -len);
3629 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3630 }
3631
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003632 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003633 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003634 return 1;
3635}
3636
3637/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003638 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003639 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003640 *
3641 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003642 */
3643__LJMP static int hlua_channel_del_data(lua_State *L)
3644{
3645 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003646 struct filter *filter;
3647 size_t input, output;
3648 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003649
3650 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3651 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3652 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003653
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003654 if (IS_HTX_STRM(chn_strm(chn))) {
3655 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3656 WILL_LJMP(lua_error(L));
3657 }
3658
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003659 output = co_data(chn);
3660 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003661
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003662 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3663 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003664 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003665
3666 offset = output;
3667 if (lua_gettop(L) > 2) {
3668 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3669 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003670 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003671 offset += output;
3672 if (offset < output || offset > input + output) {
3673 lua_pushfstring(L, "offset out of range.");
3674 WILL_LJMP(lua_error(L));
3675 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003676 }
3677
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003678 len = output + input - offset;
3679 if (lua_gettop(L) == 4) {
3680 len = MAY_LJMP(luaL_checkinteger(L, 4));
3681 if (!len)
3682 goto end;
3683 if (len == -1)
3684 len = output + input - offset;
3685 if (len < 0 || offset + len > output + input) {
3686 lua_pushfstring(L, "length out of range.");
3687 WILL_LJMP(lua_error(L));
3688 }
3689 }
3690
3691 _hlua_channel_delete(chn, offset, len);
3692 if (filter) {
3693 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3694
3695 flt_update_offsets(filter, chn, -len);
3696 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3697 }
3698
3699 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003700 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003701 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003702}
3703
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003704/* Append data in the output side of the buffer. This data is immediately
3705 * sent. The function returns the amount of data written. If the buffer
3706 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003707 * if the channel is closed.
3708 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003709__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003710{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003711 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003712 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003713 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003714 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003715 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003716 struct hlua *hlua;
3717
3718 /* Get hlua struct, or NULL if we execute from main lua state */
3719 hlua = hlua_gethlua(L);
3720 if (!hlua) {
3721 lua_pushnil(L);
3722 return 1;
3723 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003724
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003725 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3726 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3727 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003728
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003729 offset = co_data(chn);
3730 len = ci_data(chn);
3731
3732 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3733 if (filter && !hlua_filter_from_payload(filter))
3734 WILL_LJMP(lua_error(L));
3735
3736
Willy Tarreau47860ed2015-03-10 14:07:50 +01003737 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003738 lua_pushinteger(L, -1);
3739 return 1;
3740 }
3741
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003742 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003743 if (len > sz -l) {
3744 if (filter) {
3745 lua_pushinteger(L, -1);
3746 return 1;
3747 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003748 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003749 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003750
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003751 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003752 if (ret == -1) {
3753 lua_pop(L, 1);
3754 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003755 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003756 }
3757 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758 if (filter) {
3759 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3760
3761
3762 flt_update_offsets(filter, chn, ret);
3763 FLT_OFF(filter, chn) += ret;
3764 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3765 }
3766 else
3767 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003768
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003769 l += ret;
3770 lua_pop(L, 1);
3771 lua_pushinteger(L, l);
3772 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003773
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003774 if (l < sz) {
3775 /* Yield only if the channel's output is not empty.
3776 * Otherwise it means we cannot add more data. */
3777 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003778 return 1;
3779
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003780 /* If we are waiting for space in the response buffer, we
3781 * must set the flag WAKERESWR. This flag required the task
3782 * wake up if any activity is detected on the response buffer.
3783 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003784 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003785 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003786 else
3787 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003788 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003789 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003790
3791 return 1;
3792}
3793
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003794/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003795 * yield the LUA process, and resume it without checking the
3796 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003797 *
3798 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003799 */
3800__LJMP static int hlua_channel_send(lua_State *L)
3801{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003802 struct channel *chn;
3803
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003804 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003805 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3806 if (IS_HTX_STRM(chn_strm(chn))) {
3807 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3808 WILL_LJMP(lua_error(L));
3809 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003810 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003811 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003812}
3813
3814/* This function forward and amount of butes. The data pass from
3815 * the input side of the buffer to the output side, and can be
3816 * forwarded. This function never fails.
3817 *
3818 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003819 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003820 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003821__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003822{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003823 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003824 struct filter *filter;
3825 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003826 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003827 struct hlua *hlua;
3828
3829 /* Get hlua struct, or NULL if we execute from main lua state */
3830 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003831 if (!hlua) {
3832 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003833 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003834 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003835
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003836 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003837 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003838 l = MAY_LJMP(luaL_checkinteger(L, -1));
3839
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003840 offset = co_data(chn);
3841 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003842
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003843 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3844 if (filter && !hlua_filter_from_payload(filter))
3845 WILL_LJMP(lua_error(L));
3846
3847 max = fwd - l;
3848 if (max > len)
3849 max = len;
3850
3851 if (filter) {
3852 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3853
3854 FLT_OFF(filter, chn) += max;
3855 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3856 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3857 }
3858 else
3859 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003860
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003861 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003862 lua_pop(L, 1);
3863 lua_pushinteger(L, l);
3864
3865 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003866 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003867 /* The the input channel or the output channel are closed, we
3868 * must return the amount of data forwarded.
3869 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003870 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003871 return 1;
3872
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003873 /* If we are waiting for space data in the response buffer, we
3874 * must set the flag WAKERESWR. This flag required the task
3875 * wake up if any activity is detected on the response buffer.
3876 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003877 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003878 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003879 else
3880 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003881
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003882 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003883 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003884 }
3885
3886 return 1;
3887}
3888
3889/* Just check the input and prepare the stack for the previous
3890 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003891 *
3892 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003893 */
3894__LJMP static int hlua_channel_forward(lua_State *L)
3895{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003896 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003897
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003898 MAY_LJMP(check_args(L, 2, "forward"));
3899 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3900 if (IS_HTX_STRM(chn_strm(chn))) {
3901 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3902 WILL_LJMP(lua_error(L));
3903 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003904 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003905 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003906}
3907
3908/* Just returns the number of bytes available in the input
3909 * side of the buffer. This function never fails.
3910 */
3911__LJMP static int hlua_channel_get_in_len(lua_State *L)
3912{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003913 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003914 struct filter *filter;
3915 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003916
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003917 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003918 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003919
3920 output = co_data(chn);
3921 input = ci_data(chn);
3922 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3923 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3924 lua_pushinteger(L, input);
3925 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003926 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003927
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003928 lua_pushinteger(L, htx->data - co_data(chn));
3929 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003930 return 1;
3931}
3932
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003933/* Returns true if the channel is full. */
3934__LJMP static int hlua_channel_is_full(lua_State *L)
3935{
3936 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003937
3938 MAY_LJMP(check_args(L, 1, "is_full"));
3939 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003940 /* ignore the reserve, we are not on a producer side (ie in an
3941 * applet).
3942 */
3943 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003944 return 1;
3945}
3946
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003947/* Returns true if the channel may still receive data. */
3948__LJMP static int hlua_channel_may_recv(lua_State *L)
3949{
3950 struct channel *chn;
3951
3952 MAY_LJMP(check_args(L, 1, "may_recv"));
3953 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3954 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3955 return 1;
3956}
3957
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003958/* Returns true if the channel is the response channel. */
3959__LJMP static int hlua_channel_is_resp(lua_State *L)
3960{
3961 struct channel *chn;
3962
3963 MAY_LJMP(check_args(L, 1, "is_resp"));
3964 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3965
3966 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3967 return 1;
3968}
3969
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003970/* Just returns the number of bytes available in the output
3971 * side of the buffer. This function never fails.
3972 */
3973__LJMP static int hlua_channel_get_out_len(lua_State *L)
3974{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003975 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003976 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003977
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003978 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003979 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003980
3981 output = co_data(chn);
3982 input = ci_data(chn);
3983 hlua_channel_filter(L, 1, chn, &output, &input);
3984
3985 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003986 return 1;
3987}
3988
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003989/*
3990 *
3991 *
3992 * Class Fetches
3993 *
3994 *
3995 */
3996
3997/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003998 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003999 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004000__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004001{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004002 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004003}
4004
4005/* This function creates and push in the stack a fetch object according
4006 * with a current TXN.
4007 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004008static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004009{
Willy Tarreau7073c472015-04-06 11:15:40 +02004010 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004011
4012 /* Check stack size. */
4013 if (!lua_checkstack(L, 3))
4014 return 0;
4015
4016 /* Create the object: obj[0] = userdata.
4017 * Note that the base of the Fetches object is the
4018 * transaction object.
4019 */
4020 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004021 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004022 lua_rawseti(L, -2, 0);
4023
Willy Tarreau7073c472015-04-06 11:15:40 +02004024 hsmp->s = txn->s;
4025 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004026 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004027 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004028
4029 /* Pop a class sesison metatable and affect it to the userdata. */
4030 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4031 lua_setmetatable(L, -2);
4032
4033 return 1;
4034}
4035
4036/* This function is an LUA binding. It is called with each sample-fetch.
4037 * It uses closure argument to store the associated sample-fetch. It
4038 * returns only one argument or throws an error. An error is thrown
4039 * only if an error is encountered during the argument parsing. If
4040 * the "sample-fetch" function fails, nil is returned.
4041 */
4042__LJMP static int hlua_run_sample_fetch(lua_State *L)
4043{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004044 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004045 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004046 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004047 int i;
4048 struct sample smp;
4049
4050 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004051 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004052
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004053 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004054 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004055
Thierry FOURNIERca988662015-12-20 18:43:03 +01004056 /* Check execution authorization. */
4057 if (f->use & SMP_USE_HTTP_ANY &&
4058 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4059 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4060 "is not available in Lua services", f->kw);
4061 WILL_LJMP(lua_error(L));
4062 }
4063
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004064 /* Get extra arguments. */
4065 for (i = 0; i < lua_gettop(L) - 1; i++) {
4066 if (i >= ARGM_NBARGS)
4067 break;
4068 hlua_lua2arg(L, i + 2, &args[i]);
4069 }
4070 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004071 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004072
4073 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004074 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004075
4076 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004077 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004078 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004079 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004080 }
4081
4082 /* Initialise the sample. */
4083 memset(&smp, 0, sizeof(smp));
4084
4085 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004086 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004087 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004088 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004089 lua_pushstring(L, "");
4090 else
4091 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004092 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004093 }
4094
4095 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004096 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004097 hlua_smp2lua_str(L, &smp);
4098 else
4099 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004100
4101 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004102 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004103 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004104
4105 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004106 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004107 WILL_LJMP(lua_error(L));
4108 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004109}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004110
4111/*
4112 *
4113 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004114 * Class Converters
4115 *
4116 *
4117 */
4118
4119/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004120 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004121 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004122__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004123{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004124 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004125}
4126
4127/* This function creates and push in the stack a Converters object
4128 * according with a current TXN.
4129 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004130static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004131{
Willy Tarreau7073c472015-04-06 11:15:40 +02004132 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004133
4134 /* Check stack size. */
4135 if (!lua_checkstack(L, 3))
4136 return 0;
4137
4138 /* Create the object: obj[0] = userdata.
4139 * Note that the base of the Converters object is the
4140 * same than the TXN object.
4141 */
4142 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004143 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004144 lua_rawseti(L, -2, 0);
4145
Willy Tarreau7073c472015-04-06 11:15:40 +02004146 hsmp->s = txn->s;
4147 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004148 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004149 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004150
Willy Tarreau87b09662015-04-03 00:22:06 +02004151 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004152 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4153 lua_setmetatable(L, -2);
4154
4155 return 1;
4156}
4157
4158/* This function is an LUA binding. It is called with each converter.
4159 * It uses closure argument to store the associated converter. It
4160 * returns only one argument or throws an error. An error is thrown
4161 * only if an error is encountered during the argument parsing. If
4162 * the converter function function fails, nil is returned.
4163 */
4164__LJMP static int hlua_run_sample_conv(lua_State *L)
4165{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004166 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004167 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004168 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004169 int i;
4170 struct sample smp;
4171
4172 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004173 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004174
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004175 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004176 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004177
4178 /* Get extra arguments. */
4179 for (i = 0; i < lua_gettop(L) - 2; i++) {
4180 if (i >= ARGM_NBARGS)
4181 break;
4182 hlua_lua2arg(L, i + 3, &args[i]);
4183 }
4184 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004185 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004186
4187 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004188 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004189
4190 /* Run the special args checker. */
4191 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4192 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004193 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004194 }
4195
4196 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004197 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004198 if (!hlua_lua2smp(L, 2, &smp)) {
4199 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004200 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004201 }
4202
Willy Tarreau1777ea62016-03-10 16:15:46 +01004203 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4204
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004205 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004206 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004207 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004208 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004209 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004211 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4212 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004213 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004214 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004215 }
4216
4217 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004218 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004219 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004220 lua_pushstring(L, "");
4221 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004222 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004223 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004224 }
4225
4226 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004227 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004228 hlua_smp2lua_str(L, &smp);
4229 else
4230 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004231 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004232 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004233 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004234
4235 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004236 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004237 WILL_LJMP(lua_error(L));
4238 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004239}
4240
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004241/*
4242 *
4243 *
4244 * Class AppletTCP
4245 *
4246 *
4247 */
4248
4249/* Returns a struct hlua_txn if the stack entry "ud" is
4250 * a class stream, otherwise it throws an error.
4251 */
4252__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4253{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004254 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004255}
4256
4257/* This function creates and push in the stack an Applet object
4258 * according with a current TXN.
4259 */
4260static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4261{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004262 struct hlua_appctx *luactx;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004263 struct stream_interface *si = ctx->owner;
4264 struct stream *s = si_strm(si);
4265 struct proxy *p = s->be;
4266
4267 /* Check stack size. */
4268 if (!lua_checkstack(L, 3))
4269 return 0;
4270
4271 /* Create the object: obj[0] = userdata.
4272 * Note that the base of the Converters object is the
4273 * same than the TXN object.
4274 */
4275 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004276 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004277 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004278 luactx->appctx = ctx;
4279 luactx->htxn.s = s;
4280 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004281
4282 /* Create the "f" field that contains a list of fetches. */
4283 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004284 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004285 return 0;
4286 lua_settable(L, -3);
4287
4288 /* Create the "sf" field that contains a list of stringsafe fetches. */
4289 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004290 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004291 return 0;
4292 lua_settable(L, -3);
4293
4294 /* Create the "c" field that contains a list of converters. */
4295 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004296 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004297 return 0;
4298 lua_settable(L, -3);
4299
4300 /* Create the "sc" field that contains a list of stringsafe converters. */
4301 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004302 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004303 return 0;
4304 lua_settable(L, -3);
4305
4306 /* Pop a class stream metatable and affect it to the table. */
4307 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4308 lua_setmetatable(L, -2);
4309
4310 return 1;
4311}
4312
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004313__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4314{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004315 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004316 struct stream *s;
4317 const char *name;
4318 size_t len;
4319 struct sample smp;
4320
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004321 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4322 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004323
4324 /* It is useles to retrieve the stream, but this function
4325 * runs only in a stream context.
4326 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004327 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004328 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004329 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004330
4331 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004332 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004333 hlua_lua2smp(L, 3, &smp);
4334
4335 /* Store the sample in a variable. */
4336 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004337
4338 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4339 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4340 else
4341 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4342
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004343 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004344}
4345
4346__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4347{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004348 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004349 struct stream *s;
4350 const char *name;
4351 size_t len;
4352 struct sample smp;
4353
4354 MAY_LJMP(check_args(L, 2, "unset_var"));
4355
4356 /* It is useles to retrieve the stream, but this function
4357 * runs only in a stream context.
4358 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004359 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004360 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004361 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004362
4363 /* Unset the variable. */
4364 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004365 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4366 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004367}
4368
4369__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4370{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004371 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004372 struct stream *s;
4373 const char *name;
4374 size_t len;
4375 struct sample smp;
4376
4377 MAY_LJMP(check_args(L, 2, "get_var"));
4378
4379 /* It is useles to retrieve the stream, but this function
4380 * runs only in a stream context.
4381 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004382 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004383 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004384 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004385
4386 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004387 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004388 lua_pushnil(L);
4389 return 1;
4390 }
4391
4392 return hlua_smp2lua(L, &smp);
4393}
4394
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004395__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4396{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004397 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4398 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004399 struct hlua *hlua;
4400
4401 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004402 if (!s->hlua)
4403 return 0;
4404 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004405
4406 MAY_LJMP(check_args(L, 2, "set_priv"));
4407
4408 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004409 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004410
4411 /* Get and store new value. */
4412 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4413 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4414
4415 return 0;
4416}
4417
4418__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4419{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004420 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4421 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004422 struct hlua *hlua;
4423
4424 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004425 if (!s->hlua) {
4426 lua_pushnil(L);
4427 return 1;
4428 }
4429 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004430
4431 /* Push configuration index in the stack. */
4432 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4433
4434 return 1;
4435}
4436
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004437/* If expected data not yet available, it returns a yield. This function
4438 * consumes the data in the buffer. It returns a string containing the
4439 * data. This string can be empty.
4440 */
4441__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4442{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004443 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4444 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004445 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004446 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004447 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004448 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004449 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004450
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004451 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004452 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004453
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004454 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004455 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004456 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004457 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004458 }
4459
4460 /* End of data: commit the total strings and return. */
4461 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004462 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004463 return 1;
4464 }
4465
4466 /* Ensure that the block 2 length is usable. */
4467 if (ret == 1)
4468 len2 = 0;
4469
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004470 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004471 luaL_addlstring(&luactx->b, blk1, len1);
4472 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004473
4474 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004475 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004476 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004477 return 1;
4478}
4479
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004480/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004481__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4482{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004483 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004484
4485 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004487
4488 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4489}
4490
4491/* If expected data not yet available, it returns a yield. This function
4492 * consumes the data in the buffer. It returns a string containing the
4493 * data. This string can be empty.
4494 */
4495__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4496{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004497 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4498 struct stream_interface *si = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004499 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004500 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004501 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004502 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004503 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004504 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004505
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004506 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004507 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004508
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004509 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004510 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004511 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004512 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004513 }
4514
4515 /* End of data: commit the total strings and return. */
4516 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004517 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004518 return 1;
4519 }
4520
4521 /* Ensure that the block 2 length is usable. */
4522 if (ret == 1)
4523 len2 = 0;
4524
4525 if (len == -1) {
4526
4527 /* If len == -1, catenate all the data avalaile and
4528 * yield because we want to get all the data until
4529 * the end of data stream.
4530 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004531 luaL_addlstring(&luactx->b, blk1, len1);
4532 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004533 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004534 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004535 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004536
4537 } else {
4538
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004539 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004540 if (len1 > len)
4541 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004542 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004543 len -= len1;
4544
4545 /* Copy the second block. */
4546 if (len2 > len)
4547 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004548 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004549 len -= len2;
4550
4551 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004552 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004554 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004555 if (len > 0) {
4556 lua_pushinteger(L, len);
4557 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004558 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004559 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004560 }
4561
4562 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004563 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004564 return 1;
4565 }
4566
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004567 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004568 hlua_pusherror(L, "Lua: internal error");
4569 WILL_LJMP(lua_error(L));
4570 return 0;
4571}
4572
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004573/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004574__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4575{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004576 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004577 int len = -1;
4578
4579 if (lua_gettop(L) > 2)
4580 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4581 if (lua_gettop(L) >= 2) {
4582 len = MAY_LJMP(luaL_checkinteger(L, 2));
4583 lua_pop(L, 1);
4584 }
4585
4586 /* Confirm or set the required length */
4587 lua_pushinteger(L, len);
4588
4589 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004590 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004591
4592 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4593}
4594
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004595/* Append data in the output side of the buffer. This data is immediately
4596 * sent. The function returns the amount of data written. If the buffer
4597 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004598 * if the channel is closed.
4599 */
4600__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4601{
4602 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004603 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004604 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4605 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004606 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607 struct channel *chn = si_ic(si);
4608 int max;
4609
4610 /* Get the max amount of data which can write as input in the channel. */
4611 max = channel_recv_max(chn);
4612 if (max > (len - l))
4613 max = len - l;
4614
4615 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004616 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004617
4618 /* update counters. */
4619 l += max;
4620 lua_pop(L, 1);
4621 lua_pushinteger(L, l);
4622
4623 /* If some data is not send, declares the situation to the
4624 * applet, and returns a yield.
4625 */
4626 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004627 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004628 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004629 }
4630
4631 return 1;
4632}
4633
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004634/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004635 * yield the LUA process, and resume it without checking the
4636 * input arguments.
4637 */
4638__LJMP static int hlua_applet_tcp_send(lua_State *L)
4639{
4640 MAY_LJMP(check_args(L, 2, "send"));
4641 lua_pushinteger(L, 0);
4642
4643 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4644}
4645
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004646/*
4647 *
4648 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004649 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004650 *
4651 *
4652 */
4653
4654/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004655 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004656 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004657__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004658{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004659 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004660}
4661
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004662/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004663 * according with a current TXN.
4664 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004665static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004666{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004667 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004668 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004669 struct stream_interface *si = ctx->owner;
4670 struct stream *s = si_strm(si);
4671 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004672 struct htx *htx;
4673 struct htx_blk *blk;
4674 struct htx_sl *sl;
4675 struct ist path;
4676 unsigned long long len = 0;
4677 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004678 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004679
4680 /* Check stack size. */
4681 if (!lua_checkstack(L, 3))
4682 return 0;
4683
4684 /* Create the object: obj[0] = userdata.
4685 * Note that the base of the Converters object is the
4686 * same than the TXN object.
4687 */
4688 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004689 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004690 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004691 luactx->appctx = ctx;
4692 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4693 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4694 luactx->htxn.s = s;
4695 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004696
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004697 /* Create the "f" field that contains a list of fetches. */
4698 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004699 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004700 return 0;
4701 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004702
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004703 /* Create the "sf" field that contains a list of stringsafe fetches. */
4704 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004705 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004706 return 0;
4707 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004708
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004709 /* Create the "c" field that contains a list of converters. */
4710 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004711 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004712 return 0;
4713 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004714
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004715 /* Create the "sc" field that contains a list of stringsafe converters. */
4716 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004717 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004718 return 0;
4719 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004720
Christopher Fauleta2097962019-07-15 16:25:33 +02004721 htx = htxbuf(&s->req.buf);
4722 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004723 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004724 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004725
Christopher Fauleta2097962019-07-15 16:25:33 +02004726 /* Stores the request method. */
4727 lua_pushstring(L, "method");
4728 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4729 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004730
Christopher Fauleta2097962019-07-15 16:25:33 +02004731 /* Stores the http version. */
4732 lua_pushstring(L, "version");
4733 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4734 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004735
Christopher Fauleta2097962019-07-15 16:25:33 +02004736 /* creates an array of headers. hlua_http_get_headers() crates and push
4737 * the array on the top of the stack.
4738 */
4739 lua_pushstring(L, "headers");
4740 htxn.s = s;
4741 htxn.p = px;
4742 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004743 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004744 return 0;
4745 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004746
Amaury Denoyellec453f952021-07-06 11:40:12 +02004747 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4748 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004749 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004750 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004751
Christopher Fauleta2097962019-07-15 16:25:33 +02004752 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004753 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004754 q = p;
4755 while (q < end && *q != '?')
4756 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004757
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004758 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004759 lua_pushstring(L, "path");
4760 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004761 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004762
Christopher Fauleta2097962019-07-15 16:25:33 +02004763 /* Stores the query string. */
4764 lua_pushstring(L, "qs");
4765 if (*q == '?')
4766 q++;
4767 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004768 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004769 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004770
Christopher Fauleta2097962019-07-15 16:25:33 +02004771 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4772 struct htx_blk *blk = htx_get_blk(htx, pos);
4773 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004774
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004775 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004776 break;
4777 if (type == HTX_BLK_DATA)
4778 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004779 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004780 if (htx->extra != ULLONG_MAX)
4781 len += htx->extra;
4782
4783 /* Stores the request path. */
4784 lua_pushstring(L, "length");
4785 lua_pushinteger(L, len);
4786 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004787
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004788 /* Create an empty array of HTTP request headers. */
4789 lua_pushstring(L, "response");
4790 lua_newtable(L);
4791 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004792
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004793 /* Pop a class stream metatable and affect it to the table. */
4794 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4795 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004796
4797 return 1;
4798}
4799
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004800__LJMP static int hlua_applet_http_set_var(lua_State *L)
4801{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004802 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004803 struct stream *s;
4804 const char *name;
4805 size_t len;
4806 struct sample smp;
4807
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004808 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4809 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004810
4811 /* It is useles to retrieve the stream, but this function
4812 * runs only in a stream context.
4813 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004814 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004815 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004816 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004817
4818 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004819 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004820 hlua_lua2smp(L, 3, &smp);
4821
4822 /* Store the sample in a variable. */
4823 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004824
4825 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4826 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4827 else
4828 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4829
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004830 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004831}
4832
4833__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4834{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004835 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004836 struct stream *s;
4837 const char *name;
4838 size_t len;
4839 struct sample smp;
4840
4841 MAY_LJMP(check_args(L, 2, "unset_var"));
4842
4843 /* It is useles to retrieve the stream, but this function
4844 * runs only in a stream context.
4845 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004846 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004847 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004848 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004849
4850 /* Unset the variable. */
4851 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004852 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4853 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004854}
4855
4856__LJMP static int hlua_applet_http_get_var(lua_State *L)
4857{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004858 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004859 struct stream *s;
4860 const char *name;
4861 size_t len;
4862 struct sample smp;
4863
4864 MAY_LJMP(check_args(L, 2, "get_var"));
4865
4866 /* It is useles to retrieve the stream, but this function
4867 * runs only in a stream context.
4868 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004869 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004870 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004871 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004872
4873 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004874 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004875 lua_pushnil(L);
4876 return 1;
4877 }
4878
4879 return hlua_smp2lua(L, &smp);
4880}
4881
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004882__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4883{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004884 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4885 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004886 struct hlua *hlua;
4887
4888 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004889 if (!s->hlua)
4890 return 0;
4891 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004892
4893 MAY_LJMP(check_args(L, 2, "set_priv"));
4894
4895 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004896 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004897
4898 /* Get and store new value. */
4899 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4900 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4901
4902 return 0;
4903}
4904
4905__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4906{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004907 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4908 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004909 struct hlua *hlua;
4910
4911 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004912 if (!s->hlua) {
4913 lua_pushnil(L);
4914 return 1;
4915 }
4916 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004917
4918 /* Push configuration index in the stack. */
4919 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4920
4921 return 1;
4922}
4923
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004924/* If expected data not yet available, it returns a yield. This function
4925 * consumes the data in the buffer. It returns a string containing the
4926 * data. This string can be empty.
4927 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004928__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004929{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004930 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4931 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004932 struct channel *req = si_oc(si);
4933 struct htx *htx;
4934 struct htx_blk *blk;
4935 size_t count;
4936 int stop = 0;
4937
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004938 htx = htx_from_buf(&req->buf);
4939 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004940 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004941
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004942 while (count && !stop && blk) {
4943 enum htx_blk_type type = htx_get_blk_type(blk);
4944 uint32_t sz = htx_get_blksz(blk);
4945 struct ist v;
4946 uint32_t vlen;
4947 char *nl;
4948
4949 vlen = sz;
4950 if (vlen > count) {
4951 if (type != HTX_BLK_DATA)
4952 break;
4953 vlen = count;
4954 }
4955
4956 switch (type) {
4957 case HTX_BLK_UNUSED:
4958 break;
4959
4960 case HTX_BLK_DATA:
4961 v = htx_get_blk_value(htx, blk);
4962 v.len = vlen;
4963 nl = istchr(v, '\n');
4964 if (nl != NULL) {
4965 stop = 1;
4966 vlen = nl - v.ptr + 1;
4967 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004968 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004969 break;
4970
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004971 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004972 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004973 stop = 1;
4974 break;
4975
4976 default:
4977 break;
4978 }
4979
4980 co_set_data(req, co_data(req) - vlen);
4981 count -= vlen;
4982 if (sz == vlen)
4983 blk = htx_remove_blk(htx, blk);
4984 else {
4985 htx_cut_data_blk(htx, blk, vlen);
4986 break;
4987 }
4988 }
4989
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004990 /* The message was fully consumed and no more data are expected
4991 * (EOM flag set).
4992 */
4993 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
4994 stop = 1;
4995
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004996 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004997 if (!stop) {
4998 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004999 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005000 }
5001
5002 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005003 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005004 return 1;
5005}
5006
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005007
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005008/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005009__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005010{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005011 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005012
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005013 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005014 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005015
Christopher Fauleta2097962019-07-15 16:25:33 +02005016 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005017}
5018
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005019/* If expected data not yet available, it returns a yield. This function
5020 * consumes the data in the buffer. It returns a string containing the
5021 * data. This string can be empty.
5022 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005023__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005024{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005025 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5026 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005027 struct channel *req = si_oc(si);
5028 struct htx *htx;
5029 struct htx_blk *blk;
5030 size_t count;
5031 int len;
5032
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005033 htx = htx_from_buf(&req->buf);
5034 len = MAY_LJMP(luaL_checkinteger(L, 2));
5035 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005036 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005037 while (count && len && blk) {
5038 enum htx_blk_type type = htx_get_blk_type(blk);
5039 uint32_t sz = htx_get_blksz(blk);
5040 struct ist v;
5041 uint32_t vlen;
5042
5043 vlen = sz;
5044 if (len > 0 && vlen > len)
5045 vlen = len;
5046 if (vlen > count) {
5047 if (type != HTX_BLK_DATA)
5048 break;
5049 vlen = count;
5050 }
5051
5052 switch (type) {
5053 case HTX_BLK_UNUSED:
5054 break;
5055
5056 case HTX_BLK_DATA:
5057 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005058 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005059 break;
5060
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005061 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005062 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005063 len = 0;
5064 break;
5065
5066 default:
5067 break;
5068 }
5069
5070 co_set_data(req, co_data(req) - vlen);
5071 count -= vlen;
5072 if (len > 0)
5073 len -= vlen;
5074 if (sz == vlen)
5075 blk = htx_remove_blk(htx, blk);
5076 else {
5077 htx_cut_data_blk(htx, blk, vlen);
5078 break;
5079 }
5080 }
5081
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005082 /* The message was fully consumed and no more data are expected
5083 * (EOM flag set).
5084 */
5085 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5086 len = 0;
5087
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005088 htx_to_buf(htx, &req->buf);
5089
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005090 /* If we are no other data available, yield waiting for new data. */
5091 if (len) {
5092 if (len > 0) {
5093 lua_pushinteger(L, len);
5094 lua_replace(L, 2);
5095 }
5096 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005097 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005098 }
5099
5100 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005101 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005102 return 1;
5103}
5104
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005105/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005106__LJMP static int hlua_applet_http_recv(lua_State *L)
5107{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005108 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005109 int len = -1;
5110
5111 /* Check arguments. */
5112 if (lua_gettop(L) > 2)
5113 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5114 if (lua_gettop(L) >= 2) {
5115 len = MAY_LJMP(luaL_checkinteger(L, 2));
5116 lua_pop(L, 1);
5117 }
5118
Christopher Fauleta2097962019-07-15 16:25:33 +02005119 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005120
Christopher Fauleta2097962019-07-15 16:25:33 +02005121 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005122 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005123
Christopher Fauleta2097962019-07-15 16:25:33 +02005124 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005125}
5126
5127/* Append data in the output side of the buffer. This data is immediately
5128 * sent. The function returns the amount of data written. If the buffer
5129 * cannot contain the data, the function yields. The function returns -1
5130 * if the channel is closed.
5131 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005132__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005133{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005134 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5135 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005136 struct channel *res = si_ic(si);
5137 struct htx *htx = htx_from_buf(&res->buf);
5138 const char *data;
5139 size_t len;
5140 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5141 int max;
5142
Christopher Faulet9060fc02019-07-03 11:39:30 +02005143 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005144 if (!max)
5145 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005146
5147 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5148
5149 /* Get the max amount of data which can write as input in the channel. */
5150 if (max > (len - l))
5151 max = len - l;
5152
5153 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005154 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005155 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005156
5157 /* update counters. */
5158 l += max;
5159 lua_pop(L, 1);
5160 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005161
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005162 /* If some data is not send, declares the situation to the
5163 * applet, and returns a yield.
5164 */
5165 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005166 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005167 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005168 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005169 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005170 }
5171
Christopher Fauleta2097962019-07-15 16:25:33 +02005172 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005173 return 1;
5174}
5175
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005176/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005177 * yield the LUA process, and resume it without checking the
5178 * input arguments.
5179 */
5180__LJMP static int hlua_applet_http_send(lua_State *L)
5181{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005182 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005183
5184 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005185 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005186 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5187 WILL_LJMP(lua_error(L));
5188 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005189
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005190 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005191 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005192
Christopher Fauleta2097962019-07-15 16:25:33 +02005193 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005194}
5195
5196__LJMP static int hlua_applet_http_addheader(lua_State *L)
5197{
5198 const char *name;
5199 int ret;
5200
5201 MAY_LJMP(hlua_checkapplet_http(L, 1));
5202 name = MAY_LJMP(luaL_checkstring(L, 2));
5203 MAY_LJMP(luaL_checkstring(L, 3));
5204
5205 /* Push in the stack the "response" entry. */
5206 ret = lua_getfield(L, 1, "response");
5207 if (ret != LUA_TTABLE) {
5208 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5209 "is expected as an array. %s found", lua_typename(L, ret));
5210 WILL_LJMP(lua_error(L));
5211 }
5212
5213 /* check if the header is already registered if it is not
5214 * the case, register it.
5215 */
5216 ret = lua_getfield(L, -1, name);
5217 if (ret == LUA_TNIL) {
5218
5219 /* Entry not found. */
5220 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5221
5222 /* Insert the new header name in the array in the top of the stack.
5223 * It left the new array in the top of the stack.
5224 */
5225 lua_newtable(L);
5226 lua_pushvalue(L, 2);
5227 lua_pushvalue(L, -2);
5228 lua_settable(L, -4);
5229
5230 } else if (ret != LUA_TTABLE) {
5231
5232 /* corruption error. */
5233 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5234 "is expected as an array. %s found", name, lua_typename(L, ret));
5235 WILL_LJMP(lua_error(L));
5236 }
5237
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005238 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005239 * the header value as new entry.
5240 */
5241 lua_pushvalue(L, 3);
5242 ret = lua_rawlen(L, -2);
5243 lua_rawseti(L, -2, ret + 1);
5244 lua_pushboolean(L, 1);
5245 return 1;
5246}
5247
5248__LJMP static int hlua_applet_http_status(lua_State *L)
5249{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005250 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005251 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005252 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005253
5254 if (status < 100 || status > 599) {
5255 lua_pushboolean(L, 0);
5256 return 1;
5257 }
5258
Willy Tarreau7e702d12021-04-28 17:59:21 +02005259 luactx->appctx->ctx.hlua_apphttp.status = status;
5260 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005261 lua_pushboolean(L, 1);
5262 return 1;
5263}
5264
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005265
Christopher Fauleta2097962019-07-15 16:25:33 +02005266__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005267{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005268 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5269 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005270 struct channel *res = si_ic(si);
5271 struct htx *htx;
5272 struct htx_sl *sl;
5273 struct h1m h1m;
5274 const char *status, *reason;
5275 const char *name, *value;
5276 size_t nlen, vlen;
5277 unsigned int flags;
5278
5279 /* Send the message at once. */
5280 htx = htx_from_buf(&res->buf);
5281 h1m_init_res(&h1m);
5282
5283 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005284 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5285 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005286 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005287 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5288 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005289 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5290 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5291 }
5292 else {
5293 flags = HTX_SL_F_IS_RESP;
5294 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5295 }
5296 if (!sl) {
5297 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005298 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005299 WILL_LJMP(lua_error(L));
5300 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005301 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005302
5303 /* Get the array associated to the field "response" in the object AppletHTTP. */
5304 lua_pushvalue(L, 0);
5305 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5306 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\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 }
5310
5311 /* Browse the list of headers. */
5312 lua_pushnil(L);
5313 while(lua_next(L, -2) != 0) {
5314 /* We expect a string as -2. */
5315 if (lua_type(L, -2) != LUA_TSTRING) {
5316 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005317 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005318 lua_typename(L, lua_type(L, -2)));
5319 WILL_LJMP(lua_error(L));
5320 }
5321 name = lua_tolstring(L, -2, &nlen);
5322
5323 /* We expect an array as -1. */
5324 if (lua_type(L, -1) != LUA_TTABLE) {
5325 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 +02005326 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005327 name,
5328 lua_typename(L, lua_type(L, -1)));
5329 WILL_LJMP(lua_error(L));
5330 }
5331
5332 /* Browse the table who is on the top of the stack. */
5333 lua_pushnil(L);
5334 while(lua_next(L, -2) != 0) {
5335 int id;
5336
5337 /* We expect a number as -2. */
5338 if (lua_type(L, -2) != LUA_TNUMBER) {
5339 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 +02005340 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005341 name,
5342 lua_typename(L, lua_type(L, -2)));
5343 WILL_LJMP(lua_error(L));
5344 }
5345 id = lua_tointeger(L, -2);
5346
5347 /* We expect a string as -2. */
5348 if (lua_type(L, -1) != LUA_TSTRING) {
5349 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 +02005350 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005351 name, id,
5352 lua_typename(L, lua_type(L, -1)));
5353 WILL_LJMP(lua_error(L));
5354 }
5355 value = lua_tolstring(L, -1, &vlen);
5356
5357 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005358 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5359 int ret;
5360
5361 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5362 if (ret < 0) {
5363 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5364 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5365 name);
5366 WILL_LJMP(lua_error(L));
5367 }
5368 else if (ret == 0)
5369 goto next; /* Skip it */
5370 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005371 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5372 struct ist v = ist2(value, vlen);
5373 int ret;
5374
5375 ret = h1_parse_cont_len_header(&h1m, &v);
5376 if (ret < 0) {
5377 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005378 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005379 name);
5380 WILL_LJMP(lua_error(L));
5381 }
5382 else if (ret == 0)
5383 goto next; /* Skip it */
5384 }
5385
5386 /* Add a new header */
5387 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5388 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005389 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005390 name);
5391 WILL_LJMP(lua_error(L));
5392 }
5393 next:
5394 /* Remove the array from the stack, and get next element with a remaining string. */
5395 lua_pop(L, 1);
5396 }
5397
5398 /* Remove the array from the stack, and get next element with a remaining string. */
5399 lua_pop(L, 1);
5400 }
5401
5402 if (h1m.flags & H1_MF_CHNK)
5403 h1m.flags &= ~H1_MF_CLEN;
5404 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5405 h1m.flags |= H1_MF_XFER_LEN;
5406
5407 /* Uset HTX start-line flags */
5408 if (h1m.flags & H1_MF_XFER_ENC)
5409 flags |= HTX_SL_F_XFER_ENC;
5410 if (h1m.flags & H1_MF_XFER_LEN) {
5411 flags |= HTX_SL_F_XFER_LEN;
5412 if (h1m.flags & H1_MF_CHNK)
5413 flags |= HTX_SL_F_CHNK;
5414 else if (h1m.flags & H1_MF_CLEN)
5415 flags |= HTX_SL_F_CLEN;
5416 if (h1m.body_len == 0)
5417 flags |= HTX_SL_F_BODYLESS;
5418 }
5419 sl->flags |= flags;
5420
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005421 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005422 * and the status code implies the presence of a message body, we must
5423 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005424 * for the keepalive compliance. If the applet announces a transfer-encoding
5425 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005426 */
5427 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005428 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5429 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5430 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005431 /* Add a new header */
5432 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5433 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5434 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005435 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005436 WILL_LJMP(lua_error(L));
5437 }
5438 }
5439
5440 /* Finalize headers. */
5441 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5442 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005443 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005444 WILL_LJMP(lua_error(L));
5445 }
5446
5447 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5448 b_reset(&res->buf);
5449 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5450 WILL_LJMP(lua_error(L));
5451 }
5452
5453 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005454 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005455
5456 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005457 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005458 return 0;
5459
5460}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005461/* We will build the status line and the headers of the HTTP response.
5462 * We will try send at once if its not possible, we give back the hand
5463 * waiting for more room.
5464 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005465__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005466{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005467 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5468 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005469 struct channel *res = si_ic(si);
5470
5471 if (co_data(res)) {
5472 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005473 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005474 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005475 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005476}
5477
5478
Christopher Fauleta2097962019-07-15 16:25:33 +02005479__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005480{
Christopher Fauleta2097962019-07-15 16:25:33 +02005481 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005482}
5483
Christopher Fauleta2097962019-07-15 16:25:33 +02005484/*
5485 *
5486 *
5487 * Class HTTP
5488 *
5489 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005490 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005491
5492/* Returns a struct hlua_txn if the stack entry "ud" is
5493 * a class stream, otherwise it throws an error.
5494 */
5495__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005496{
Christopher Fauleta2097962019-07-15 16:25:33 +02005497 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5498}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005499
Christopher Fauleta2097962019-07-15 16:25:33 +02005500/* This function creates and push in the stack a HTTP object
5501 * according with a current TXN.
5502 */
5503static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5504{
5505 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005506
Christopher Fauleta2097962019-07-15 16:25:33 +02005507 /* Check stack size. */
5508 if (!lua_checkstack(L, 3))
5509 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005510
Christopher Fauleta2097962019-07-15 16:25:33 +02005511 /* Create the object: obj[0] = userdata.
5512 * Note that the base of the Converters object is the
5513 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005514 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005515 lua_newtable(L);
5516 htxn = lua_newuserdata(L, sizeof(*htxn));
5517 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005518
5519 htxn->s = txn->s;
5520 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005521 htxn->dir = txn->dir;
5522 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005523
5524 /* Pop a class stream metatable and affect it to the table. */
5525 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5526 lua_setmetatable(L, -2);
5527
5528 return 1;
5529}
5530
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005531/* This function creates and returns an array containing the status-line
5532 * elements. This function does not fails.
5533 */
5534__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5535{
5536 /* Create the table. */
5537 lua_newtable(L);
5538
5539 if (sl->flags & HTX_SL_F_IS_RESP) {
5540 lua_pushstring(L, "version");
5541 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5542 lua_settable(L, -3);
5543 lua_pushstring(L, "code");
5544 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5545 lua_settable(L, -3);
5546 lua_pushstring(L, "reason");
5547 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5548 lua_settable(L, -3);
5549 }
5550 else {
5551 lua_pushstring(L, "method");
5552 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5553 lua_settable(L, -3);
5554 lua_pushstring(L, "uri");
5555 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5556 lua_settable(L, -3);
5557 lua_pushstring(L, "version");
5558 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5559 lua_settable(L, -3);
5560 }
5561 return 1;
5562}
5563
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005564/* This function creates ans returns an array of HTTP headers.
5565 * This function does not fails. It is used as wrapper with the
5566 * 2 following functions.
5567 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005568__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005569{
Christopher Fauleta2097962019-07-15 16:25:33 +02005570 struct htx *htx;
5571 int32_t pos;
5572
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005573 /* Create the table. */
5574 lua_newtable(L);
5575
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005576
Christopher Fauleta2097962019-07-15 16:25:33 +02005577 htx = htxbuf(&msg->chn->buf);
5578 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5579 struct htx_blk *blk = htx_get_blk(htx, pos);
5580 enum htx_blk_type type = htx_get_blk_type(blk);
5581 struct ist n, v;
5582 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005583
Christopher Fauleta2097962019-07-15 16:25:33 +02005584 if (type == HTX_BLK_HDR) {
5585 n = htx_get_blk_name(htx,blk);
5586 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005587 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005588 else if (type == HTX_BLK_EOH)
5589 break;
5590 else
5591 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005592
Christopher Fauleta2097962019-07-15 16:25:33 +02005593 /* Check for existing entry:
5594 * assume that the table is on the top of the stack, and
5595 * push the key in the stack, the function lua_gettable()
5596 * perform the lookup.
5597 */
5598 lua_pushlstring(L, n.ptr, n.len);
5599 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005600
Christopher Fauleta2097962019-07-15 16:25:33 +02005601 switch (lua_type(L, -1)) {
5602 case LUA_TNIL:
5603 /* Table not found, create it. */
5604 lua_pop(L, 1); /* remove the nil value. */
5605 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5606 lua_newtable(L); /* create and push empty table. */
5607 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5608 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5609 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005610 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005611
Christopher Fauleta2097962019-07-15 16:25:33 +02005612 case LUA_TTABLE:
5613 /* Entry found: push the value in the table. */
5614 len = lua_rawlen(L, -1);
5615 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5616 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5617 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5618 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005619
Christopher Fauleta2097962019-07-15 16:25:33 +02005620 default:
5621 /* Other cases are errors. */
5622 hlua_pusherror(L, "internal error during the parsing of headers.");
5623 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005624 }
5625 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005626 return 1;
5627}
5628
5629__LJMP static int hlua_http_req_get_headers(lua_State *L)
5630{
5631 struct hlua_txn *htxn;
5632
5633 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5634 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5635
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005636 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005637 WILL_LJMP(lua_error(L));
5638
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005639 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005640}
5641
5642__LJMP static int hlua_http_res_get_headers(lua_State *L)
5643{
5644 struct hlua_txn *htxn;
5645
5646 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5647 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5648
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005649 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005650 WILL_LJMP(lua_error(L));
5651
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005652 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005653}
5654
5655/* This function replace full header, or just a value in
5656 * the request or in the response. It is a wrapper fir the
5657 * 4 following functions.
5658 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005659__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005660{
5661 size_t name_len;
5662 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5663 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5664 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005665 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005666 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005667
Dragan Dosen26743032019-04-30 15:54:36 +02005668 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005669 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5670
Christopher Fauleta2097962019-07-15 16:25:33 +02005671 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005672 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005673 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005674 return 0;
5675}
5676
5677__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5678{
5679 struct hlua_txn *htxn;
5680
5681 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5682 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5683
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005684 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005685 WILL_LJMP(lua_error(L));
5686
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005687 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005688}
5689
5690__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5691{
5692 struct hlua_txn *htxn;
5693
5694 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5695 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5696
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005697 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005698 WILL_LJMP(lua_error(L));
5699
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005700 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005701}
5702
5703__LJMP static int hlua_http_req_rep_val(lua_State *L)
5704{
5705 struct hlua_txn *htxn;
5706
5707 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5708 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5709
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005710 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005711 WILL_LJMP(lua_error(L));
5712
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005713 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005714}
5715
5716__LJMP static int hlua_http_res_rep_val(lua_State *L)
5717{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005718 struct hlua_txn *htxn;
5719
5720 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5721 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5722
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005723 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005724 WILL_LJMP(lua_error(L));
5725
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005726 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005727}
5728
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005729/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005730 * It is a wrapper for the 2 following functions.
5731 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005732__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005733{
5734 size_t len;
5735 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005736 struct htx *htx = htxbuf(&msg->chn->buf);
5737 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005738
Christopher Fauleta2097962019-07-15 16:25:33 +02005739 ctx.blk = NULL;
5740 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5741 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005742 return 0;
5743}
5744
5745__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5746{
5747 struct hlua_txn *htxn;
5748
5749 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5750 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5751
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005752 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005753 WILL_LJMP(lua_error(L));
5754
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005755 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005756}
5757
5758__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5759{
5760 struct hlua_txn *htxn;
5761
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005762 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005763 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5764
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005765 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005766 WILL_LJMP(lua_error(L));
5767
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005768 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005769}
5770
5771/* This function adds an header. It is a wrapper used by
5772 * the 2 following functions.
5773 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005774__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005775{
5776 size_t name_len;
5777 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5778 size_t value_len;
5779 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005780 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005781
Christopher Fauleta2097962019-07-15 16:25:33 +02005782 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5783 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005784 return 0;
5785}
5786
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005787__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5788{
5789 struct hlua_txn *htxn;
5790
5791 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5792 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5793
5794 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5795 WILL_LJMP(lua_error(L));
5796
5797 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5798}
5799
5800__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5801{
5802 struct hlua_txn *htxn;
5803
5804 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5805 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5806
5807 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5808 WILL_LJMP(lua_error(L));
5809
5810 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5811}
5812
5813static int hlua_http_req_set_hdr(lua_State *L)
5814{
5815 struct hlua_txn *htxn;
5816
5817 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5818 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5819
5820 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5821 WILL_LJMP(lua_error(L));
5822
5823 hlua_http_del_hdr(L, &htxn->s->txn->req);
5824 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5825}
5826
5827static int hlua_http_res_set_hdr(lua_State *L)
5828{
5829 struct hlua_txn *htxn;
5830
5831 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5832 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5833
5834 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5835 WILL_LJMP(lua_error(L));
5836
5837 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5838 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5839}
5840
5841/* This function set the method. */
5842static int hlua_http_req_set_meth(lua_State *L)
5843{
5844 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5845 size_t name_len;
5846 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5847
5848 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5849 WILL_LJMP(lua_error(L));
5850
5851 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5852 return 1;
5853}
5854
5855/* This function set the method. */
5856static int hlua_http_req_set_path(lua_State *L)
5857{
5858 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5859 size_t name_len;
5860 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5861
5862 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5863 WILL_LJMP(lua_error(L));
5864
5865 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5866 return 1;
5867}
5868
5869/* This function set the query-string. */
5870static int hlua_http_req_set_query(lua_State *L)
5871{
5872 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5873 size_t name_len;
5874 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5875
5876 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5877 WILL_LJMP(lua_error(L));
5878
5879 /* Check length. */
5880 if (name_len > trash.size - 1) {
5881 lua_pushboolean(L, 0);
5882 return 1;
5883 }
5884
5885 /* Add the mark question as prefix. */
5886 chunk_reset(&trash);
5887 trash.area[trash.data++] = '?';
5888 memcpy(trash.area + trash.data, name, name_len);
5889 trash.data += name_len;
5890
5891 lua_pushboolean(L,
5892 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5893 return 1;
5894}
5895
5896/* This function set the uri. */
5897static int hlua_http_req_set_uri(lua_State *L)
5898{
5899 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5900 size_t name_len;
5901 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5902
5903 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5904 WILL_LJMP(lua_error(L));
5905
5906 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5907 return 1;
5908}
5909
5910/* This function set the response code & optionally reason. */
5911static int hlua_http_res_set_status(lua_State *L)
5912{
5913 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5914 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5915 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5916 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5917
5918 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5919 WILL_LJMP(lua_error(L));
5920
5921 http_res_set_status(code, reason, htxn->s);
5922 return 0;
5923}
5924
5925/*
5926 *
5927 *
5928 * Class HTTPMessage
5929 *
5930 *
5931 */
5932
5933/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5934 * otherwise it throws an error.
5935 */
5936__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5937{
5938 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5939}
5940
5941/* Creates and pushes on the stack a HTTP object according with a current TXN.
5942 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005943static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005944{
5945 /* Check stack size. */
5946 if (!lua_checkstack(L, 3))
5947 return 0;
5948
5949 lua_newtable(L);
5950 lua_pushlightuserdata(L, msg);
5951 lua_rawseti(L, -2, 0);
5952
5953 /* Create the "channel" field that contains the request channel object. */
5954 lua_pushstring(L, "channel");
5955 if (!hlua_channel_new(L, msg->chn))
5956 return 0;
5957 lua_rawset(L, -3);
5958
5959 /* Pop a class stream metatable and affect it to the table. */
5960 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5961 lua_setmetatable(L, -2);
5962
5963 return 1;
5964}
5965
5966/* Helper function returning a filter attached to the HTTP message at the
5967 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05005968 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005969 * filled with output and input length respectively.
5970 */
5971static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5972{
5973 struct channel *chn = msg->chn;
5974 struct htx *htx = htxbuf(&chn->buf);
5975 struct filter *filter = NULL;
5976
5977 *offset = co_data(msg->chn);
5978 *len = htx->data - co_data(msg->chn);
5979
5980 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5981 filter = lua_touserdata (L, -1);
5982 if (msg->msg_state >= HTTP_MSG_DATA) {
5983 struct hlua_flt_ctx *flt_ctx = filter->ctx;
5984
5985 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
5986 *len = flt_ctx->cur_len[CHN_IDX(chn)];
5987 }
5988 }
5989
5990 lua_pop(L, 1);
5991 return filter;
5992}
5993
5994/* Returns true if the channel attached to the HTTP message is the response
5995 * channel.
5996 */
5997__LJMP static int hlua_http_msg_is_resp(lua_State *L)
5998{
5999 struct http_msg *msg;
6000
6001 MAY_LJMP(check_args(L, 1, "is_resp"));
6002 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6003
6004 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6005 return 1;
6006}
6007
6008/* Returns an array containing the elements status-line of the HTTP message. It relies
6009 * on hlua_http_get_stline().
6010 */
6011__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6012{
6013 struct http_msg *msg;
6014 struct htx *htx;
6015 struct htx_sl *sl;
6016
6017 MAY_LJMP(check_args(L, 1, "get_stline"));
6018 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6019
6020 if (msg->msg_state > HTTP_MSG_BODY)
6021 WILL_LJMP(lua_error(L));
6022
6023 htx = htxbuf(&msg->chn->buf);
6024 sl = http_get_stline(htx);
6025 if (!sl)
6026 return 0;
6027 return hlua_http_get_stline(L, sl);
6028}
6029
6030/* Returns an array containing all headers of the HTTP message. it relies on
6031 * hlua_http_get_headers().
6032 */
6033__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6034{
6035 struct http_msg *msg;
6036
6037 MAY_LJMP(check_args(L, 1, "get_headers"));
6038 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6039
6040 if (msg->msg_state > HTTP_MSG_BODY)
6041 WILL_LJMP(lua_error(L));
6042
6043 return hlua_http_get_headers(L, msg);
6044}
6045
6046/* Deletes all occurrences of an header in the HTTP message matching on its
6047 * name. It relies on hlua_http_del_hdr().
6048 */
6049__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6050{
6051 struct http_msg *msg;
6052
6053 MAY_LJMP(check_args(L, 2, "del_header"));
6054 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6055
6056 if (msg->msg_state > HTTP_MSG_BODY)
6057 WILL_LJMP(lua_error(L));
6058
6059 return hlua_http_del_hdr(L, msg);
6060}
6061
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006062/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006063 * message given its name against a regex and replaces it if it matches. It
6064 * relies on hlua_http_rep_hdr().
6065 */
6066__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6067{
6068 struct http_msg *msg;
6069
6070 MAY_LJMP(check_args(L, 4, "rep_header"));
6071 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6072
6073 if (msg->msg_state > HTTP_MSG_BODY)
6074 WILL_LJMP(lua_error(L));
6075
6076 return hlua_http_rep_hdr(L, msg, 1);
6077}
6078
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006079/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006080 * message given its name against a regex and replaces it if it matches. It
6081 * relies on hlua_http_rep_hdr().
6082 */
6083__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6084{
6085 struct http_msg *msg;
6086
6087 MAY_LJMP(check_args(L, 4, "rep_value"));
6088 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6089
6090 if (msg->msg_state > HTTP_MSG_BODY)
6091 WILL_LJMP(lua_error(L));
6092
6093 return hlua_http_rep_hdr(L, msg, 0);
6094}
6095
6096/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6097__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6098{
6099 struct http_msg *msg;
6100
6101 MAY_LJMP(check_args(L, 3, "add_header"));
6102 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6103
6104 if (msg->msg_state > HTTP_MSG_BODY)
6105 WILL_LJMP(lua_error(L));
6106
6107 return hlua_http_add_hdr(L, msg);
6108}
6109
6110/* Add an header in the HTTP message removing existing headers with the same
6111 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6112 */
6113__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6114{
6115 struct http_msg *msg;
6116
6117 MAY_LJMP(check_args(L, 3, "set_header"));
6118 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6119
6120 if (msg->msg_state > HTTP_MSG_BODY)
6121 WILL_LJMP(lua_error(L));
6122
6123 hlua_http_del_hdr(L, msg);
6124 return hlua_http_add_hdr(L, msg);
6125}
6126
6127/* Rewrites the request method. It relies on http_req_replace_stline(). */
6128__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6129{
6130 struct stream *s;
6131 struct http_msg *msg;
6132 const char *name;
6133 size_t name_len;
6134
6135 MAY_LJMP(check_args(L, 2, "set_method"));
6136 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6137 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6138
6139 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6140 WILL_LJMP(lua_error(L));
6141
6142 s = chn_strm(msg->chn);
6143 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6144 return 1;
6145}
6146
6147/* Rewrites the request path. It relies on http_req_replace_stline(). */
6148__LJMP static int hlua_http_msg_set_path(lua_State *L)
6149{
6150 struct stream *s;
6151 struct http_msg *msg;
6152 const char *name;
6153 size_t name_len;
6154
6155 MAY_LJMP(check_args(L, 2, "set_path"));
6156 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6157 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6158
6159 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6160 WILL_LJMP(lua_error(L));
6161
6162 s = chn_strm(msg->chn);
6163 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6164 return 1;
6165}
6166
6167/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6168__LJMP static int hlua_http_msg_set_query(lua_State *L)
6169{
6170 struct stream *s;
6171 struct http_msg *msg;
6172 const char *name;
6173 size_t name_len;
6174
6175 MAY_LJMP(check_args(L, 2, "set_query"));
6176 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6177 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6178
6179 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6180 WILL_LJMP(lua_error(L));
6181
6182 /* Check length. */
6183 if (name_len > trash.size - 1) {
6184 lua_pushboolean(L, 0);
6185 return 1;
6186 }
6187
6188 /* Add the mark question as prefix. */
6189 chunk_reset(&trash);
6190 trash.area[trash.data++] = '?';
6191 memcpy(trash.area + trash.data, name, name_len);
6192 trash.data += name_len;
6193
6194 s = chn_strm(msg->chn);
6195 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6196 return 1;
6197}
6198
6199/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6200__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6201{
6202 struct stream *s;
6203 struct http_msg *msg;
6204 const char *name;
6205 size_t name_len;
6206
6207 MAY_LJMP(check_args(L, 2, "set_uri"));
6208 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6209 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6210
6211 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6212 WILL_LJMP(lua_error(L));
6213
6214 s = chn_strm(msg->chn);
6215 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6216 return 1;
6217}
6218
6219/* Rewrites the response status code. It relies on http_res_set_status(). */
6220__LJMP static int hlua_http_msg_set_status(lua_State *L)
6221{
6222 struct http_msg *msg;
6223 unsigned int code;
6224 const char *reason;
6225 size_t reason_len;
6226
6227 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6228 code = MAY_LJMP(luaL_checkinteger(L, 2));
6229 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6230
6231 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6232 WILL_LJMP(lua_error(L));
6233
6234 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6235 return 1;
6236}
6237
6238/* Returns true if the HTTP message is full. */
6239__LJMP static int hlua_http_msg_is_full(lua_State *L)
6240{
6241 struct http_msg *msg;
6242
6243 MAY_LJMP(check_args(L, 1, "is_full"));
6244 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6245 lua_pushboolean(L, channel_full(msg->chn, 0));
6246 return 1;
6247}
6248
6249/* Returns true if the HTTP message may still receive data. */
6250__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6251{
6252 struct http_msg *msg;
6253 struct htx *htx;
6254
6255 MAY_LJMP(check_args(L, 1, "may_recv"));
6256 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6257 htx = htxbuf(&msg->chn->buf);
6258 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6259 return 1;
6260}
6261
6262/* Returns true if the HTTP message EOM was received */
6263__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6264{
6265 struct http_msg *msg;
6266 struct htx *htx;
6267
6268 MAY_LJMP(check_args(L, 1, "may_recv"));
6269 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6270 htx = htxbuf(&msg->chn->buf);
6271 lua_pushboolean(L, !htx_expect_more(htx));
6272 return 1;
6273}
6274
6275/* Returns the number of bytes available in the input side of the HTTP
6276 * message. This function never fails.
6277 */
6278__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6279{
6280 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006281 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006282
6283 MAY_LJMP(check_args(L, 1, "input"));
6284 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006285 hlua_http_msg_filter(L, 1, msg, &output, &input);
6286 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006287 return 1;
6288}
6289
6290/* Returns the number of bytes available in the output side of the HTTP
6291 * message. This function never fails.
6292 */
6293__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6294{
6295 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006296 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006297
6298 MAY_LJMP(check_args(L, 1, "output"));
6299 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006300 hlua_http_msg_filter(L, 1, msg, &output, &input);
6301 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006302 return 1;
6303}
6304
6305/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6306 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006307 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006308 * block. This function is called during the payload filtering, so the headers
6309 * are already scheduled for output (from the filter point of view).
6310 */
6311static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6312{
6313 struct htx *htx = htxbuf(&msg->chn->buf);
6314 struct htx_blk *blk;
6315 struct htx_ret htxret;
6316 luaL_Buffer b;
6317 int ret = 0;
6318
6319 luaL_buffinit(L, &b);
6320 htxret = htx_find_offset(htx, offset);
6321 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6322 enum htx_blk_type type = htx_get_blk_type(blk);
6323 struct ist v;
6324
6325 switch (type) {
6326 case HTX_BLK_UNUSED:
6327 break;
6328
6329 case HTX_BLK_DATA:
6330 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006331 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006332 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006333
6334 luaL_addlstring(&b, v.ptr, v.len);
6335 ret += v.len;
6336 break;
6337
6338 default:
vishnu0af4bd72021-10-24 06:46:24 +05306339 if (!ret)
6340 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006341 goto end;
6342 }
6343 offset = 0;
6344 }
6345
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006346end:
vishnu0af4bd72021-10-24 06:46:24 +05306347 if (!ret && (htx->flags & HTX_FL_EOM))
6348 goto no_data;
6349 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006350 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306351
6352 no_data:
6353 /* Remove the empty string and push nil on the stack */
6354 lua_pop(L, 1);
6355 lua_pushnil(L);
6356 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006357}
6358
6359/* Copies the string <str> to the HTTP message <msg> at the offset
6360 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006361 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006362 * the filter context.
6363 */
6364static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6365{
6366 struct htx *htx = htx_from_buf(&msg->chn->buf);
6367 struct htx_ret htxret;
6368 int /*max, */ret = 0;
6369
6370 /* Nothing to do, just return */
6371 if (unlikely(istlen(str) == 0))
6372 goto end;
6373
6374 if (istlen(str) > htx_free_data_space(htx)) {
6375 ret = -1;
6376 goto end;
6377 }
6378
6379 htxret = htx_find_offset(htx, offset);
6380 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6381 if (!htx_add_last_data(htx, str))
6382 goto end;
6383 }
6384 else {
6385 struct ist v = htx_get_blk_value(htx, htxret.blk);
6386 v.ptr += htxret.ret;
6387 v.len = 0;
6388 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6389 goto end;
6390 }
6391 ret = str.len;
6392 if (ret) {
6393 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6394 flt_update_offsets(filter, msg->chn, ret);
6395 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6396 }
6397
6398 end:
6399 htx_to_buf(htx, &msg->chn->buf);
6400 return ret;
6401}
6402
6403/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6404 * position <offset>. It stops on the first non-DATA HTX block. This function is
6405 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006406 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006407 * update the filter context.
6408 */
6409static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6410{
6411 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6412 struct htx *htx = htx_from_buf(&msg->chn->buf);
6413 struct htx_blk *blk;
6414 struct htx_ret htxret;
6415 size_t ret = 0;
6416
6417 /* Be sure <len> is always the amount of DATA to remove */
6418 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6419 htx_truncate(htx, offset);
6420 ret = len;
6421 goto end;
6422 }
6423
6424 htxret = htx_find_offset(htx, offset);
6425 blk = htxret.blk;
6426 if (htxret.ret) {
6427 struct ist v;
6428
6429 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6430 goto end;
6431 v = htx_get_blk_value(htx, blk);
6432 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006433 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006434 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006435 len -= v.len;
6436 ret += v.len;
6437 }
6438
6439
6440 while (blk && len) {
6441 enum htx_blk_type type = htx_get_blk_type(blk);
6442 uint32_t sz = htx_get_blksz(blk);
6443
6444 switch (type) {
6445 case HTX_BLK_UNUSED:
6446 break;
6447
6448 case HTX_BLK_DATA:
6449 if (len < sz) {
6450 htx_cut_data_blk(htx, blk, len);
6451 ret += len;
6452 goto end;
6453 }
6454 break;
6455
6456 default:
6457 goto end;
6458 }
6459
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006460 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006461 len -= sz;
6462 ret += sz;
6463 blk = htx_remove_blk(htx, blk);
6464 }
6465
6466end:
6467 flt_update_offsets(filter, msg->chn, -ret);
6468 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6469 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6470 * to loose the EOM flag if the message is empty.
6471 */
6472}
6473
6474/* Copies input data found in an HTTP message. Unlike the channel function used
6475 * to duplicate raw data, this one can only be called inside a filter, from
6476 * http_payload callback. So it cannot yield. An exception is returned if it is
6477 * called from another callback. If nothing was copied, a nil value is pushed on
6478 * the stack.
6479 */
6480__LJMP static int hlua_http_msg_get_body(lua_State *L)
6481{
6482 struct http_msg *msg;
6483 struct filter *filter;
6484 size_t output, input;
6485 int offset, len;
6486
6487 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6488 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6489 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6490
6491 if (msg->msg_state < HTTP_MSG_DATA)
6492 WILL_LJMP(lua_error(L));
6493
6494 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6495 if (!filter || !hlua_filter_from_payload(filter))
6496 WILL_LJMP(lua_error(L));
6497
6498 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6499 lua_pushnil(L);
6500 return 1;
6501 }
6502
6503 offset = output;
6504 if (lua_gettop(L) > 1) {
6505 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6506 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006507 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006508 offset += output;
6509 if (offset < output || offset > input + output) {
6510 lua_pushfstring(L, "offset out of range.");
6511 WILL_LJMP(lua_error(L));
6512 }
6513 }
6514 len = output + input - offset;
6515 if (lua_gettop(L) == 3) {
6516 len = MAY_LJMP(luaL_checkinteger(L, 3));
6517 if (!len)
6518 goto dup;
6519 if (len == -1)
6520 len = global.tune.bufsize;
6521 if (len < 0) {
6522 lua_pushfstring(L, "length out of range.");
6523 WILL_LJMP(lua_error(L));
6524 }
6525 }
6526
6527 dup:
6528 _hlua_http_msg_dup(msg, L, offset, len);
6529 return 1;
6530}
6531
6532/* Appends a string to the HTTP message, after all existing DATA blocks but
6533 * before the trailers, if any. It returns the amount of data written or -1 if
6534 * nothing was copied. Unlike the channel function used to append data, this one
6535 * can only be called inside a filter, from http_payload callback. So it cannot
6536 * yield. An exception is returned if it is called from another callback.
6537 */
6538__LJMP static int hlua_http_msg_append(lua_State *L)
6539{
6540 struct http_msg *msg;
6541 struct filter *filter;
6542 const char *str;
6543 size_t offset, len, sz;
6544 int ret;
6545
6546 MAY_LJMP(check_args(L, 2, "append"));
6547 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6548
6549 if (msg->msg_state < HTTP_MSG_DATA)
6550 WILL_LJMP(lua_error(L));
6551
6552 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6553 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6554 if (!filter || !hlua_filter_from_payload(filter))
6555 WILL_LJMP(lua_error(L));
6556
6557 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6558 lua_pushinteger(L, ret);
6559 return 1;
6560}
6561
6562/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6563 * returns the amount of data written or -1 if nothing was copied. Unlike the
6564 * channel function used to prepend data, this one can only be called inside a
6565 * filter, from http_payload callback. So it cannot yield. An exception is
6566 * returned if it is called from another callback.
6567 */
6568__LJMP static int hlua_http_msg_prepend(lua_State *L)
6569{
6570 struct http_msg *msg;
6571 struct filter *filter;
6572 const char *str;
6573 size_t offset, len, sz;
6574 int ret;
6575
6576 MAY_LJMP(check_args(L, 2, "prepend"));
6577 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006578
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006579 if (msg->msg_state < HTTP_MSG_DATA)
6580 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006581
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006582 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6583 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6584 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006585 WILL_LJMP(lua_error(L));
6586
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006587 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6588 lua_pushinteger(L, ret);
6589 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006590}
6591
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006592/* Inserts a string to the HTTP message at a given offset. By default the string
6593 * is appended at the end of DATA blocks. It returns the amount of data written
6594 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6595 * this one can only be called inside a filter, from http_payload callback. So
6596 * it cannot yield. An exception is returned if it is called from another
6597 * callback.
6598 */
6599__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006600{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006601 struct http_msg *msg;
6602 struct filter *filter;
6603 const char *str;
6604 size_t input, output, sz;
6605 int offset;
6606 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006607
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006608 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6609 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6610 MAY_LJMP(check_args(L, 2, "insert"));
6611 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006612
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006613 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006614 WILL_LJMP(lua_error(L));
6615
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006616 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6617 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6618 if (!filter || !hlua_filter_from_payload(filter))
6619 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006620
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006621 offset = input + output;
6622 if (lua_gettop(L) > 2) {
6623 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6624 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006625 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006626 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006627 if (offset < output || offset > output + input) {
6628 lua_pushfstring(L, "offset out of range.");
6629 WILL_LJMP(lua_error(L));
6630 }
6631 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006632
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006633 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6634 lua_pushinteger(L, ret);
6635 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006636}
6637
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006638/* Removes a given amount of data from the HTTP message at a given offset. By
6639 * default all DATA blocks are removed. It returns the amount of data
6640 * removed. Unlike the channel function used to remove data, this one can only
6641 * be called inside a filter, from http_payload callback. So it cannot yield. An
6642 * exception is returned if it is called from another callback.
6643 */
6644__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006645{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006646 struct http_msg *msg;
6647 struct filter *filter;
6648 size_t input, output;
6649 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006650
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006651 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6652 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6653 MAY_LJMP(check_args(L, 2, "insert"));
6654 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006655
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006656 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006657 WILL_LJMP(lua_error(L));
6658
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006659 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6660 if (!filter || !hlua_filter_from_payload(filter))
6661 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006662
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006663 offset = input + output;
6664 if (lua_gettop(L) > 2) {
6665 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6666 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006667 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006668 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006669 if (offset < output || offset > output + input) {
6670 lua_pushfstring(L, "offset out of range.");
6671 WILL_LJMP(lua_error(L));
6672 }
6673 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006674
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006675 len = output + input - offset;
6676 if (lua_gettop(L) == 4) {
6677 len = MAY_LJMP(luaL_checkinteger(L, 4));
6678 if (!len)
6679 goto end;
6680 if (len == -1)
6681 len = output + input - offset;
6682 if (len < 0 || offset + len > output + input) {
6683 lua_pushfstring(L, "length out of range.");
6684 WILL_LJMP(lua_error(L));
6685 }
6686 }
6687
6688 _hlua_http_msg_delete(msg, filter, offset, len);
6689
6690 end:
6691 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006692 return 1;
6693}
6694
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006695/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006696 * all remaining data are removed, accordingly to the filter context. It returns
6697 * the amount of data written or -1 if nothing was copied. Unlike the channel
6698 * function used to replace data, this one can only be called inside a filter,
6699 * from http_payload callback. So it cannot yield. An exception is returned if
6700 * it is called from another callback.
6701 */
6702__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006703{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006704 struct http_msg *msg;
6705 struct filter *filter;
6706 struct htx *htx;
6707 const char *str;
6708 size_t input, output, sz;
6709 int offset, len;
6710 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006711
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006712 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6713 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6714 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6715
6716 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006717 WILL_LJMP(lua_error(L));
6718
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006719 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6720 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6721 if (!filter || !hlua_filter_from_payload(filter))
6722 WILL_LJMP(lua_error(L));
6723
6724 offset = output;
6725 if (lua_gettop(L) > 2) {
6726 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6727 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006728 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006729 offset += output;
6730 if (offset < output || offset > input + output) {
6731 lua_pushfstring(L, "offset out of range.");
6732 WILL_LJMP(lua_error(L));
6733 }
6734 }
6735
6736 len = output + input - offset;
6737 if (lua_gettop(L) == 4) {
6738 len = MAY_LJMP(luaL_checkinteger(L, 4));
6739 if (!len)
6740 goto set;
6741 if (len == -1)
6742 len = output + input - offset;
6743 if (len < 0 || offset + len > output + input) {
6744 lua_pushfstring(L, "length out of range.");
6745 WILL_LJMP(lua_error(L));
6746 }
6747 }
6748
6749 set:
6750 /* Be sure we can copied the string once input data will be removed. */
6751 htx = htx_from_buf(&msg->chn->buf);
6752 if (sz > htx_free_data_space(htx) + len)
6753 lua_pushinteger(L, -1);
6754 else {
6755 _hlua_http_msg_delete(msg, filter, offset, len);
6756 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6757 lua_pushinteger(L, ret);
6758 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006759 return 1;
6760}
6761
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006762/* Prepends data into an HTTP message and forward it, from the filter point of
6763 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6764 * the channel function used to send data, this one can only be called inside a
6765 * filter, from http_payload callback. So it cannot yield. An exception is
6766 * returned if it is called from another callback.
6767 */
6768__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006769{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006770 struct http_msg *msg;
6771 struct filter *filter;
6772 struct htx *htx;
6773 const char *str;
6774 size_t offset, len, sz;
6775 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006776
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006777 MAY_LJMP(check_args(L, 2, "send"));
6778 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6779
6780 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006781 WILL_LJMP(lua_error(L));
6782
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006783 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6784 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6785 if (!filter || !hlua_filter_from_payload(filter))
6786 WILL_LJMP(lua_error(L));
6787
6788 /* Return an error if the channel's output is closed */
6789 if (unlikely(channel_output_closed(msg->chn))) {
6790 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006791 return 1;
6792 }
6793
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006794 htx = htx_from_buf(&msg->chn->buf);
6795 if (sz > htx_free_data_space(htx)) {
6796 lua_pushinteger(L, -1);
6797 return 1;
6798 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006799
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006800 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6801 if (ret > 0) {
6802 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6803
6804 FLT_OFF(filter, msg->chn) += ret;
6805 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6806 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6807 }
6808
6809 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006810 return 1;
6811}
6812
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006813/* Forwards a given amount of bytes. It return -1 if the channel's output is
6814 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6815 * channel function used to forward data, this one can only be called inside a
6816 * filter, from http_payload callback. So it cannot yield. An exception is
6817 * returned if it is called from another callback. All other functions deal with
6818 * DATA block, this one not.
6819*/
6820__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006821{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006822 struct http_msg *msg;
6823 struct filter *filter;
6824 size_t offset, len;
6825 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006826
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006827 MAY_LJMP(check_args(L, 2, "forward"));
6828 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6829
6830 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006831 WILL_LJMP(lua_error(L));
6832
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006833 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6834 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6835 if (!filter || !hlua_filter_from_payload(filter))
6836 WILL_LJMP(lua_error(L));
6837
6838 /* Nothing to do, just return */
6839 if (!fwd)
6840 goto end;
6841
6842 /* Return an error if the channel's output is closed */
6843 if (unlikely(channel_output_closed(msg->chn))) {
6844 ret = -1;
6845 goto end;
6846 }
6847
6848 ret = fwd;
6849 if (ret > len)
6850 ret = len;
6851
6852 if (ret) {
6853 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6854
6855 FLT_OFF(filter, msg->chn) += ret;
6856 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6857 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6858 }
6859
6860 end:
6861 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006862 return 1;
6863}
6864
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006865/* Set EOM flag on the HTX message.
6866 *
6867 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6868 * really know how to do without this feature.
6869 */
6870__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006871{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006872 struct http_msg *msg;
6873 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006874
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006875 MAY_LJMP(check_args(L, 1, "set_eom"));
6876 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6877 htx = htxbuf(&msg->chn->buf);
6878 htx->flags |= HTX_FL_EOM;
6879 return 0;
6880}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006881
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006882/* Unset EOM flag on the HTX message.
6883 *
6884 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6885 * really know how to do without this feature.
6886 */
6887__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6888{
6889 struct http_msg *msg;
6890 struct htx *htx;
6891
6892 MAY_LJMP(check_args(L, 1, "set_eom"));
6893 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6894 htx = htxbuf(&msg->chn->buf);
6895 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006896 return 0;
6897}
6898
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006899/*
6900 *
6901 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006902 * Class HTTPClient
6903 *
6904 *
6905 */
6906__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6907{
6908 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6909}
6910
William Lallemandf77f1de2021-09-28 19:10:38 +02006911
6912/* stops the httpclient and ask it to kill itself */
6913__LJMP static int hlua_httpclient_gc(lua_State *L)
6914{
6915 struct hlua_httpclient *hlua_hc;
6916
6917 MAY_LJMP(check_args(L, 1, "__gc"));
6918
6919 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6920
6921 httpclient_stop_and_destroy(hlua_hc->hc);
6922
6923 hlua_hc->hc = NULL;
6924
6925
6926 return 0;
6927}
6928
6929
William Lallemand3956c4e2021-09-21 16:25:15 +02006930__LJMP static int hlua_httpclient_new(lua_State *L)
6931{
6932 struct hlua_httpclient *hlua_hc;
6933 struct hlua *hlua;
6934
6935 /* Get hlua struct, or NULL if we execute from main lua state */
6936 hlua = hlua_gethlua(L);
6937 if (!hlua)
6938 return 0;
6939
6940 /* Check stack size. */
6941 if (!lua_checkstack(L, 3)) {
6942 hlua_pusherror(L, "httpclient: full stack");
6943 goto err;
6944 }
6945 /* Create the object: obj[0] = userdata. */
6946 lua_newtable(L);
6947 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6948 lua_rawseti(L, -2, 0);
6949 memset(hlua_hc, 0, sizeof(*hlua_hc));
6950
6951 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6952 if (!hlua_hc->hc)
6953 goto err;
6954
6955 /* Pop a class stream metatable and affect it to the userdata. */
6956 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6957 lua_setmetatable(L, -2);
6958
6959 return 1;
6960
6961 err:
6962 WILL_LJMP(lua_error(L));
6963 return 0;
6964}
6965
6966
6967/*
6968 * Callback of the httpclient, this callback wakes the lua task up, once the
6969 * httpclient receives some data
6970 *
6971 */
6972
William Lallemandbd5739e2021-10-28 15:41:38 +02006973static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02006974{
6975 struct hlua *hlua = hc->caller;
6976
6977 if (!hlua || !hlua->task)
6978 return;
6979
6980 task_wakeup(hlua->task, TASK_WOKEN_MSG);
6981}
6982
6983/*
William Lallemandd7df73a2021-09-23 17:54:00 +02006984 * Fill the lua stack with headers from the httpclient response
6985 * This works the same way as the hlua_http_get_headers() function
6986 */
6987__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
6988{
6989 struct http_hdr *hdr;
6990
6991 lua_newtable(L);
6992
William Lallemandef574b22021-10-05 16:19:31 +02006993 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02006994 struct ist n, v;
6995 int len;
6996
6997 n = hdr->n;
6998 v = hdr->v;
6999
7000 /* Check for existing entry:
7001 * assume that the table is on the top of the stack, and
7002 * push the key in the stack, the function lua_gettable()
7003 * perform the lookup.
7004 */
7005
7006 lua_pushlstring(L, n.ptr, n.len);
7007 lua_gettable(L, -2);
7008
7009 switch (lua_type(L, -1)) {
7010 case LUA_TNIL:
7011 /* Table not found, create it. */
7012 lua_pop(L, 1); /* remove the nil value. */
7013 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7014 lua_newtable(L); /* create and push empty table. */
7015 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7016 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7017 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7018 break;
7019
7020 case LUA_TTABLE:
7021 /* Entry found: push the value in the table. */
7022 len = lua_rawlen(L, -1);
7023 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7024 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7025 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7026 break;
7027
7028 default:
7029 /* Other cases are errors. */
7030 hlua_pusherror(L, "internal error during the parsing of headers.");
7031 WILL_LJMP(lua_error(L));
7032 }
7033 }
7034 return 1;
7035}
7036
7037/*
William Lallemand746e6f32021-10-06 10:57:44 +02007038 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7039 *
7040 * Caller must free the result
7041 */
7042struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7043{
7044 struct http_hdr hdrs[global.tune.max_http_hdr];
7045 struct http_hdr *result = NULL;
7046 uint32_t hdr_num = 0;
7047
7048 lua_pushnil(L);
7049 while (lua_next(L, -2) != 0) {
7050 struct ist name, value;
7051 const char *n, *v;
7052 size_t nlen, vlen;
7053
7054 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7055 /* Skip element if the key is not a string or if the value is not a table */
7056 goto next_hdr;
7057 }
7058
7059 n = lua_tolstring(L, -2, &nlen);
7060 name = ist2(n, nlen);
7061
7062 /* Loop on header's values */
7063 lua_pushnil(L);
7064 while (lua_next(L, -2)) {
7065 if (!lua_isstring(L, -1)) {
7066 /* Skip the value if it is not a string */
7067 goto next_value;
7068 }
7069
7070 v = lua_tolstring(L, -1, &vlen);
7071 value = ist2(v, vlen);
7072 name = ist2(n, nlen);
7073
7074 hdrs[hdr_num].n = istdup(name);
7075 hdrs[hdr_num].v = istdup(value);
7076
7077 hdr_num++;
7078
7079 next_value:
7080 lua_pop(L, 1);
7081 }
7082
7083 next_hdr:
7084 lua_pop(L, 1);
7085
7086 }
7087
7088 if (hdr_num) {
7089 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007090 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007091 if (!result)
7092 goto skip_headers;
7093 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7094
7095 result[hdr_num].n = IST_NULL;
7096 result[hdr_num].v = IST_NULL;
7097 }
7098
7099skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007100
7101 return result;
7102}
7103
7104
William Lallemandbd5739e2021-10-28 15:41:38 +02007105/*
7106 * For each yield, checks if there is some data in the httpclient and push them
7107 * in the lua buffer, once the httpclient finished its job, push the result on
7108 * the stack
7109 */
7110__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7111{
7112 struct buffer *tr;
7113 int res;
7114 struct hlua *hlua = hlua_gethlua(L);
7115 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7116
7117
7118 tr = get_trash_chunk();
7119
7120 res = httpclient_res_xfer(hlua_hc->hc, tr);
7121 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7122
7123 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7124
7125 luaL_pushresult(&hlua_hc->b);
7126 lua_settable(L, -3);
7127
7128 lua_pushstring(L, "status");
7129 lua_pushinteger(L, hlua_hc->hc->res.status);
7130 lua_settable(L, -3);
7131
7132
7133 lua_pushstring(L, "reason");
7134 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7135 lua_settable(L, -3);
7136
7137 lua_pushstring(L, "headers");
7138 hlua_httpclient_get_headers(L, hlua_hc);
7139 lua_settable(L, -3);
7140
7141 return 1;
7142 }
7143
7144 if (httpclient_data(hlua_hc->hc))
7145 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7146
7147 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7148
7149 return 0;
7150}
7151
7152/*
7153 * Call this when trying to stream a body during a request
7154 */
7155__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7156{
7157 struct hlua *hlua;
7158 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7159 const char *body_str = NULL;
7160 int ret;
7161 int end = 0;
7162 size_t buf_len;
7163 size_t to_send = 0;
7164
7165 hlua = hlua_gethlua(L);
7166
7167 if (!hlua || !hlua->task)
7168 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7169 "'frontend', 'backend' or 'task'"));
7170
7171 ret = lua_getfield(L, -1, "body");
7172 if (ret != LUA_TSTRING)
7173 goto rcv;
7174
7175 body_str = lua_tolstring(L, -1, &buf_len);
7176 lua_pop(L, 1);
7177
Christopher Fauletfc591292022-01-12 14:46:03 +01007178 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007179
7180 if ((hlua_hc->sent + to_send) >= buf_len)
7181 end = 1;
7182
7183 /* the end flag is always set since we are using the whole remaining size */
7184 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7185
7186 if (buf_len > hlua_hc->sent) {
7187 /* still need to process the buffer */
7188 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7189 } else {
7190 goto rcv;
7191 /* we sent the whole request buffer we can recv */
7192 }
7193 return 0;
7194
7195rcv:
7196
7197 /* we return a "res" object */
7198 lua_newtable(L);
7199
William Lallemandbd5739e2021-10-28 15:41:38 +02007200 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007201 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007202
William Lallemand933fe392021-11-04 09:45:58 +01007203 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007204 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7205
7206 return 1;
7207}
William Lallemand746e6f32021-10-06 10:57:44 +02007208
William Lallemand3956c4e2021-09-21 16:25:15 +02007209/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007210 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007211 */
7212
William Lallemanddc2cc902021-10-26 11:43:26 +02007213__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007214{
7215 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007216 struct http_hdr *hdrs = NULL;
7217 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007218 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007219 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007220 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007221 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007222 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007223
7224 hlua = hlua_gethlua(L);
7225
7226 if (!hlua || !hlua->task)
7227 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7228 "'frontend', 'backend' or 'task'"));
7229
William Lallemand746e6f32021-10-06 10:57:44 +02007230 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7231 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7232
William Lallemand4f4f2b72022-02-17 20:00:23 +01007233 hlua_hc = hlua_checkhttpclient(L, 1);
7234
7235 ret = lua_getfield(L, -1, "dst");
7236 if (ret == LUA_TSTRING) {
7237 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7238 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
7239 }
7240 lua_pop(L, 1);
7241
William Lallemand746e6f32021-10-06 10:57:44 +02007242 ret = lua_getfield(L, -1, "url");
7243 if (ret == LUA_TSTRING) {
7244 url_str = lua_tostring(L, -1);
7245 }
7246 lua_pop(L, 1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007247
William Lallemand746e6f32021-10-06 10:57:44 +02007248 ret = lua_getfield(L, -1, "headers");
7249 if (ret == LUA_TTABLE) {
7250 hdrs = hlua_httpclient_table_to_hdrs(L);
7251 }
7252 lua_pop(L, 1);
William Lallemand79416cb2021-09-24 14:51:44 +02007253
William Lallemanddec25c32021-10-25 19:48:37 +02007254 ret = lua_getfield(L, -1, "body");
7255 if (ret == LUA_TSTRING) {
William Lallemandbd5739e2021-10-28 15:41:38 +02007256 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemanddec25c32021-10-25 19:48:37 +02007257 }
William Lallemandbd5739e2021-10-28 15:41:38 +02007258
William Lallemanddec25c32021-10-25 19:48:37 +02007259 lua_pop(L, 1);
7260
William Lallemand746e6f32021-10-06 10:57:44 +02007261 if (!url_str) {
7262 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7263 return 0;
7264 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007265
William Lallemand3956c4e2021-09-21 16:25:15 +02007266
7267 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007268 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007269
7270 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007271 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7272 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7273 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007274
William Lallemandbd5739e2021-10-28 15:41:38 +02007275 /* a body is available, it will use the request callback */
7276 if (body_str) {
7277 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7278 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007279
William Lallemandbd5739e2021-10-28 15:41:38 +02007280 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007281
William Lallemand746e6f32021-10-06 10:57:44 +02007282 /* free the temporary headers array */
7283 hdrs_i = hdrs;
7284 while (hdrs_i && isttest(hdrs_i->n)) {
7285 istfree(&hdrs_i->n);
7286 istfree(&hdrs_i->v);
7287 hdrs_i++;
7288 }
7289 ha_free(&hdrs);
7290
7291
William Lallemand6137a9e2021-10-26 15:01:53 +02007292 if (ret != ERR_NONE) {
7293 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7294 return 0;
7295 }
7296
William Lallemand6137a9e2021-10-26 15:01:53 +02007297 httpclient_start(hlua_hc->hc);
7298
William Lallemandbd5739e2021-10-28 15:41:38 +02007299 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007300
William Lallemand3956c4e2021-09-21 16:25:15 +02007301 return 0;
7302}
7303
7304/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007305 * Sends an HTTP HEAD request and wait for a response
7306 *
7307 * httpclient:head(url, headers, payload)
7308 */
7309__LJMP static int hlua_httpclient_head(lua_State *L)
7310{
7311 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7312}
7313
7314/*
7315 * Send an HTTP GET request and wait for a response
7316 *
7317 * httpclient:get(url, headers, payload)
7318 */
7319__LJMP static int hlua_httpclient_get(lua_State *L)
7320{
7321 return hlua_httpclient_send(L, HTTP_METH_GET);
7322
7323}
7324
7325/*
7326 * Sends an HTTP PUT request and wait for a response
7327 *
7328 * httpclient:put(url, headers, payload)
7329 */
7330__LJMP static int hlua_httpclient_put(lua_State *L)
7331{
7332 return hlua_httpclient_send(L, HTTP_METH_PUT);
7333}
7334
7335/*
7336 * Send an HTTP POST request and wait for a response
7337 *
7338 * httpclient:post(url, headers, payload)
7339 */
7340__LJMP static int hlua_httpclient_post(lua_State *L)
7341{
7342 return hlua_httpclient_send(L, HTTP_METH_POST);
7343}
7344
7345
7346/*
7347 * Sends an HTTP DELETE request and wait for a response
7348 *
7349 * httpclient:delete(url, headers, payload)
7350 */
7351__LJMP static int hlua_httpclient_delete(lua_State *L)
7352{
7353 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7354}
7355
7356/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007357 *
7358 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007359 * Class TXN
7360 *
7361 *
7362 */
7363
7364/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007365 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007366 */
7367__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7368{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007369 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007370}
7371
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007372__LJMP static int hlua_set_var(lua_State *L)
7373{
7374 struct hlua_txn *htxn;
7375 const char *name;
7376 size_t len;
7377 struct sample smp;
7378
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007379 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7380 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007381
7382 /* It is useles to retrieve the stream, but this function
7383 * runs only in a stream context.
7384 */
7385 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7386 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7387
7388 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007389 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007390 hlua_lua2smp(L, 3, &smp);
7391
7392 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007393 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007394
7395 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7396 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7397 else
7398 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7399
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007400 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007401}
7402
Christopher Faulet85d79c92016-11-09 16:54:56 +01007403__LJMP static int hlua_unset_var(lua_State *L)
7404{
7405 struct hlua_txn *htxn;
7406 const char *name;
7407 size_t len;
7408 struct sample smp;
7409
7410 MAY_LJMP(check_args(L, 2, "unset_var"));
7411
7412 /* It is useles to retrieve the stream, but this function
7413 * runs only in a stream context.
7414 */
7415 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7416 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7417
7418 /* Unset the variable. */
7419 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007420 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7421 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007422}
7423
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007424__LJMP static int hlua_get_var(lua_State *L)
7425{
7426 struct hlua_txn *htxn;
7427 const char *name;
7428 size_t len;
7429 struct sample smp;
7430
7431 MAY_LJMP(check_args(L, 2, "get_var"));
7432
7433 /* It is useles to retrieve the stream, but this function
7434 * runs only in a stream context.
7435 */
7436 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7437 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7438
Willy Tarreau7560dd42016-03-10 16:28:58 +01007439 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007440 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007441 lua_pushnil(L);
7442 return 1;
7443 }
7444
7445 return hlua_smp2lua(L, &smp);
7446}
7447
Willy Tarreau59551662015-03-10 14:23:13 +01007448__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007449{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007450 struct hlua *hlua;
7451
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007452 MAY_LJMP(check_args(L, 2, "set_priv"));
7453
Willy Tarreau87b09662015-04-03 00:22:06 +02007454 /* It is useles to retrieve the stream, but this function
7455 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007456 */
7457 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007458
7459 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007460 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007461 if (!hlua)
7462 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007463
7464 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007465 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007466
7467 /* Get and store new value. */
7468 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7469 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7470
7471 return 0;
7472}
7473
Willy Tarreau59551662015-03-10 14:23:13 +01007474__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007475{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007476 struct hlua *hlua;
7477
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007478 MAY_LJMP(check_args(L, 1, "get_priv"));
7479
Willy Tarreau87b09662015-04-03 00:22:06 +02007480 /* It is useles to retrieve the stream, but this function
7481 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007482 */
7483 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007484
7485 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007486 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007487 if (!hlua) {
7488 lua_pushnil(L);
7489 return 1;
7490 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007491
7492 /* Push configuration index in the stack. */
7493 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7494
7495 return 1;
7496}
7497
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007498/* Create stack entry containing a class TXN. This function
7499 * return 0 if the stack does not contains free slots,
7500 * otherwise it returns 1.
7501 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007502static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007503{
Willy Tarreaude491382015-04-06 11:04:28 +02007504 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007505
7506 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007507 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007508 return 0;
7509
7510 /* NOTE: The allocation never fails. The failure
7511 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007512 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007513 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007514 /* Create the object: obj[0] = userdata. */
7515 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007516 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007517 lua_rawseti(L, -2, 0);
7518
Willy Tarreaude491382015-04-06 11:04:28 +02007519 htxn->s = s;
7520 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007521 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007522 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007523
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007524 /* Create the "f" field that contains a list of fetches. */
7525 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007526 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007527 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007528 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007529
7530 /* Create the "sf" field that contains a list of stringsafe fetches. */
7531 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007532 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007533 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007534 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007535
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007536 /* Create the "c" field that contains a list of converters. */
7537 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007538 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007539 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007540 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007541
7542 /* Create the "sc" field that contains a list of stringsafe converters. */
7543 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007544 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007545 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007546 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007547
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007548 /* Create the "req" field that contains the request channel object. */
7549 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007550 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007551 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007552 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007553
7554 /* Create the "res" field that contains the response channel object. */
7555 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007556 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007557 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007558 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007559
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007560 /* Creates the HTTP object is the current proxy allows http. */
7561 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007562 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007563 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007564 return 0;
7565 }
7566 else
7567 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007568 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007569
Christopher Faulet78c35472020-02-26 17:14:08 +01007570 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7571 /* HTTPMessage object are created when a lua TXN is created from
7572 * a filter context only
7573 */
7574
7575 /* Creates the HTTP-Request object is the current proxy allows http. */
7576 lua_pushstring(L, "http_req");
7577 if (p->mode == PR_MODE_HTTP) {
7578 if (!hlua_http_msg_new(L, &s->txn->req))
7579 return 0;
7580 }
7581 else
7582 lua_pushnil(L);
7583 lua_rawset(L, -3);
7584
7585 /* Creates the HTTP-Response object is the current proxy allows http. */
7586 lua_pushstring(L, "http_res");
7587 if (p->mode == PR_MODE_HTTP) {
7588 if (!hlua_http_msg_new(L, &s->txn->rsp))
7589 return 0;
7590 }
7591 else
7592 lua_pushnil(L);
7593 lua_rawset(L, -3);
7594 }
7595
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007596 /* Pop a class sesison metatable and affect it to the userdata. */
7597 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7598 lua_setmetatable(L, -2);
7599
7600 return 1;
7601}
7602
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007603__LJMP static int hlua_txn_deflog(lua_State *L)
7604{
7605 const char *msg;
7606 struct hlua_txn *htxn;
7607
7608 MAY_LJMP(check_args(L, 2, "deflog"));
7609 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7610 msg = MAY_LJMP(luaL_checkstring(L, 2));
7611
7612 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7613 return 0;
7614}
7615
7616__LJMP static int hlua_txn_log(lua_State *L)
7617{
7618 int level;
7619 const char *msg;
7620 struct hlua_txn *htxn;
7621
7622 MAY_LJMP(check_args(L, 3, "log"));
7623 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7624 level = MAY_LJMP(luaL_checkinteger(L, 2));
7625 msg = MAY_LJMP(luaL_checkstring(L, 3));
7626
7627 if (level < 0 || level >= NB_LOG_LEVELS)
7628 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7629
7630 hlua_sendlog(htxn->s->be, level, msg);
7631 return 0;
7632}
7633
7634__LJMP static int hlua_txn_log_debug(lua_State *L)
7635{
7636 const char *msg;
7637 struct hlua_txn *htxn;
7638
7639 MAY_LJMP(check_args(L, 2, "Debug"));
7640 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7641 msg = MAY_LJMP(luaL_checkstring(L, 2));
7642 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7643 return 0;
7644}
7645
7646__LJMP static int hlua_txn_log_info(lua_State *L)
7647{
7648 const char *msg;
7649 struct hlua_txn *htxn;
7650
7651 MAY_LJMP(check_args(L, 2, "Info"));
7652 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7653 msg = MAY_LJMP(luaL_checkstring(L, 2));
7654 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7655 return 0;
7656}
7657
7658__LJMP static int hlua_txn_log_warning(lua_State *L)
7659{
7660 const char *msg;
7661 struct hlua_txn *htxn;
7662
7663 MAY_LJMP(check_args(L, 2, "Warning"));
7664 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7665 msg = MAY_LJMP(luaL_checkstring(L, 2));
7666 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7667 return 0;
7668}
7669
7670__LJMP static int hlua_txn_log_alert(lua_State *L)
7671{
7672 const char *msg;
7673 struct hlua_txn *htxn;
7674
7675 MAY_LJMP(check_args(L, 2, "Alert"));
7676 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7677 msg = MAY_LJMP(luaL_checkstring(L, 2));
7678 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7679 return 0;
7680}
7681
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007682__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7683{
7684 struct hlua_txn *htxn;
7685 int ll;
7686
7687 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7688 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7689 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7690
7691 if (ll < 0 || ll > 7)
7692 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7693
7694 htxn->s->logs.level = ll;
7695 return 0;
7696}
7697
7698__LJMP static int hlua_txn_set_tos(lua_State *L)
7699{
7700 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007701 int tos;
7702
7703 MAY_LJMP(check_args(L, 2, "set_tos"));
7704 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7705 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7706
Willy Tarreau1a18b542018-12-11 16:37:42 +01007707 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007708 return 0;
7709}
7710
7711__LJMP static int hlua_txn_set_mark(lua_State *L)
7712{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007713 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007714 int mark;
7715
7716 MAY_LJMP(check_args(L, 2, "set_mark"));
7717 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7718 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7719
Lukas Tribus579e3e32019-08-11 18:03:45 +02007720 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007721 return 0;
7722}
7723
Patrick Hemmer268a7072018-05-11 12:52:31 -04007724__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7725{
7726 struct hlua_txn *htxn;
7727
7728 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7729 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7730 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7731 return 0;
7732}
7733
7734__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7735{
7736 struct hlua_txn *htxn;
7737
7738 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7739 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7740 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7741 return 0;
7742}
7743
Christopher Faulet700d9e82020-01-31 12:21:52 +01007744/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007745 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007746 * message and terminate the transaction. It returns 1 on success and 0 on
7747 * error. The Reply must be on top of the stack.
7748 */
7749__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7750{
7751 struct htx *htx;
7752 struct htx_sl *sl;
7753 struct h1m h1m;
7754 const char *status, *reason, *body;
7755 size_t status_len, reason_len, body_len;
7756 int ret, code, flags;
7757
7758 code = 200;
7759 status = "200";
7760 status_len = 3;
7761 ret = lua_getfield(L, -1, "status");
7762 if (ret == LUA_TNUMBER) {
7763 code = lua_tointeger(L, -1);
7764 status = lua_tolstring(L, -1, &status_len);
7765 }
7766 lua_pop(L, 1);
7767
7768 reason = http_get_reason(code);
7769 reason_len = strlen(reason);
7770 ret = lua_getfield(L, -1, "reason");
7771 if (ret == LUA_TSTRING)
7772 reason = lua_tolstring(L, -1, &reason_len);
7773 lua_pop(L, 1);
7774
7775 body = NULL;
7776 body_len = 0;
7777 ret = lua_getfield(L, -1, "body");
7778 if (ret == LUA_TSTRING)
7779 body = lua_tolstring(L, -1, &body_len);
7780 lua_pop(L, 1);
7781
7782 /* Prepare the response before inserting the headers */
7783 h1m_init_res(&h1m);
7784 htx = htx_from_buf(&s->res.buf);
7785 channel_htx_truncate(&s->res, htx);
7786 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7787 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7788 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7789 ist2(status, status_len), ist2(reason, reason_len));
7790 }
7791 else {
7792 flags = HTX_SL_F_IS_RESP;
7793 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7794 ist2(status, status_len), ist2(reason, reason_len));
7795 }
7796 if (!sl)
7797 goto fail;
7798 sl->info.res.status = code;
7799
7800 /* Push in the stack the "headers" entry. */
7801 ret = lua_getfield(L, -1, "headers");
7802 if (ret != LUA_TTABLE)
7803 goto skip_headers;
7804
7805 lua_pushnil(L);
7806 while (lua_next(L, -2) != 0) {
7807 struct ist name, value;
7808 const char *n, *v;
7809 size_t nlen, vlen;
7810
7811 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7812 /* Skip element if the key is not a string or if the value is not a table */
7813 goto next_hdr;
7814 }
7815
7816 n = lua_tolstring(L, -2, &nlen);
7817 name = ist2(n, nlen);
7818 if (isteqi(name, ist("content-length"))) {
7819 /* Always skip content-length header. It will be added
7820 * later with the correct len
7821 */
7822 goto next_hdr;
7823 }
7824
7825 /* Loop on header's values */
7826 lua_pushnil(L);
7827 while (lua_next(L, -2)) {
7828 if (!lua_isstring(L, -1)) {
7829 /* Skip the value if it is not a string */
7830 goto next_value;
7831 }
7832
7833 v = lua_tolstring(L, -1, &vlen);
7834 value = ist2(v, vlen);
7835
7836 if (isteqi(name, ist("transfer-encoding")))
7837 h1_parse_xfer_enc_header(&h1m, value);
7838 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7839 goto fail;
7840
7841 next_value:
7842 lua_pop(L, 1);
7843 }
7844
7845 next_hdr:
7846 lua_pop(L, 1);
7847 }
7848 skip_headers:
7849 lua_pop(L, 1);
7850
7851 /* Update h1m flags: CLEN is set if CHNK is not present */
7852 if (!(h1m.flags & H1_MF_CHNK)) {
7853 const char *clen = ultoa(body_len);
7854
7855 h1m.flags |= H1_MF_CLEN;
7856 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7857 goto fail;
7858 }
7859 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7860 h1m.flags |= H1_MF_XFER_LEN;
7861
7862 /* Update HTX start-line flags */
7863 if (h1m.flags & H1_MF_XFER_ENC)
7864 flags |= HTX_SL_F_XFER_ENC;
7865 if (h1m.flags & H1_MF_XFER_LEN) {
7866 flags |= HTX_SL_F_XFER_LEN;
7867 if (h1m.flags & H1_MF_CHNK)
7868 flags |= HTX_SL_F_CHNK;
7869 else if (h1m.flags & H1_MF_CLEN)
7870 flags |= HTX_SL_F_CLEN;
7871 if (h1m.body_len == 0)
7872 flags |= HTX_SL_F_BODYLESS;
7873 }
7874 sl->flags |= flags;
7875
7876
7877 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007878 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007879 goto fail;
7880
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007881 htx->flags |= HTX_FL_EOM;
7882
Christopher Faulet700d9e82020-01-31 12:21:52 +01007883 /* Now, forward the response and terminate the transaction */
7884 s->txn->status = code;
7885 htx_to_buf(htx, &s->res.buf);
7886 if (!http_forward_proxy_resp(s, 1))
7887 goto fail;
7888
7889 return 1;
7890
7891 fail:
7892 channel_htx_truncate(&s->res, htx);
7893 return 0;
7894}
7895
7896/* Terminate a transaction if called from a lua action. For TCP streams,
7897 * processing is just aborted. Nothing is returned to the client and all
7898 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7899 * is forwarded to the client before terminating the transaction. On success,
7900 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7901 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7902 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007903 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007904__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007905{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007906 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007907 struct stream *s;
7908 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007909
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007910 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007911
Christopher Faulet700d9e82020-01-31 12:21:52 +01007912 /* If the flags NOTERM is set, we cannot terminate the session, so we
7913 * just end the execution of the current lua code. */
7914 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007915 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007916
Christopher Faulet700d9e82020-01-31 12:21:52 +01007917 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007918 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007919 struct channel *req = &s->req;
7920 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007921
Christopher Faulet700d9e82020-01-31 12:21:52 +01007922 channel_auto_read(req);
7923 channel_abort(req);
7924 channel_auto_close(req);
7925 channel_erase(req);
7926
7927 res->wex = tick_add_ifset(now_ms, res->wto);
7928 channel_auto_read(res);
7929 channel_auto_close(res);
7930 channel_shutr_now(res);
7931
7932 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7933 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007934 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007935
Christopher Faulet700d9e82020-01-31 12:21:52 +01007936 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7937 /* No reply or invalid reply */
7938 s->txn->status = 0;
7939 http_reply_and_close(s, 0, NULL);
7940 }
7941 else {
7942 /* Remove extra args to have the reply on top of the stack */
7943 if (lua_gettop(L) > 2)
7944 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007945
Christopher Faulet700d9e82020-01-31 12:21:52 +01007946 if (!hlua_txn_forward_reply(L, s)) {
7947 if (!(s->flags & SF_ERR_MASK))
7948 s->flags |= SF_ERR_PRXCOND;
7949 lua_pushinteger(L, ACT_RET_ERR);
7950 WILL_LJMP(hlua_done(L));
7951 return 0; /* Never reached */
7952 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007953 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007954
Christopher Faulet700d9e82020-01-31 12:21:52 +01007955 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7956 if (htxn->dir == SMP_OPT_DIR_REQ) {
7957 /* let's log the request time */
7958 s->logs.tv_request = now;
7959 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007960 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007961 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007962
Christopher Faulet700d9e82020-01-31 12:21:52 +01007963 done:
7964 if (!(s->flags & SF_ERR_MASK))
7965 s->flags |= SF_ERR_LOCAL;
7966 if (!(s->flags & SF_FINST_MASK))
7967 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007968
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007969 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7970 lua_pushinteger(L, -1);
7971 else
7972 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007973 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007974 return 0;
7975}
7976
Christopher Faulet700d9e82020-01-31 12:21:52 +01007977/*
7978 *
7979 *
7980 * Class REPLY
7981 *
7982 *
7983 */
7984
7985/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
7986 * free slots, the function fails and returns 0;
7987 */
7988static int hlua_txn_reply_new(lua_State *L)
7989{
7990 struct hlua_txn *htxn;
7991 const char *reason, *body = NULL;
7992 int ret, status;
7993
7994 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007995 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007996 hlua_pusherror(L, "txn object is not an HTTP transaction.");
7997 WILL_LJMP(lua_error(L));
7998 }
7999
8000 /* Default value */
8001 status = 200;
8002 reason = http_get_reason(status);
8003
8004 if (lua_istable(L, 2)) {
8005 /* load status and reason from the table argument at index 2 */
8006 ret = lua_getfield(L, 2, "status");
8007 if (ret == LUA_TNIL)
8008 goto reason;
8009 else if (ret != LUA_TNUMBER) {
8010 /* invalid status: ignore the reason */
8011 goto body;
8012 }
8013 status = lua_tointeger(L, -1);
8014
8015 reason:
8016 lua_pop(L, 1); /* restore the stack: remove status */
8017 ret = lua_getfield(L, 2, "reason");
8018 if (ret == LUA_TSTRING)
8019 reason = lua_tostring(L, -1);
8020
8021 body:
8022 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8023 ret = lua_getfield(L, 2, "body");
8024 if (ret == LUA_TSTRING)
8025 body = lua_tostring(L, -1);
8026 lua_pop(L, 1); /* restore the stack: remove body */
8027 }
8028
8029 /* Create the Reply table */
8030 lua_newtable(L);
8031
8032 /* Add status element */
8033 lua_pushstring(L, "status");
8034 lua_pushinteger(L, status);
8035 lua_settable(L, -3);
8036
8037 /* Add reason element */
8038 reason = http_get_reason(status);
8039 lua_pushstring(L, "reason");
8040 lua_pushstring(L, reason);
8041 lua_settable(L, -3);
8042
8043 /* Add body element, nil if undefined */
8044 lua_pushstring(L, "body");
8045 if (body)
8046 lua_pushstring(L, body);
8047 else
8048 lua_pushnil(L);
8049 lua_settable(L, -3);
8050
8051 /* Add headers element */
8052 lua_pushstring(L, "headers");
8053 lua_newtable(L);
8054
8055 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8056 if (lua_istable(L, 2)) {
8057 /* load headers from the table argument at index 2. If it is a table, copy it. */
8058 ret = lua_getfield(L, 2, "headers");
8059 if (ret == LUA_TTABLE) {
8060 /* stack: [ ... <headers:table>, <table> ] */
8061 lua_pushnil(L);
8062 while (lua_next(L, -2) != 0) {
8063 /* stack: [ ... <headers:table>, <table>, k, v] */
8064 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8065 /* invalid value type, skip it */
8066 lua_pop(L, 1);
8067 continue;
8068 }
8069
8070
8071 /* Duplicate the key and swap it with the value. */
8072 lua_pushvalue(L, -2);
8073 lua_insert(L, -2);
8074 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8075
8076 lua_newtable(L);
8077 lua_insert(L, -2);
8078 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8079
8080 if (lua_isstring(L, -1)) {
8081 /* push the value in the inner table */
8082 lua_rawseti(L, -2, 1);
8083 }
8084 else { /* table */
8085 lua_pushnil(L);
8086 while (lua_next(L, -2) != 0) {
8087 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8088 if (!lua_isstring(L, -1)) {
8089 /* invalid value type, skip it*/
8090 lua_pop(L, 1);
8091 continue;
8092 }
8093 /* push the value in the inner table */
8094 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8095 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8096 }
8097 lua_pop(L, 1);
8098 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8099 }
8100
8101 /* push (k,v) on the stack in the headers table:
8102 * stack: [ ... <headers:table>, <table>, k, k, v ]
8103 */
8104 lua_settable(L, -5);
8105 /* stack: [ ... <headers:table>, <table>, k ] */
8106 }
8107 }
8108 lua_pop(L, 1);
8109 }
8110 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8111 lua_settable(L, -3);
8112 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8113
8114 /* Pop a class sesison metatable and affect it to the userdata. */
8115 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8116 lua_setmetatable(L, -2);
8117 return 1;
8118}
8119
8120/* Set the reply status code, and optionally the reason. If no reason is
8121 * provided, the default one corresponding to the status code is used.
8122 */
8123__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8124{
8125 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8126 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8127
8128 /* First argument (self) must be a table */
8129 luaL_checktype(L, 1, LUA_TTABLE);
8130
8131 if (status < 100 || status > 599) {
8132 lua_pushboolean(L, 0);
8133 return 1;
8134 }
8135 if (!reason)
8136 reason = http_get_reason(status);
8137
8138 lua_pushinteger(L, status);
8139 lua_setfield(L, 1, "status");
8140
8141 lua_pushstring(L, reason);
8142 lua_setfield(L, 1, "reason");
8143
8144 lua_pushboolean(L, 1);
8145 return 1;
8146}
8147
8148/* Add a header into the reply object. Each header name is associated to an
8149 * array of values in the "headers" table. If the header name is not found, a
8150 * new entry is created.
8151 */
8152__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8153{
8154 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8155 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8156 int ret;
8157
8158 /* First argument (self) must be a table */
8159 luaL_checktype(L, 1, LUA_TTABLE);
8160
8161 /* Push in the stack the "headers" entry. */
8162 ret = lua_getfield(L, 1, "headers");
8163 if (ret != LUA_TTABLE) {
8164 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8165 WILL_LJMP(lua_error(L));
8166 }
8167
8168 /* check if the header is already registered. If not, register it. */
8169 ret = lua_getfield(L, -1, name);
8170 if (ret == LUA_TNIL) {
8171 /* Entry not found. */
8172 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8173
8174 /* Insert the new header name in the array in the top of the stack.
8175 * It left the new array in the top of the stack.
8176 */
8177 lua_newtable(L);
8178 lua_pushstring(L, name);
8179 lua_pushvalue(L, -2);
8180 lua_settable(L, -4);
8181 }
8182 else if (ret != LUA_TTABLE) {
8183 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8184 WILL_LJMP(lua_error(L));
8185 }
8186
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008187 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008188 * the header value as new entry.
8189 */
8190 lua_pushstring(L, value);
8191 ret = lua_rawlen(L, -2);
8192 lua_rawseti(L, -2, ret + 1);
8193
8194 lua_pushboolean(L, 1);
8195 return 1;
8196}
8197
8198/* Remove all occurrences of a given header name. */
8199__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8200{
8201 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8202 int ret;
8203
8204 /* First argument (self) must be a table */
8205 luaL_checktype(L, 1, LUA_TTABLE);
8206
8207 /* Push in the stack the "headers" entry. */
8208 ret = lua_getfield(L, 1, "headers");
8209 if (ret != LUA_TTABLE) {
8210 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8211 WILL_LJMP(lua_error(L));
8212 }
8213
8214 lua_pushstring(L, name);
8215 lua_pushnil(L);
8216 lua_settable(L, -3);
8217
8218 lua_pushboolean(L, 1);
8219 return 1;
8220}
8221
8222/* Set the reply's body. Overwrite any existing entry. */
8223__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8224{
8225 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8226
8227 /* First argument (self) must be a table */
8228 luaL_checktype(L, 1, LUA_TTABLE);
8229
8230 lua_pushstring(L, payload);
8231 lua_setfield(L, 1, "body");
8232
8233 lua_pushboolean(L, 1);
8234 return 1;
8235}
8236
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008237__LJMP static int hlua_log(lua_State *L)
8238{
8239 int level;
8240 const char *msg;
8241
8242 MAY_LJMP(check_args(L, 2, "log"));
8243 level = MAY_LJMP(luaL_checkinteger(L, 1));
8244 msg = MAY_LJMP(luaL_checkstring(L, 2));
8245
8246 if (level < 0 || level >= NB_LOG_LEVELS)
8247 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8248
8249 hlua_sendlog(NULL, level, msg);
8250 return 0;
8251}
8252
8253__LJMP static int hlua_log_debug(lua_State *L)
8254{
8255 const char *msg;
8256
8257 MAY_LJMP(check_args(L, 1, "debug"));
8258 msg = MAY_LJMP(luaL_checkstring(L, 1));
8259 hlua_sendlog(NULL, LOG_DEBUG, msg);
8260 return 0;
8261}
8262
8263__LJMP static int hlua_log_info(lua_State *L)
8264{
8265 const char *msg;
8266
8267 MAY_LJMP(check_args(L, 1, "info"));
8268 msg = MAY_LJMP(luaL_checkstring(L, 1));
8269 hlua_sendlog(NULL, LOG_INFO, msg);
8270 return 0;
8271}
8272
8273__LJMP static int hlua_log_warning(lua_State *L)
8274{
8275 const char *msg;
8276
8277 MAY_LJMP(check_args(L, 1, "warning"));
8278 msg = MAY_LJMP(luaL_checkstring(L, 1));
8279 hlua_sendlog(NULL, LOG_WARNING, msg);
8280 return 0;
8281}
8282
8283__LJMP static int hlua_log_alert(lua_State *L)
8284{
8285 const char *msg;
8286
8287 MAY_LJMP(check_args(L, 1, "alert"));
8288 msg = MAY_LJMP(luaL_checkstring(L, 1));
8289 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008290 return 0;
8291}
8292
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008293__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008294{
8295 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008296 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008297 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008298 return 0;
8299}
8300
8301__LJMP static int hlua_sleep(lua_State *L)
8302{
8303 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008304 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008305
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008306 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008307
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008308 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008309 wakeup_ms = tick_add(now_ms, delay);
8310 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008311
Willy Tarreau9635e032018-10-16 17:52:55 +02008312 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008313 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008314}
8315
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008316__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008317{
8318 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008319 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008320
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008321 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008322
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008323 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008324 wakeup_ms = tick_add(now_ms, delay);
8325 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008326
Willy Tarreau9635e032018-10-16 17:52:55 +02008327 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008328 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008329}
8330
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008331/* This functionis an LUA binding. it permits to give back
8332 * the hand at the HAProxy scheduler. It is used when the
8333 * LUA processing consumes a lot of time.
8334 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008335__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008336{
8337 return 0;
8338}
8339
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008340__LJMP static int hlua_yield(lua_State *L)
8341{
Willy Tarreau9635e032018-10-16 17:52:55 +02008342 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008343 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008344}
8345
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008346/* This function change the nice of the currently executed
8347 * task. It is used set low or high priority at the current
8348 * task.
8349 */
Willy Tarreau59551662015-03-10 14:23:13 +01008350__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008351{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008352 struct hlua *hlua;
8353 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008354
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008355 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008356 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008357
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008358 /* Get hlua struct, or NULL if we execute from main lua state */
8359 hlua = hlua_gethlua(L);
8360
8361 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008362 if (!hlua || !hlua->task)
8363 return 0;
8364
8365 if (nice < -1024)
8366 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008367 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008368 nice = 1024;
8369
8370 hlua->task->nice = nice;
8371 return 0;
8372}
8373
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008374/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008375 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8376 * return an E_AGAIN signal, the emmiter of this signal must set a
8377 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008378 *
8379 * Task wrapper are longjmp safe because the only one Lua code
8380 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008381 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008382struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008383{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008384 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008385 enum hlua_exec status;
8386
Christopher Faulet5bc99722018-04-25 10:34:45 +02008387 if (task->thread_mask == MAX_THREADS_MASK)
8388 task_set_affinity(task, tid_bit);
8389
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008390 /* If it is the first call to the task, we must initialize the
8391 * execution timeouts.
8392 */
8393 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008394 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008395
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008396 /* Execute the Lua code. */
8397 status = hlua_ctx_resume(hlua, 1);
8398
8399 switch (status) {
8400 /* finished or yield */
8401 case HLUA_E_OK:
8402 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008403 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008404 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008405 break;
8406
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008407 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008408 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008409 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008410 break;
8411
8412 /* finished with error. */
8413 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008414 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008415 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008416 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008417 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008418 break;
8419
8420 case HLUA_E_ERR:
8421 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008422 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008423 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008424 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008425 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008426 break;
8427 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008428 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008429}
8430
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008431/* This function is an LUA binding that register LUA function to be
8432 * executed after the HAProxy configuration parsing and before the
8433 * HAProxy scheduler starts. This function expect only one LUA
8434 * argument that is a function. This function returns nothing, but
8435 * throws if an error is encountered.
8436 */
8437__LJMP static int hlua_register_init(lua_State *L)
8438{
8439 struct hlua_init_function *init;
8440 int ref;
8441
8442 MAY_LJMP(check_args(L, 1, "register_init"));
8443
8444 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8445
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008446 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008447 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008448 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008449
8450 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008451 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008452 return 0;
8453}
8454
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008455/* This functio is an LUA binding. It permits to register a task
8456 * executed in parallel of the main HAroxy activity. The task is
8457 * created and it is set in the HAProxy scheduler. It can be called
8458 * from the "init" section, "post init" or during the runtime.
8459 *
8460 * Lua prototype:
8461 *
8462 * <none> core.register_task(<function>)
8463 */
8464static int hlua_register_task(lua_State *L)
8465{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008466 struct hlua *hlua = NULL;
8467 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008468 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008469 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008470
8471 MAY_LJMP(check_args(L, 1, "register_task"));
8472
8473 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8474
Thierry Fournier75fc0292020-11-28 13:18:56 +01008475 /* Get the reference state. If the reference is NULL, L is the master
8476 * state, otherwise hlua->T is.
8477 */
8478 hlua = hlua_gethlua(L);
8479 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008480 /* we are in runtime processing */
8481 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008482 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008483 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008484 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008485
Willy Tarreaubafbe012017-11-24 17:34:44 +01008486 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008487 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008488 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008489 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008490
Thierry Fournier59f11be2020-11-29 00:37:41 +01008491 /* We are in the common lua state, execute the task anywhere,
8492 * otherwise, inherit the current thread identifier
8493 */
8494 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008495 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008496 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008497 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008498 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008499 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008500
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008501 task->context = hlua;
8502 task->process = hlua_process_task;
8503
Thierry Fournier021d9862020-11-28 23:42:03 +01008504 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008505 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008506
8507 /* Restore the function in the stack. */
8508 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8509 hlua->nargs = 0;
8510
8511 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008512 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008513
8514 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008515
8516 alloc_error:
8517 task_destroy(task);
8518 hlua_ctx_destroy(hlua);
8519 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8520 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008521}
8522
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008523/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8524 * doesn't allow "yield" functions because the HAProxy engine cannot
8525 * resume converters.
8526 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008527static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008528{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008529 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008530 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008531 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008532
Willy Tarreaube508f12016-03-10 11:47:01 +01008533 if (!stream)
8534 return 0;
8535
Willy Tarreau87b09662015-04-03 00:22:06 +02008536 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008537 * Lua context can be not initialized. This behavior
8538 * permits to save performances because a systematic
8539 * Lua initialization cause 5% performances loss.
8540 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008541 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008542 struct hlua *hlua;
8543
8544 hlua = pool_alloc(pool_head_hlua);
8545 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008546 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8547 return 0;
8548 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008549 HLUA_INIT(hlua);
8550 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008551 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008552 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8553 return 0;
8554 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008555 }
8556
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008557 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008558 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008559
8560 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008561 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008562 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8563 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008564 else
8565 error = "critical error";
8566 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008567 return 0;
8568 }
8569
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008570 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008571 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008572 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008573 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008574 return 0;
8575 }
8576
8577 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008578 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008579
8580 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008581 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008582 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008583 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008584 return 0;
8585 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008586 hlua_smp2lua(stream->hlua->T, smp);
8587 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008588
8589 /* push keywords in the stack. */
8590 if (arg_p) {
8591 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008592 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008593 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008594 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008595 return 0;
8596 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008597 hlua_arg2lua(stream->hlua->T, arg_p);
8598 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008599 }
8600 }
8601
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008602 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008603 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008604
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008605 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008606 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008607 }
8608
8609 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008610 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008611 /* finished. */
8612 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008613 /* If the stack is empty, the function fails. */
8614 if (lua_gettop(stream->hlua->T) <= 0)
8615 return 0;
8616
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008617 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008618 hlua_lua2smp(stream->hlua->T, -1, smp);
8619 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008620 return 1;
8621
8622 /* yield. */
8623 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008624 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008625 return 0;
8626
8627 /* finished with error. */
8628 case HLUA_E_ERRMSG:
8629 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008630 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008631 fcn->name, lua_tostring(stream->hlua->T, -1));
8632 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008633 return 0;
8634
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008635 case HLUA_E_ETMOUT:
8636 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8637 return 0;
8638
8639 case HLUA_E_NOMEM:
8640 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8641 return 0;
8642
8643 case HLUA_E_YIELD:
8644 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8645 return 0;
8646
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008647 case HLUA_E_ERR:
8648 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008649 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008650 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008651
8652 default:
8653 return 0;
8654 }
8655}
8656
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008657/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8658 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008659 * resume sample-fetches. This function will be called by the sample
8660 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008661 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008662static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8663 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008664{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008665 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008666 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008667 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008668 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008669
Willy Tarreaube508f12016-03-10 11:47:01 +01008670 if (!stream)
8671 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008672
Willy Tarreau87b09662015-04-03 00:22:06 +02008673 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008674 * Lua context can be not initialized. This behavior
8675 * permits to save performances because a systematic
8676 * Lua initialization cause 5% performances loss.
8677 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008678 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008679 struct hlua *hlua;
8680
8681 hlua = pool_alloc(pool_head_hlua);
8682 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008683 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8684 return 0;
8685 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008686 hlua->T = NULL;
8687 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008688 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008689 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8690 return 0;
8691 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008692 }
8693
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008694 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008695 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008696
8697 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008698 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008699 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8700 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008701 else
8702 error = "critical error";
8703 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008704 return 0;
8705 }
8706
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008707 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008708 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008709 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008710 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008711 return 0;
8712 }
8713
8714 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008715 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008716
8717 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008718 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008719 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008720 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008721 return 0;
8722 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008723 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008724
8725 /* push keywords in the stack. */
8726 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8727 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008728 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008729 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008730 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008731 return 0;
8732 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008733 hlua_arg2lua(stream->hlua->T, arg_p);
8734 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008735 }
8736
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008737 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008738 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008739
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008740 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008741 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008742 }
8743
8744 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008745 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008746 /* finished. */
8747 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008748 /* If the stack is empty, the function fails. */
8749 if (lua_gettop(stream->hlua->T) <= 0)
8750 return 0;
8751
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008752 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008753 hlua_lua2smp(stream->hlua->T, -1, smp);
8754 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008755
8756 /* Set the end of execution flag. */
8757 smp->flags &= ~SMP_F_MAY_CHANGE;
8758 return 1;
8759
8760 /* yield. */
8761 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008762 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008763 return 0;
8764
8765 /* finished with error. */
8766 case HLUA_E_ERRMSG:
8767 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008768 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008769 fcn->name, lua_tostring(stream->hlua->T, -1));
8770 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008771 return 0;
8772
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008773 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008774 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8775 return 0;
8776
8777 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008778 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8779 return 0;
8780
8781 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008782 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8783 return 0;
8784
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008785 case HLUA_E_ERR:
8786 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008787 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008788 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008789
8790 default:
8791 return 0;
8792 }
8793}
8794
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008795/* This function is an LUA binding used for registering
8796 * "sample-conv" functions. It expects a converter name used
8797 * in the haproxy configuration file, and an LUA function.
8798 */
8799__LJMP static int hlua_register_converters(lua_State *L)
8800{
8801 struct sample_conv_kw_list *sck;
8802 const char *name;
8803 int ref;
8804 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008805 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008806 struct sample_conv *sc;
8807 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008808
8809 MAY_LJMP(check_args(L, 2, "register_converters"));
8810
8811 /* First argument : converter name. */
8812 name = MAY_LJMP(luaL_checkstring(L, 1));
8813
8814 /* Second argument : lua function. */
8815 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8816
Thierry Fournierf67442e2020-11-28 20:41:07 +01008817 /* Check if the converter is already registered */
8818 trash = get_trash_chunk();
8819 chunk_printf(trash, "lua.%s", name);
8820 sc = find_sample_conv(trash->area, trash->data);
8821 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008822 fcn = sc->private;
8823 if (fcn->function_ref[hlua_state_id] != -1) {
8824 ha_warning("Trying to register converter 'lua.%s' more than once. "
8825 "This will become a hard error in version 2.5.\n", name);
8826 }
8827 fcn->function_ref[hlua_state_id] = ref;
8828 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008829 }
8830
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008831 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008832 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008833 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008834 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008835 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008836 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008837 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008838
8839 /* Fill fcn. */
8840 fcn->name = strdup(name);
8841 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008842 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008843 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008844
8845 /* List head */
8846 sck->list.n = sck->list.p = NULL;
8847
8848 /* converter keyword. */
8849 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008850 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008851 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008852 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008853
8854 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8855 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008856 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 +01008857 sck->kw[0].val_args = NULL;
8858 sck->kw[0].in_type = SMP_T_STR;
8859 sck->kw[0].out_type = SMP_T_STR;
8860 sck->kw[0].private = fcn;
8861
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008862 /* Register this new converter */
8863 sample_register_convs(sck);
8864
8865 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008866
8867 alloc_error:
8868 release_hlua_function(fcn);
8869 ha_free(&sck);
8870 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8871 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008872}
8873
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008874/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008875 * "sample-fetch" functions. It expects a converter name used
8876 * in the haproxy configuration file, and an LUA function.
8877 */
8878__LJMP static int hlua_register_fetches(lua_State *L)
8879{
8880 const char *name;
8881 int ref;
8882 int len;
8883 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008884 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008885 struct sample_fetch *sf;
8886 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008887
8888 MAY_LJMP(check_args(L, 2, "register_fetches"));
8889
8890 /* First argument : sample-fetch name. */
8891 name = MAY_LJMP(luaL_checkstring(L, 1));
8892
8893 /* Second argument : lua function. */
8894 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8895
Thierry Fournierf67442e2020-11-28 20:41:07 +01008896 /* Check if the sample-fetch is already registered */
8897 trash = get_trash_chunk();
8898 chunk_printf(trash, "lua.%s", name);
8899 sf = find_sample_fetch(trash->area, trash->data);
8900 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008901 fcn = sf->private;
8902 if (fcn->function_ref[hlua_state_id] != -1) {
8903 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8904 "This will become a hard error in version 2.5.\n", name);
8905 }
8906 fcn->function_ref[hlua_state_id] = ref;
8907 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008908 }
8909
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008910 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008911 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008912 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008913 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008914 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008915 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008916 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008917
8918 /* Fill fcn. */
8919 fcn->name = strdup(name);
8920 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008921 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008922 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008923
8924 /* List head */
8925 sfk->list.n = sfk->list.p = NULL;
8926
8927 /* sample-fetch keyword. */
8928 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008929 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008930 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008931 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008932
8933 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8934 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008935 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 +01008936 sfk->kw[0].val_args = NULL;
8937 sfk->kw[0].out_type = SMP_T_STR;
8938 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8939 sfk->kw[0].val = 0;
8940 sfk->kw[0].private = fcn;
8941
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008942 /* Register this new fetch. */
8943 sample_register_fetches(sfk);
8944
8945 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008946
8947 alloc_error:
8948 release_hlua_function(fcn);
8949 ha_free(&sfk);
8950 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8951 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008952}
8953
Christopher Faulet501465d2020-02-26 14:54:16 +01008954/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008955 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008956__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008957{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008958 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008959 unsigned int delay;
8960 unsigned int wakeup_ms;
8961
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008962 /* Get hlua struct, or NULL if we execute from main lua state */
8963 hlua = hlua_gethlua(L);
8964 if (!hlua) {
8965 return 0;
8966 }
8967
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008968 MAY_LJMP(check_args(L, 1, "wake_time"));
8969
8970 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8971 wakeup_ms = tick_add(now_ms, delay);
8972 hlua->wake_time = wakeup_ms;
8973 return 0;
8974}
8975
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008976/* This function is a wrapper to execute each LUA function declared as an action
8977 * wrapper during the initialisation period. This function may return any
8978 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8979 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8980 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008981 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008982static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02008983 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008984{
8985 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008986 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008987 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008988 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008989
8990 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008991 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
8992 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
8993 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
8994 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008995 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008996 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008997 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008998 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008999
Willy Tarreau87b09662015-04-03 00:22:06 +02009000 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009001 * Lua context can be not initialized. This behavior
9002 * permits to save performances because a systematic
9003 * Lua initialization cause 5% performances loss.
9004 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009005 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009006 struct hlua *hlua;
9007
9008 hlua = pool_alloc(pool_head_hlua);
9009 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009010 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009011 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009012 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009013 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009014 HLUA_INIT(hlua);
9015 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009016 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 +01009017 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009018 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009019 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009020 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009021 }
9022
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009023 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009024 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009025
9026 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009027 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009028 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9029 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009030 else
9031 error = "critical error";
9032 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009033 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009034 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009035 }
9036
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009037 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009038 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009039 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009040 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009041 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009042 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009043 }
9044
9045 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009046 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 +01009047
Willy Tarreau87b09662015-04-03 00:22:06 +02009048 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009049 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009050 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009051 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009052 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009053 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009054 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009055 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009056
9057 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009058 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009059 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009060 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009061 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009062 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009063 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009064 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009065 lua_pushstring(s->hlua->T, *arg);
9066 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009067 }
9068
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009069 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009070 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009071
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009072 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009073 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009074 }
9075
9076 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009077 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009078 /* finished. */
9079 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009080 /* Catch the return value */
9081 if (lua_gettop(s->hlua->T) > 0)
9082 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009083
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009084 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009085 if (act_ret == ACT_RET_YIELD) {
9086 if (flags & ACT_OPT_FINAL)
9087 goto err_yield;
9088
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009089 if (dir == SMP_OPT_DIR_REQ)
9090 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9091 s->hlua->wake_time);
9092 else
9093 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9094 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009095 }
9096 goto end;
9097
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009098 /* yield. */
9099 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009100 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009101 if (dir == SMP_OPT_DIR_REQ)
9102 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9103 s->hlua->wake_time);
9104 else
9105 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9106 s->hlua->wake_time);
9107
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009108 /* Some actions can be wake up when a "write" event
9109 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009110 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009111 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009112 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009113 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009114 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009115 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009116 act_ret = ACT_RET_YIELD;
9117 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009118
9119 /* finished with error. */
9120 case HLUA_E_ERRMSG:
9121 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009122 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009123 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009124 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009125 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009126
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009127 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009128 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009129 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009130
9131 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009132 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009133 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009134
9135 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009136 err_yield:
9137 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009138 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009139 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009140 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009141
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009142 case HLUA_E_ERR:
9143 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009144 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009145 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009146
9147 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009148 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009149 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009150
9151 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009152 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009153 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009154 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009155}
9156
Willy Tarreau144f84a2021-03-02 16:09:26 +01009157struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009158{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009159 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009160
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009161 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009162 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009163 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009164}
9165
9166static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
9167{
9168 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009169 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009170 struct task *task;
9171 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009172 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009173
Willy Tarreaubafbe012017-11-24 17:34:44 +01009174 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009175 if (!hlua) {
9176 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009177 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009178 return 0;
9179 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009180 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009181 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009182 ctx->ctx.hlua_apptcp.flags = 0;
9183
9184 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009185 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009186 if (!task) {
9187 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009188 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009189 return 0;
9190 }
9191 task->nice = 0;
9192 task->context = ctx;
9193 task->process = hlua_applet_wakeup;
9194 ctx->ctx.hlua_apptcp.task = task;
9195
9196 /* In the execution wrappers linked with a stream, the
9197 * Lua context can be not initialized. This behavior
9198 * permits to save performances because a systematic
9199 * Lua initialization cause 5% performances loss.
9200 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009201 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 +02009202 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009203 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009204 return 0;
9205 }
9206
9207 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009208 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009209
9210 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009211 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009212 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9213 error = lua_tostring(hlua->T, -1);
9214 else
9215 error = "critical error";
9216 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009217 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009218 return 0;
9219 }
9220
9221 /* Check stack available size. */
9222 if (!lua_checkstack(hlua->T, 1)) {
9223 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009224 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009225 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009226 return 0;
9227 }
9228
9229 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009230 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009231
9232 /* Create and and push object stream in the stack. */
9233 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
9234 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009235 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009236 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009237 return 0;
9238 }
9239 hlua->nargs = 1;
9240
9241 /* push keywords in the stack. */
9242 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9243 if (!lua_checkstack(hlua->T, 1)) {
9244 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009245 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009246 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009247 return 0;
9248 }
9249 lua_pushstring(hlua->T, *arg);
9250 hlua->nargs++;
9251 }
9252
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009253 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009254
9255 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009256 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01009257 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009258
9259 return 1;
9260}
9261
Willy Tarreau60409db2019-08-21 14:14:50 +02009262void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009263{
9264 struct stream_interface *si = ctx->owner;
9265 struct stream *strm = si_strm(si);
9266 struct channel *res = si_ic(si);
9267 struct act_rule *rule = ctx->rule;
9268 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009269 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009270
9271 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02009272 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
9273 /* eat the whole request */
9274 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009275 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009276 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009277
9278 /* If the stream is disconnect or closed, ldo nothing. */
9279 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9280 return;
9281
9282 /* Execute the function. */
9283 switch (hlua_ctx_resume(hlua, 1)) {
9284 /* finished. */
9285 case HLUA_E_OK:
9286 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9287
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009288 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02009289 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009290 res->flags |= CF_READ_NULL;
9291 si_shutr(si);
9292 return;
9293
9294 /* yield. */
9295 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009296 if (hlua->wake_time != TICK_ETERNITY)
9297 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009298 return;
9299
9300 /* finished with error. */
9301 case HLUA_E_ERRMSG:
9302 /* Display log. */
9303 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009304 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009305 lua_pop(hlua->T, 1);
9306 goto error;
9307
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009308 case HLUA_E_ETMOUT:
9309 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009310 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009311 goto error;
9312
9313 case HLUA_E_NOMEM:
9314 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009315 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009316 goto error;
9317
9318 case HLUA_E_YIELD: /* unexpected */
9319 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009320 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009321 goto error;
9322
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009323 case HLUA_E_ERR:
9324 /* Display log. */
9325 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009326 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009327 goto error;
9328
9329 default:
9330 goto error;
9331 }
9332
9333error:
9334
9335 /* For all other cases, just close the stream. */
9336 si_shutw(si);
9337 si_shutr(si);
9338 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9339}
9340
9341static void hlua_applet_tcp_release(struct appctx *ctx)
9342{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009343 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009344 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009345 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009346 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009347}
9348
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009349/* The function returns 1 if the initialisation is complete, 0 if
9350 * an errors occurs and -1 if more data are required for initializing
9351 * the applet.
9352 */
9353static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
9354{
9355 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009356 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009357 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009358 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009359 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009360 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009361
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009362 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009363 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009364 if (!hlua) {
9365 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009366 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009367 return 0;
9368 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009369 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009370 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009371 ctx->ctx.hlua_apphttp.left_bytes = -1;
9372 ctx->ctx.hlua_apphttp.flags = 0;
9373
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009374 if (txn->req.flags & HTTP_MSGF_VER_11)
9375 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
9376
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009377 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009378 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009379 if (!task) {
9380 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009381 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009382 return 0;
9383 }
9384 task->nice = 0;
9385 task->context = ctx;
9386 task->process = hlua_applet_wakeup;
9387 ctx->ctx.hlua_apphttp.task = task;
9388
9389 /* In the execution wrappers linked with a stream, the
9390 * Lua context can be not initialized. This behavior
9391 * permits to save performances because a systematic
9392 * Lua initialization cause 5% performances loss.
9393 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009394 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 +02009395 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009396 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009397 return 0;
9398 }
9399
9400 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009401 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009402
9403 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009404 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009405 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9406 error = lua_tostring(hlua->T, -1);
9407 else
9408 error = "critical error";
9409 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009410 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009411 return 0;
9412 }
9413
9414 /* Check stack available size. */
9415 if (!lua_checkstack(hlua->T, 1)) {
9416 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009417 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009418 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009419 return 0;
9420 }
9421
9422 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009423 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009424
9425 /* Create and and push object stream in the stack. */
9426 if (!hlua_applet_http_new(hlua->T, ctx)) {
9427 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009428 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009429 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009430 return 0;
9431 }
9432 hlua->nargs = 1;
9433
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009434 /* push keywords in the stack. */
9435 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9436 if (!lua_checkstack(hlua->T, 1)) {
9437 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009438 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009439 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009440 return 0;
9441 }
9442 lua_pushstring(hlua->T, *arg);
9443 hlua->nargs++;
9444 }
9445
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009446 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009447
9448 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009449 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009450
9451 return 1;
9452}
9453
Willy Tarreau60409db2019-08-21 14:14:50 +02009454void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009455{
9456 struct stream_interface *si = ctx->owner;
9457 struct stream *strm = si_strm(si);
9458 struct channel *req = si_oc(si);
9459 struct channel *res = si_ic(si);
9460 struct act_rule *rule = ctx->rule;
9461 struct proxy *px = strm->be;
9462 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
9463 struct htx *req_htx, *res_htx;
9464
9465 res_htx = htx_from_buf(&res->buf);
9466
9467 /* If the stream is disconnect or closed, ldo nothing. */
9468 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9469 goto out;
9470
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009471 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009472 if (!b_size(&res->buf)) {
9473 si_rx_room_blk(si);
9474 goto out;
9475 }
9476 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009477 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009478 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9479
9480 /* Set the currently running flag. */
9481 if (!HLUA_IS_RUNNING(hlua) &&
9482 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009483 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009484 si_cant_get(si);
9485 goto out;
9486 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009487 }
9488
9489 /* Executes The applet if it is not done. */
9490 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9491
9492 /* Execute the function. */
9493 switch (hlua_ctx_resume(hlua, 1)) {
9494 /* finished. */
9495 case HLUA_E_OK:
9496 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9497 break;
9498
9499 /* yield. */
9500 case HLUA_E_AGAIN:
9501 if (hlua->wake_time != TICK_ETERNITY)
9502 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009503 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009504
9505 /* finished with error. */
9506 case HLUA_E_ERRMSG:
9507 /* Display log. */
9508 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009509 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009510 lua_pop(hlua->T, 1);
9511 goto error;
9512
9513 case HLUA_E_ETMOUT:
9514 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009515 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009516 goto error;
9517
9518 case HLUA_E_NOMEM:
9519 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009520 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009521 goto error;
9522
9523 case HLUA_E_YIELD: /* unexpected */
9524 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009525 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009526 goto error;
9527
9528 case HLUA_E_ERR:
9529 /* Display log. */
9530 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009531 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009532 goto error;
9533
9534 default:
9535 goto error;
9536 }
9537 }
9538
9539 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009540 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9541 goto done;
9542
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009543 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9544 goto error;
9545
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009546 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
9547 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009548 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9549 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009550 }
9551
9552 done:
9553 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009554 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009555 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009556 si_shutr(si);
9557 }
9558
9559 /* eat the whole request */
9560 if (co_data(req)) {
9561 req_htx = htx_from_buf(&req->buf);
9562 co_htx_skip(req, req_htx, co_data(req));
9563 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009564 }
9565 }
9566
9567 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009568 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009569 return;
9570
9571 error:
9572
9573 /* If we are in HTTP mode, and we are not send any
9574 * data, return a 500 server error in best effort:
9575 * if there is no room available in the buffer,
9576 * just close the connection.
9577 */
9578 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009579 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009580
9581 channel_erase(res);
9582 res->buf.data = b_data(err);
9583 memcpy(res->buf.area, b_head(err), b_data(err));
9584 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009585 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009586 }
9587 if (!(strm->flags & SF_ERR_MASK))
9588 strm->flags |= SF_ERR_RESOURCE;
9589 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9590 goto done;
9591}
9592
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009593static void hlua_applet_http_release(struct appctx *ctx)
9594{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009595 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009596 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009597 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009598 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009599}
9600
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009601/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009602 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009603 *
9604 * This function can fail with an abort() due to an Lua critical error.
9605 * We are in the configuration parsing process of HAProxy, this abort() is
9606 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009607 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009608static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9609 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009610{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009611 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009612 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009613
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009614 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009615 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009616 if (!rule->arg.hlua_rule) {
9617 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009618 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009619 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009620
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009621 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009622 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9623 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009624 if (!rule->arg.hlua_rule->args) {
9625 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009626 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009627 }
9628
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009629 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009630 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009631
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009632 /* Expect some arguments */
9633 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009634 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009635 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009636 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009637 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009638 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009639 if (!rule->arg.hlua_rule->args[i]) {
9640 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009641 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009642 }
9643 (*cur_arg)++;
9644 }
9645 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009646
Thierry FOURNIER42148732015-09-02 17:17:33 +02009647 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009648 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009649 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009650
9651 error:
9652 if (rule->arg.hlua_rule) {
9653 if (rule->arg.hlua_rule->args) {
9654 for (i = 0; i < fcn->nargs; i++)
9655 ha_free(&rule->arg.hlua_rule->args[i]);
9656 ha_free(&rule->arg.hlua_rule->args);
9657 }
9658 ha_free(&rule->arg.hlua_rule);
9659 }
9660 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009661}
9662
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009663static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9664 struct act_rule *rule, char **err)
9665{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009666 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009667
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009668 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009669 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009670 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009671 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009672 * the call of this analyzer.
9673 */
9674 if (rule->from != ACT_F_HTTP_REQ) {
9675 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9676 return ACT_RET_PRS_ERR;
9677 }
9678
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009679 /* Memory for the rule. */
9680 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9681 if (!rule->arg.hlua_rule) {
9682 memprintf(err, "out of memory error");
9683 return ACT_RET_PRS_ERR;
9684 }
9685
9686 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009687 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009688
9689 /* TODO: later accept arguments. */
9690 rule->arg.hlua_rule->args = NULL;
9691
9692 /* Add applet pointer in the rule. */
9693 rule->applet.obj_type = OBJ_TYPE_APPLET;
9694 rule->applet.name = fcn->name;
9695 rule->applet.init = hlua_applet_http_init;
9696 rule->applet.fct = hlua_applet_http_fct;
9697 rule->applet.release = hlua_applet_http_release;
9698 rule->applet.timeout = hlua_timeout_applet;
9699
9700 return ACT_RET_PRS_OK;
9701}
9702
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009703/* This function is an LUA binding used for registering
9704 * "sample-conv" functions. It expects a converter name used
9705 * in the haproxy configuration file, and an LUA function.
9706 */
9707__LJMP static int hlua_register_action(lua_State *L)
9708{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009709 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009710 const char *name;
9711 int ref;
9712 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009713 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009714 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009715 struct buffer *trash;
9716 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009717
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009718 /* Initialise the number of expected arguments at 0. */
9719 nargs = 0;
9720
9721 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9722 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009723
9724 /* First argument : converter name. */
9725 name = MAY_LJMP(luaL_checkstring(L, 1));
9726
9727 /* Second argument : environment. */
9728 if (lua_type(L, 2) != LUA_TTABLE)
9729 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9730
9731 /* Third argument : lua function. */
9732 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9733
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009734 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009735 if (lua_gettop(L) >= 4)
9736 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9737
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009738 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009739 lua_pushnil(L);
9740 while (lua_next(L, 2) != 0) {
9741 if (lua_type(L, -1) != LUA_TSTRING)
9742 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9743
Thierry Fournierf67442e2020-11-28 20:41:07 +01009744 /* Check if action exists */
9745 trash = get_trash_chunk();
9746 chunk_printf(trash, "lua.%s", name);
9747 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9748 akw = tcp_req_cont_action(trash->area);
9749 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9750 akw = tcp_res_cont_action(trash->area);
9751 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9752 akw = action_http_req_custom(trash->area);
9753 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9754 akw = action_http_res_custom(trash->area);
9755 } else {
9756 akw = NULL;
9757 }
9758 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009759 fcn = akw->private;
9760 if (fcn->function_ref[hlua_state_id] != -1) {
9761 ha_warning("Trying to register action 'lua.%s' more than once. "
9762 "This will become a hard error in version 2.5.\n", name);
9763 }
9764 fcn->function_ref[hlua_state_id] = ref;
9765
9766 /* pop the environment string. */
9767 lua_pop(L, 1);
9768 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009769 }
9770
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009771 /* Check required environment. Only accepted "http" or "tcp". */
9772 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009773 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009774 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009775 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009776 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009777 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009778 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009779
9780 /* Fill fcn. */
9781 fcn->name = strdup(name);
9782 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009783 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009784 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009785
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009786 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009787 fcn->nargs = nargs;
9788
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009789 /* List head */
9790 akl->list.n = akl->list.p = NULL;
9791
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009792 /* action keyword. */
9793 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009794 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009795 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009796 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009797
9798 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9799
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009800 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009801 akl->kw[0].private = fcn;
9802 akl->kw[0].parse = action_register_lua;
9803
9804 /* select the action registering point. */
9805 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9806 tcp_req_cont_keywords_register(akl);
9807 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9808 tcp_res_cont_keywords_register(akl);
9809 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9810 http_req_keywords_register(akl);
9811 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9812 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009813 else {
9814 release_hlua_function(fcn);
9815 if (akl)
9816 ha_free((char **)&(akl->kw[0].kw));
9817 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009818 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009819 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9820 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009821 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009822
9823 /* pop the environment string. */
9824 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009825
9826 /* reset for next loop */
9827 akl = NULL;
9828 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009829 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009830 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009831
9832 alloc_error:
9833 release_hlua_function(fcn);
9834 ha_free(&akl);
9835 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9836 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009837}
9838
9839static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9840 struct act_rule *rule, char **err)
9841{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009842 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009843
Christopher Faulet280f85b2019-07-15 15:02:04 +02009844 if (px->mode == PR_MODE_HTTP) {
9845 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009846 return ACT_RET_PRS_ERR;
9847 }
9848
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009849 /* Memory for the rule. */
9850 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9851 if (!rule->arg.hlua_rule) {
9852 memprintf(err, "out of memory error");
9853 return ACT_RET_PRS_ERR;
9854 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009855
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009856 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009857 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009858
9859 /* TODO: later accept arguments. */
9860 rule->arg.hlua_rule->args = NULL;
9861
9862 /* Add applet pointer in the rule. */
9863 rule->applet.obj_type = OBJ_TYPE_APPLET;
9864 rule->applet.name = fcn->name;
9865 rule->applet.init = hlua_applet_tcp_init;
9866 rule->applet.fct = hlua_applet_tcp_fct;
9867 rule->applet.release = hlua_applet_tcp_release;
9868 rule->applet.timeout = hlua_timeout_applet;
9869
9870 return 0;
9871}
9872
9873/* This function is an LUA binding used for registering
9874 * "sample-conv" functions. It expects a converter name used
9875 * in the haproxy configuration file, and an LUA function.
9876 */
9877__LJMP static int hlua_register_service(lua_State *L)
9878{
9879 struct action_kw_list *akl;
9880 const char *name;
9881 const char *env;
9882 int ref;
9883 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009884 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009885 struct buffer *trash;
9886 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009887
9888 MAY_LJMP(check_args(L, 3, "register_service"));
9889
9890 /* First argument : converter name. */
9891 name = MAY_LJMP(luaL_checkstring(L, 1));
9892
9893 /* Second argument : environment. */
9894 env = MAY_LJMP(luaL_checkstring(L, 2));
9895
9896 /* Third argument : lua function. */
9897 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9898
Thierry Fournierf67442e2020-11-28 20:41:07 +01009899 /* Check for service already registered */
9900 trash = get_trash_chunk();
9901 chunk_printf(trash, "lua.%s", name);
9902 akw = service_find(trash->area);
9903 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009904 fcn = akw->private;
9905 if (fcn->function_ref[hlua_state_id] != -1) {
9906 ha_warning("Trying to register service 'lua.%s' more than once. "
9907 "This will become a hard error in version 2.5.\n", name);
9908 }
9909 fcn->function_ref[hlua_state_id] = ref;
9910 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009911 }
9912
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009913 /* Allocate and fill the sample fetch keyword struct. */
9914 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9915 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009916 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009917 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009918 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009919 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009920
9921 /* Fill fcn. */
9922 len = strlen("<lua.>") + strlen(name) + 1;
9923 fcn->name = calloc(1, len);
9924 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009925 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009926 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009927 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009928
9929 /* List head */
9930 akl->list.n = akl->list.p = NULL;
9931
9932 /* converter keyword. */
9933 len = strlen("lua.") + strlen(name) + 1;
9934 akl->kw[0].kw = calloc(1, len);
9935 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009936 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009937
9938 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9939
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009940 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009941 if (strcmp(env, "tcp") == 0)
9942 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009943 else if (strcmp(env, "http") == 0)
9944 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009945 else {
9946 release_hlua_function(fcn);
9947 if (akl)
9948 ha_free((char **)&(akl->kw[0].kw));
9949 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009950 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009951 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009952 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009953
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009954 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009955 akl->kw[0].private = fcn;
9956
9957 /* End of array. */
9958 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9959
9960 /* Register this new converter */
9961 service_keywords_register(akl);
9962
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009963 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009964
9965 alloc_error:
9966 release_hlua_function(fcn);
9967 ha_free(&akl);
9968 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9969 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009970}
9971
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009972/* This function initialises Lua cli handler. It copies the
9973 * arguments in the Lua stack and create channel IO objects.
9974 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02009975static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009976{
9977 struct hlua *hlua;
9978 struct hlua_function *fcn;
9979 int i;
9980 const char *error;
9981
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009982 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009983 appctx->ctx.hlua_cli.fcn = private;
9984
Willy Tarreaubafbe012017-11-24 17:34:44 +01009985 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009986 if (!hlua) {
9987 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009988 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009989 }
9990 HLUA_INIT(hlua);
9991 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009992
9993 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05009994 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009995 * applet_http. It is absolutely compatible.
9996 */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009997 appctx->ctx.hlua_cli.task = task_new_here();
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009998 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01009999 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010000 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010001 }
10002 appctx->ctx.hlua_cli.task->nice = 0;
10003 appctx->ctx.hlua_cli.task->context = appctx;
10004 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
10005
10006 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +010010007 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 +010010008 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010009 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010010 }
10011
10012 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010013 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010014 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10015 error = lua_tostring(hlua->T, -1);
10016 else
10017 error = "critical error";
10018 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10019 goto error;
10020 }
10021
10022 /* Check stack available size. */
10023 if (!lua_checkstack(hlua->T, 2)) {
10024 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10025 goto error;
10026 }
10027
10028 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010029 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010030
10031 /* Once the arguments parsed, the CLI is like an AppletTCP,
10032 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010033 */
10034 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10035 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10036 goto error;
10037 }
10038 hlua->nargs = 1;
10039
10040 /* push keywords in the stack. */
10041 for (i = 0; *args[i]; i++) {
10042 /* Check stack available size. */
10043 if (!lua_checkstack(hlua->T, 1)) {
10044 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10045 goto error;
10046 }
10047 lua_pushstring(hlua->T, args[i]);
10048 hlua->nargs++;
10049 }
10050
10051 /* We must initialize the execution timeouts. */
10052 hlua->max_time = hlua_timeout_session;
10053
10054 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010055 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010056
10057 /* It's ok */
10058 return 0;
10059
10060 /* It's not ok. */
10061error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010062 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010063 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010064 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010065 return 1;
10066}
10067
10068static int hlua_cli_io_handler_fct(struct appctx *appctx)
10069{
10070 struct hlua *hlua;
10071 struct stream_interface *si;
10072 struct hlua_function *fcn;
10073
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010074 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010075 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +010010076 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010077
10078 /* If the stream is disconnect or closed, ldo nothing. */
10079 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
10080 return 1;
10081
10082 /* Execute the function. */
10083 switch (hlua_ctx_resume(hlua, 1)) {
10084
10085 /* finished. */
10086 case HLUA_E_OK:
10087 return 1;
10088
10089 /* yield. */
10090 case HLUA_E_AGAIN:
10091 /* We want write. */
10092 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +010010093 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010094 /* Set the timeout. */
10095 if (hlua->wake_time != TICK_ETERNITY)
10096 task_schedule(hlua->task, hlua->wake_time);
10097 return 0;
10098
10099 /* finished with error. */
10100 case HLUA_E_ERRMSG:
10101 /* Display log. */
10102 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10103 fcn->name, lua_tostring(hlua->T, -1));
10104 lua_pop(hlua->T, 1);
10105 return 1;
10106
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010107 case HLUA_E_ETMOUT:
10108 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10109 fcn->name);
10110 return 1;
10111
10112 case HLUA_E_NOMEM:
10113 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10114 fcn->name);
10115 return 1;
10116
10117 case HLUA_E_YIELD: /* unexpected */
10118 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10119 fcn->name);
10120 return 1;
10121
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010122 case HLUA_E_ERR:
10123 /* Display log. */
10124 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10125 fcn->name);
10126 return 1;
10127
10128 default:
10129 return 1;
10130 }
10131
10132 return 1;
10133}
10134
10135static void hlua_cli_io_release_fct(struct appctx *appctx)
10136{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010137 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010138 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010139}
10140
10141/* This function is an LUA binding used for registering
10142 * new keywords in the cli. It expects a list of keywords
10143 * which are the "path". It is limited to 5 keywords. A
10144 * description of the command, a function to be executed
10145 * for the parsing and a function for io handlers.
10146 */
10147__LJMP static int hlua_register_cli(lua_State *L)
10148{
10149 struct cli_kw_list *cli_kws;
10150 const char *message;
10151 int ref_io;
10152 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010153 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010154 int index;
10155 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010156 struct buffer *trash;
10157 const char *kw[5];
10158 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010159 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010160
10161 MAY_LJMP(check_args(L, 3, "register_cli"));
10162
10163 /* First argument : an array of maximum 5 keywords. */
10164 if (!lua_istable(L, 1))
10165 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10166
10167 /* Second argument : string with contextual message. */
10168 message = MAY_LJMP(luaL_checkstring(L, 2));
10169
10170 /* Third and fourth argument : lua function. */
10171 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10172
Thierry Fournierf67442e2020-11-28 20:41:07 +010010173 /* Check for CLI service already registered */
10174 trash = get_trash_chunk();
10175 index = 0;
10176 lua_pushnil(L);
10177 memset(kw, 0, sizeof(kw));
10178 while (lua_next(L, 1) != 0) {
10179 if (index >= CLI_PREFIX_KW_NB)
10180 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10181 if (lua_type(L, -1) != LUA_TSTRING)
10182 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10183 kw[index] = lua_tostring(L, -1);
10184 if (index == 0)
10185 chunk_printf(trash, "%s", kw[index]);
10186 else
10187 chunk_appendf(trash, " %s", kw[index]);
10188 index++;
10189 lua_pop(L, 1);
10190 }
10191 cli_kw = cli_find_kw_exact((char **)kw);
10192 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010193 fcn = cli_kw->private;
10194 if (fcn->function_ref[hlua_state_id] != -1) {
10195 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10196 "This will become a hard error in version 2.5.\n", trash->area);
10197 }
10198 fcn->function_ref[hlua_state_id] = ref_io;
10199 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010200 }
10201
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010202 /* Allocate and fill the sample fetch keyword struct. */
10203 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010204 if (!cli_kws) {
10205 errmsg = "Lua out of memory error.";
10206 goto error;
10207 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010208 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010209 if (!fcn) {
10210 errmsg = "Lua out of memory error.";
10211 goto error;
10212 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010213
10214 /* Fill path. */
10215 index = 0;
10216 lua_pushnil(L);
10217 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010218 if (index >= 5) {
10219 errmsg = "1st argument must be a table with a maximum of 5 entries";
10220 goto error;
10221 }
10222 if (lua_type(L, -1) != LUA_TSTRING) {
10223 errmsg = "1st argument must be a table filled with strings";
10224 goto error;
10225 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010226 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010227 if (!cli_kws->kw[0].str_kw[index]) {
10228 errmsg = "Lua out of memory error.";
10229 goto error;
10230 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010231 index++;
10232 lua_pop(L, 1);
10233 }
10234
10235 /* Copy help message. */
10236 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010237 if (!cli_kws->kw[0].usage) {
10238 errmsg = "Lua out of memory error.";
10239 goto error;
10240 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010241
10242 /* Fill fcn io handler. */
10243 len = strlen("<lua.cli>") + 1;
10244 for (i = 0; i < index; i++)
10245 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10246 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010247 if (!fcn->name) {
10248 errmsg = "Lua out of memory error.";
10249 goto error;
10250 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010251 strncat((char *)fcn->name, "<lua.cli", len);
10252 for (i = 0; i < index; i++) {
10253 strncat((char *)fcn->name, ".", len);
10254 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10255 }
10256 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010257 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010258
10259 /* Fill last entries. */
10260 cli_kws->kw[0].private = fcn;
10261 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10262 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10263 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10264
10265 /* Register this new converter */
10266 cli_register_kw(cli_kws);
10267
10268 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010269
10270 error:
10271 release_hlua_function(fcn);
10272 if (cli_kws) {
10273 for (i = 0; i < index; i++)
10274 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10275 ha_free((char **)&(cli_kws->kw[0].usage));
10276 }
10277 ha_free(&cli_kws);
10278 WILL_LJMP(luaL_error(L, errmsg));
10279 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010280}
10281
Christopher Faulet69c581a2021-05-31 08:54:04 +020010282static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10283{
10284 struct hlua_flt_config *conf = fconf->conf;
10285 lua_State *L;
10286 int error, pos, state_id, flt_ref;
10287
10288 state_id = reg_flt_to_stack_id(conf->reg);
10289 L = hlua_states[state_id];
10290 pos = lua_gettop(L);
10291
10292 /* The filter parsing function */
10293 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10294
10295 /* Push the filter class on the stack and resolve all callbacks */
10296 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10297
10298 /* Duplicate the filter class so each filter will have its own copy */
10299 lua_newtable(L);
10300 lua_pushnil(L);
10301
10302 while (lua_next(L, pos+2)) {
10303 lua_pushvalue(L, -2);
10304 lua_insert(L, -2);
10305 lua_settable(L, -4);
10306 }
10307 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10308
10309 /* Remove the original lua filter class from the stack */
10310 lua_pop(L, 1);
10311
10312 /* Push the copy on the stack */
10313 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10314
10315 /* extra args are pushed in a table */
10316 lua_newtable(L);
10317 for (pos = 0; conf->args[pos]; pos++) {
10318 /* Check stack available size. */
10319 if (!lua_checkstack(L, 1)) {
10320 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10321 goto error;
10322 }
10323 lua_pushstring(L, conf->args[pos]);
10324 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10325 }
10326
10327 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10328 switch (error) {
10329 case LUA_OK:
10330 /* replace the filter ref */
10331 conf->ref[state_id] = flt_ref;
10332 break;
10333 case LUA_ERRRUN:
10334 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10335 goto error;
10336 case LUA_ERRMEM:
10337 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10338 goto error;
10339 case LUA_ERRERR:
10340 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10341 goto error;
10342#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10343 case LUA_ERRGCMM:
10344 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10345 goto error;
10346#endif
10347 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010348 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010349 goto error;
10350 }
10351
10352 lua_settop(L, 0);
10353 return 0;
10354
10355 error:
10356 lua_settop(L, 0);
10357 return -1;
10358}
10359
10360static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10361{
10362 struct hlua_flt_config *conf = fconf->conf;
10363 lua_State *L;
10364 int state_id;
10365
10366 if (!conf)
10367 return;
10368
10369 state_id = reg_flt_to_stack_id(conf->reg);
10370 L = hlua_states[state_id];
10371 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10372}
10373
10374static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10375{
10376 struct hlua_flt_config *conf = fconf->conf;
10377 int state_id = reg_flt_to_stack_id(conf->reg);
10378
10379 /* Rely on per-thread init for global scripts */
10380 if (!state_id)
10381 return hlua_filter_init_per_thread(px, fconf);
10382 return 0;
10383}
10384
10385static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10386{
10387
10388 if (fconf->conf) {
10389 struct hlua_flt_config *conf = fconf->conf;
10390 int state_id = reg_flt_to_stack_id(conf->reg);
10391 int pos;
10392
10393 /* Rely on per-thread deinit for global scripts */
10394 if (!state_id)
10395 hlua_filter_deinit_per_thread(px, fconf);
10396
10397 for (pos = 0; conf->args[pos]; pos++)
10398 free(conf->args[pos]);
10399 free(conf->args);
10400 }
10401 ha_free(&fconf->conf);
10402 ha_free((char **)&fconf->id);
10403 ha_free(&fconf->ops);
10404}
10405
10406static int hlua_filter_new(struct stream *s, struct filter *filter)
10407{
10408 struct hlua_flt_config *conf = FLT_CONF(filter);
10409 struct hlua_flt_ctx *flt_ctx = NULL;
10410 int ret = 1;
10411
10412 /* In the execution wrappers linked with a stream, the
10413 * Lua context can be not initialized. This behavior
10414 * permits to save performances because a systematic
10415 * Lua initialization cause 5% performances loss.
10416 */
10417 if (!s->hlua) {
10418 struct hlua *hlua;
10419
10420 hlua = pool_alloc(pool_head_hlua);
10421 if (!hlua) {
10422 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10423 conf->reg->name);
10424 ret = 0;
10425 goto end;
10426 }
10427 HLUA_INIT(hlua);
10428 s->hlua = hlua;
10429 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10430 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10431 conf->reg->name);
10432 ret = 0;
10433 goto end;
10434 }
10435 }
10436
10437 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10438 if (!flt_ctx) {
10439 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10440 conf->reg->name);
10441 ret = 0;
10442 goto end;
10443 }
10444 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10445 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10446 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10447 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10448 conf->reg->name);
10449 ret = 0;
10450 goto end;
10451 }
10452 HLUA_INIT(flt_ctx->hlua[0]);
10453 HLUA_INIT(flt_ctx->hlua[1]);
10454 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10455 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
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
10462 if (!HLUA_IS_RUNNING(s->hlua)) {
10463 /* The following Lua calls can fail. */
10464 if (!SET_SAFE_LJMP(s->hlua)) {
10465 const char *error;
10466
10467 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10468 error = lua_tostring(s->hlua->T, -1);
10469 else
10470 error = "critical error";
10471 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10472 ret = 0;
10473 goto end;
10474 }
10475
10476 /* Check stack size. */
10477 if (!lua_checkstack(s->hlua->T, 1)) {
10478 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010479 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010480 ret = 0;
10481 goto end;
10482 }
10483
10484 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10485 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10486 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10487 conf->reg->name);
10488 RESET_SAFE_LJMP(s->hlua);
10489 ret = 0;
10490 goto end;
10491 }
10492 lua_insert(s->hlua->T, -2);
10493
10494 /* Push the copy on the stack */
10495 s->hlua->nargs = 1;
10496
10497 /* We must initialize the execution timeouts. */
10498 s->hlua->max_time = hlua_timeout_session;
10499
10500 /* At this point the execution is safe. */
10501 RESET_SAFE_LJMP(s->hlua);
10502 }
10503
10504 switch (hlua_ctx_resume(s->hlua, 0)) {
10505 case HLUA_E_OK:
10506 /* Nothing returned or not a table, ignore the filter for current stream */
10507 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10508 ret = 0;
10509 goto end;
10510 }
10511
10512 /* Attached the filter pointer to the ctx */
10513 lua_pushstring(s->hlua->T, "__filter");
10514 lua_pushlightuserdata(s->hlua->T, filter);
10515 lua_settable(s->hlua->T, -3);
10516
10517 /* Save a ref on the filter ctx */
10518 lua_pushvalue(s->hlua->T, 1);
10519 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10520 filter->ctx = flt_ctx;
10521 break;
10522 case HLUA_E_ERRMSG:
10523 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10524 ret = -1;
10525 goto end;
10526 case HLUA_E_ETMOUT:
10527 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10528 ret = 0;
10529 goto end;
10530 case HLUA_E_NOMEM:
10531 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10532 ret = 0;
10533 goto end;
10534 case HLUA_E_AGAIN:
10535 case HLUA_E_YIELD:
10536 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10537 " are not allowed from 'new' function.\n", conf->reg->name);
10538 ret = 0;
10539 goto end;
10540 case HLUA_E_ERR:
10541 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10542 ret = 0;
10543 goto end;
10544 default:
10545 ret = 0;
10546 goto end;
10547 }
10548
10549 end:
10550 if (s->hlua)
10551 lua_settop(s->hlua->T, 0);
10552 if (ret <= 0) {
10553 if (flt_ctx) {
10554 hlua_ctx_destroy(flt_ctx->hlua[0]);
10555 hlua_ctx_destroy(flt_ctx->hlua[1]);
10556 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10557 }
10558 }
10559 return ret;
10560}
10561
10562static void hlua_filter_delete(struct stream *s, struct filter *filter)
10563{
10564 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10565
10566 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10567 hlua_ctx_destroy(flt_ctx->hlua[0]);
10568 hlua_ctx_destroy(flt_ctx->hlua[1]);
10569 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10570 filter->ctx = NULL;
10571}
10572
Christopher Faulet9f55a502020-02-25 15:21:02 +010010573static int hlua_filter_from_payload(struct filter *filter)
10574{
10575 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10576
10577 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10578}
10579
Christopher Fauletc404f112020-02-26 15:03:09 +010010580static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10581 int dir, unsigned int flags)
10582{
10583 struct hlua *flt_hlua;
10584 struct hlua_flt_config *conf = FLT_CONF(filter);
10585 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10586 unsigned int hflags = HLUA_TXN_FLT_CTX;
10587 int ret = 1;
10588
10589 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10590 if (!flt_hlua)
10591 goto end;
10592
10593 if (!HLUA_IS_RUNNING(flt_hlua)) {
10594 int extra_idx = lua_gettop(flt_hlua->T);
10595
10596 /* The following Lua calls can fail. */
10597 if (!SET_SAFE_LJMP(flt_hlua)) {
10598 const char *error;
10599
10600 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10601 error = lua_tostring(flt_hlua->T, -1);
10602 else
10603 error = "critical error";
10604 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10605 goto end;
10606 }
10607
10608 /* Check stack size. */
10609 if (!lua_checkstack(flt_hlua->T, 3)) {
10610 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10611 RESET_SAFE_LJMP(flt_hlua);
10612 goto end;
10613 }
10614
10615 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10616 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10617 RESET_SAFE_LJMP(flt_hlua);
10618 goto end;
10619 }
10620 lua_insert(flt_hlua->T, -2);
10621
10622 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10623 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10624 RESET_SAFE_LJMP(flt_hlua);
10625 goto end;
10626 }
10627 flt_hlua->nargs = 2;
10628
10629 if (flags & HLUA_FLT_CB_ARG_CHN) {
10630 if (dir == SMP_OPT_DIR_REQ)
10631 lua_getfield(flt_hlua->T, -1, "req");
10632 else
10633 lua_getfield(flt_hlua->T, -1, "res");
10634 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10635 lua_pushstring(flt_hlua->T, "__filter");
10636 lua_pushlightuserdata(flt_hlua->T, filter);
10637 lua_settable(flt_hlua->T, -3);
10638 }
10639 flt_hlua->nargs++;
10640 }
10641 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010642 if (dir == SMP_OPT_DIR_REQ)
10643 lua_getfield(flt_hlua->T, -1, "http_req");
10644 else
10645 lua_getfield(flt_hlua->T, -1, "http_res");
10646 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10647 lua_pushstring(flt_hlua->T, "__filter");
10648 lua_pushlightuserdata(flt_hlua->T, filter);
10649 lua_settable(flt_hlua->T, -3);
10650 }
10651 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010652 }
10653
10654 /* Check stack size. */
10655 if (!lua_checkstack(flt_hlua->T, 1)) {
10656 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10657 RESET_SAFE_LJMP(flt_hlua);
10658 goto end;
10659 }
10660
10661 while (extra_idx--) {
10662 lua_pushvalue(flt_hlua->T, 1);
10663 lua_remove(flt_hlua->T, 1);
10664 flt_hlua->nargs++;
10665 }
10666
10667 /* We must initialize the execution timeouts. */
10668 flt_hlua->max_time = hlua_timeout_session;
10669
10670 /* At this point the execution is safe. */
10671 RESET_SAFE_LJMP(flt_hlua);
10672 }
10673
10674 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10675 case HLUA_E_OK:
10676 /* Catch the return value if it required */
10677 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10678 ret = lua_tointeger(flt_hlua->T, -1);
10679 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10680 }
10681
10682 /* Set timeout in the required channel. */
10683 if (flt_hlua->wake_time != TICK_ETERNITY) {
10684 if (dir == SMP_OPT_DIR_REQ)
10685 s->req.analyse_exp = flt_hlua->wake_time;
10686 else
10687 s->res.analyse_exp = flt_hlua->wake_time;
10688 }
10689 break;
10690 case HLUA_E_AGAIN:
10691 /* Set timeout in the required channel. */
10692 if (flt_hlua->wake_time != TICK_ETERNITY) {
10693 if (dir == SMP_OPT_DIR_REQ)
10694 s->req.analyse_exp = flt_hlua->wake_time;
10695 else
10696 s->res.analyse_exp = flt_hlua->wake_time;
10697 }
10698 /* Some actions can be wake up when a "write" event
10699 * is detected on a response channel. This is useful
10700 * only for actions targeted on the requests.
10701 */
10702 if (HLUA_IS_WAKERESWR(flt_hlua))
10703 s->res.flags |= CF_WAKE_WRITE;
10704 if (HLUA_IS_WAKEREQWR(flt_hlua))
10705 s->req.flags |= CF_WAKE_WRITE;
10706 ret = 0;
10707 goto end;
10708 case HLUA_E_ERRMSG:
10709 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10710 ret = -1;
10711 goto end;
10712 case HLUA_E_ETMOUT:
10713 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10714 goto end;
10715 case HLUA_E_NOMEM:
10716 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10717 goto end;
10718 case HLUA_E_YIELD:
10719 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10720 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10721 goto end;
10722 case HLUA_E_ERR:
10723 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10724 goto end;
10725 default:
10726 goto end;
10727 }
10728
10729
10730 end:
10731 return ret;
10732}
10733
10734static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10735{
10736 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10737
10738 flt_ctx->flags = 0;
10739 return hlua_filter_callback(s, filter, "start_analyze",
10740 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10741 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10742}
10743
10744static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10745{
10746 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10747
10748 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10749 return hlua_filter_callback(s, filter, "end_analyze",
10750 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10751 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10752}
10753
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010754static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10755{
10756 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10757
10758 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10759 return hlua_filter_callback(s, filter, "http_headers",
10760 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10761 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10762}
10763
10764static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10765 unsigned int offset, unsigned int len)
10766{
10767 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10768 struct hlua *flt_hlua;
10769 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10770 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10771 int ret;
10772
10773 flt_hlua = flt_ctx->hlua[idx];
10774 flt_ctx->cur_off[idx] = offset;
10775 flt_ctx->cur_len[idx] = len;
10776 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10777 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10778 if (ret != -1) {
10779 ret = flt_ctx->cur_len[idx];
10780 if (lua_gettop(flt_hlua->T) > 0) {
10781 ret = lua_tointeger(flt_hlua->T, -1);
10782 if (ret > flt_ctx->cur_len[idx])
10783 ret = flt_ctx->cur_len[idx];
10784 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10785 }
10786 }
10787 return ret;
10788}
10789
10790static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10791{
10792 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10793
10794 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10795 return hlua_filter_callback(s, filter, "http_end",
10796 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10797 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10798}
10799
Christopher Fauletc404f112020-02-26 15:03:09 +010010800static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10801 unsigned int offset, unsigned int len)
10802{
10803 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10804 struct hlua *flt_hlua;
10805 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10806 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10807 int ret;
10808
10809 flt_hlua = flt_ctx->hlua[idx];
10810 flt_ctx->cur_off[idx] = offset;
10811 flt_ctx->cur_len[idx] = len;
10812 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10813 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10814 if (ret != -1) {
10815 ret = flt_ctx->cur_len[idx];
10816 if (lua_gettop(flt_hlua->T) > 0) {
10817 ret = lua_tointeger(flt_hlua->T, -1);
10818 if (ret > flt_ctx->cur_len[idx])
10819 ret = flt_ctx->cur_len[idx];
10820 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10821 }
10822 }
10823 return ret;
10824}
10825
Christopher Faulet69c581a2021-05-31 08:54:04 +020010826static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10827 struct flt_conf *fconf, char **err, void *private)
10828{
10829 struct hlua_reg_filter *reg_flt = private;
10830 lua_State *L;
10831 struct hlua_flt_config *conf = NULL;
10832 const char *flt_id = NULL;
10833 int state_id, pos, flt_flags = 0;
10834 struct flt_ops *hlua_flt_ops = NULL;
10835
10836 state_id = reg_flt_to_stack_id(reg_flt);
10837 L = hlua_states[state_id];
10838
10839 /* Initialize the filter ops with default callbacks */
10840 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010841 if (!hlua_flt_ops)
10842 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010843 hlua_flt_ops->init = hlua_filter_init;
10844 hlua_flt_ops->deinit = hlua_filter_deinit;
10845 if (state_id) {
10846 /* Set per-thread callback if script is loaded per-thread */
10847 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10848 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10849 }
10850 hlua_flt_ops->attach = hlua_filter_new;
10851 hlua_flt_ops->detach = hlua_filter_delete;
10852
10853 /* Push the filter class on the stack and resolve all callbacks */
10854 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10855
Christopher Fauletc404f112020-02-26 15:03:09 +010010856 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10857 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10858 lua_pop(L, 1);
10859 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10860 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10861 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010862 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10863 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10864 lua_pop(L, 1);
10865 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10866 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10867 lua_pop(L, 1);
10868 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10869 hlua_flt_ops->http_end = hlua_filter_http_end;
10870 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010871 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10872 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10873 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010874
10875 /* Get id and flags of the filter class */
10876 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10877 flt_id = lua_tostring(L, -1);
10878 lua_pop(L, 1);
10879 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10880 flt_flags = lua_tointeger(L, -1);
10881 lua_pop(L, 1);
10882
10883 /* Create the filter config */
10884 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010885 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010886 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010887 conf->reg = reg_flt;
10888
10889 /* duplicate args */
10890 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10891 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010892 if (!conf->args)
10893 goto error;
10894 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010895 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010896 if (!conf->args[pos])
10897 goto error;
10898 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010899 conf->args[pos] = NULL;
10900 *cur_arg += pos + 1;
10901
Christopher Fauletc86bb872021-08-13 08:33:57 +020010902 if (flt_id) {
10903 fconf->id = strdup(flt_id);
10904 if (!fconf->id)
10905 goto error;
10906 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010907 fconf->flags = flt_flags;
10908 fconf->conf = conf;
10909 fconf->ops = hlua_flt_ops;
10910
10911 lua_settop(L, 0);
10912 return 0;
10913
10914 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010915 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010916 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010917 if (conf && conf->args) {
10918 for (pos = 0; conf->args[pos]; pos++)
10919 free(conf->args[pos]);
10920 free(conf->args);
10921 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010922 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010923 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010924 lua_settop(L, 0);
10925 return -1;
10926}
10927
Christopher Fauletc404f112020-02-26 15:03:09 +010010928__LJMP static int hlua_register_data_filter(lua_State *L)
10929{
10930 struct filter *filter;
10931 struct channel *chn;
10932
10933 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10934 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10935 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10936
10937 lua_getfield(L, 1, "__filter");
10938 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10939 filter = lua_touserdata (L, -1);
10940 lua_pop(L, 1);
10941
10942 register_data_filter(chn_strm(chn), chn, filter);
10943 return 1;
10944}
10945
10946__LJMP static int hlua_unregister_data_filter(lua_State *L)
10947{
10948 struct filter *filter;
10949 struct channel *chn;
10950
10951 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10952 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10953 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10954
10955 lua_getfield(L, 1, "__filter");
10956 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10957 filter = lua_touserdata (L, -1);
10958 lua_pop(L, 1);
10959
10960 unregister_data_filter(chn_strm(chn), chn, filter);
10961 return 1;
10962}
10963
Christopher Faulet69c581a2021-05-31 08:54:04 +020010964/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010965 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020010966 * parse configuration arguments.
10967 */
10968__LJMP static int hlua_register_filter(lua_State *L)
10969{
10970 struct buffer *trash;
10971 struct flt_kw_list *fkl;
10972 struct flt_kw *fkw;
10973 const char *name;
10974 struct hlua_reg_filter *reg_flt= NULL;
10975 int flt_ref, fun_ref;
10976 int len;
10977
10978 MAY_LJMP(check_args(L, 3, "register_filter"));
10979
10980 /* First argument : filter name. */
10981 name = MAY_LJMP(luaL_checkstring(L, 1));
10982
10983 /* Second argument : The filter class */
10984 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
10985
10986 /* Third argument : lua function. */
10987 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
10988
10989 trash = get_trash_chunk();
10990 chunk_printf(trash, "lua.%s", name);
10991 fkw = flt_find_kw(trash->area);
10992 if (fkw != NULL) {
10993 reg_flt = fkw->private;
10994 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
10995 ha_warning("Trying to register filter 'lua.%s' more than once. "
10996 "This will become a hard error in version 2.5.\n", name);
10997 }
10998 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10999 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11000 return 0;
11001 }
11002
11003 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11004 if (!fkl)
11005 goto alloc_error;
11006 fkl->scope = "HLUA";
11007
11008 reg_flt = new_hlua_reg_filter(name);
11009 if (!reg_flt)
11010 goto alloc_error;
11011
11012 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11013 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11014
11015 /* The filter keyword */
11016 len = strlen("lua.") + strlen(name) + 1;
11017 fkl->kw[0].kw = calloc(1, len);
11018 if (!fkl->kw[0].kw)
11019 goto alloc_error;
11020
11021 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11022
11023 fkl->kw[0].parse = hlua_filter_parse_fct;
11024 fkl->kw[0].private = reg_flt;
11025 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11026
11027 /* Register this new filter */
11028 flt_register_keywords(fkl);
11029
11030 return 0;
11031
11032 alloc_error:
11033 release_hlua_reg_filter(reg_flt);
11034 ha_free(&fkl);
11035 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11036 return 0; /* Never reached */
11037}
11038
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011039static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011040 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011041 char **err, unsigned int *timeout)
11042{
11043 const char *error;
11044
11045 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011046 if (error == PARSE_TIME_OVER) {
11047 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11048 args[1], args[0]);
11049 return -1;
11050 }
11051 else if (error == PARSE_TIME_UNDER) {
11052 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11053 args[1], args[0]);
11054 return -1;
11055 }
11056 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011057 memprintf(err, "%s: invalid timeout", args[0]);
11058 return -1;
11059 }
11060 return 0;
11061}
11062
11063static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011064 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011065 char **err)
11066{
11067 return hlua_read_timeout(args, section_type, curpx, defpx,
11068 file, line, err, &hlua_timeout_session);
11069}
11070
11071static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011072 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011073 char **err)
11074{
11075 return hlua_read_timeout(args, section_type, curpx, defpx,
11076 file, line, err, &hlua_timeout_task);
11077}
11078
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011079static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011080 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011081 char **err)
11082{
11083 return hlua_read_timeout(args, section_type, curpx, defpx,
11084 file, line, err, &hlua_timeout_applet);
11085}
11086
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011087static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011088 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011089 char **err)
11090{
11091 char *error;
11092
11093 hlua_nb_instruction = strtoll(args[1], &error, 10);
11094 if (*error != '\0') {
11095 memprintf(err, "%s: invalid number", args[0]);
11096 return -1;
11097 }
11098 return 0;
11099}
11100
Willy Tarreau32f61e22015-03-18 17:54:59 +010011101static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011102 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011103 char **err)
11104{
11105 char *error;
11106
11107 if (*(args[1]) == 0) {
11108 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11109 return -1;
11110 }
11111 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11112 if (*error != '\0') {
11113 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11114 return -1;
11115 }
11116 return 0;
11117}
11118
11119
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011120/* This function is called by the main configuration key "lua-load". It loads and
11121 * execute an lua file during the parsing of the HAProxy configuration file. It is
11122 * the main lua entry point.
11123 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011124 * This function runs with the HAProxy keywords API. It returns -1 if an error
11125 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011126 *
11127 * In some error case, LUA set an error message in top of the stack. This function
11128 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011129 *
11130 * This function can fail with an abort() due to an Lua critical error.
11131 * We are in the configuration parsing process of HAProxy, this abort() is
11132 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011133 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011134static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011135{
11136 int error;
11137
11138 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011139 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011140 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011141 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11142 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011143 return -1;
11144 }
11145
11146 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011147 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011148 switch (error) {
11149 case LUA_OK:
11150 break;
11151 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011152 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11153 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011154 return -1;
11155 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011156 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011157 return -1;
11158 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011159 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11160 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011161 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011162#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011163 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011164 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11165 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011166 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011167#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011168 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011169 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11170 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011171 return -1;
11172 }
11173
11174 return 0;
11175}
11176
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011177static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011178 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011179 char **err)
11180{
11181 if (*(args[1]) == 0) {
11182 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11183 return -1;
11184 }
11185
Thierry Fournier59f11be2020-11-29 00:37:41 +010011186 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011187 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011188 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011189 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011190}
11191
Thierry Fournier59f11be2020-11-29 00:37:41 +010011192static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011193 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011194 char **err)
11195{
11196 int len;
11197
11198 if (*(args[1]) == 0) {
11199 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11200 return -1;
11201 }
11202
11203 if (per_thread_load == NULL) {
11204 /* allocate the first entry large enough to store the final NULL */
11205 per_thread_load = calloc(1, sizeof(*per_thread_load));
11206 if (per_thread_load == NULL) {
11207 memprintf(err, "out of memory error");
11208 return -1;
11209 }
11210 }
11211
11212 /* count used entries */
11213 for (len = 0; per_thread_load[len] != NULL; len++)
11214 ;
11215
11216 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11217 if (per_thread_load == NULL) {
11218 memprintf(err, "out of memory error");
11219 return -1;
11220 }
11221
11222 per_thread_load[len] = strdup(args[1]);
11223 per_thread_load[len + 1] = NULL;
11224
11225 if (per_thread_load[len] == NULL) {
11226 memprintf(err, "out of memory error");
11227 return -1;
11228 }
11229
11230 /* loading for thread 1 only */
11231 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011232 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011233 return hlua_load_state(args[1], hlua_states[1], err);
11234}
11235
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011236/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11237 * in the given <ctx>.
11238 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011239static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011240{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011241 lua_getglobal(L, "package"); /* push package variable */
11242 lua_pushstring(L, path); /* push given path */
11243 lua_pushstring(L, ";"); /* push semicolon */
11244 lua_getfield(L, -3, type); /* push old path */
11245 lua_concat(L, 3); /* concatenate to new path */
11246 lua_setfield(L, -2, type); /* store new path */
11247 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011248
11249 return 0;
11250}
11251
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011252static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011253 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011254 char **err)
11255{
11256 char *path;
11257 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011258 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011259 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011260
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011261 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011262 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011263 }
11264
11265 if (!(*args[1])) {
11266 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011267 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011268 }
11269 path = args[1];
11270
11271 if (*args[2]) {
11272 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11273 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011274 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011275 }
11276 type = args[2];
11277 }
11278
Thierry Fournier59f11be2020-11-29 00:37:41 +010011279 p = calloc(1, sizeof(*p));
11280 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011281 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011282 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011283 }
11284 p->path = strdup(path);
11285 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011286 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011287 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011288 }
11289 p->type = strdup(type);
11290 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011291 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011292 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011293 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011294 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011295
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011296 /* Handle the global state and the per-thread state for the first
11297 * thread. The remaining threads will be initialized based on
11298 * prepend_path_list.
11299 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011300 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011301 lua_State *L = hlua_states[i];
11302 const char *error;
11303
11304 if (setjmp(safe_ljmp_env) != 0) {
11305 lua_atpanic(L, hlua_panic_safe);
11306 if (lua_type(L, -1) == LUA_TSTRING)
11307 error = lua_tostring(L, -1);
11308 else
11309 error = "critical error";
11310 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11311 exit(1);
11312 } else {
11313 lua_atpanic(L, hlua_panic_ljmp);
11314 }
11315
11316 hlua_prepend_path(L, type, path);
11317
11318 lua_atpanic(L, hlua_panic_safe);
11319 }
11320
Thierry Fournier59f11be2020-11-29 00:37:41 +010011321 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011322
11323err2:
11324 free(p->type);
11325 free(p->path);
11326err:
11327 free(p);
11328 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011329}
11330
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011331/* configuration keywords declaration */
11332static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011333 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011334 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011335 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011336 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11337 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011338 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011339 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011340 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011341 { 0, NULL, NULL },
11342}};
11343
Willy Tarreau0108d902018-11-25 19:14:37 +010011344INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11345
Christopher Fauletafd8f102018-11-08 11:34:21 +010011346
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011347/* This function can fail with an abort() due to an Lua critical error.
11348 * We are in the initialisation process of HAProxy, this abort() is
11349 * tolerated.
11350 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011351int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011352{
11353 struct hlua_init_function *init;
11354 const char *msg;
11355 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011356 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011357 const char *kind;
11358 const char *trace;
11359 int return_status = 1;
11360#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11361 int nres;
11362#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011363
Willy Tarreaucdb53462020-12-02 12:12:00 +010011364 /* disable memory limit checks if limit is not set */
11365 if (!hlua_global_allocator.limit)
11366 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11367
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011368 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011369 if (setjmp(safe_ljmp_env) != 0) {
11370 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011371 if (lua_type(L, -1) == LUA_TSTRING)
11372 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011373 else
11374 error = "critical error";
11375 fprintf(stderr, "Lua post-init: %s.\n", error);
11376 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011377 } else {
11378 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011379 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011380
Thierry Fournierb8cef172020-11-28 15:37:17 +010011381 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011382
Thierry Fournierc7492592020-11-28 23:57:24 +010011383 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011384 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011385
11386#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011387 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011388#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011389 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011390#endif
11391 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011392 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011393
11394 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011395 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011396 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011397
11398 case LUA_ERRERR:
11399 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011400 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011401 case LUA_ERRRUN:
11402 if (!kind)
11403 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011404 msg = lua_tostring(L, -1);
11405 lua_settop(L, 0); /* Empty the stack. */
11406 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011407 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011408 if (msg)
11409 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11410 else
11411 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11412 return_status = 0;
11413 break;
11414
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011415 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011416 /* Unknown error */
11417 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011418 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011419 case LUA_YIELD:
11420 /* yield is not configured at this step, this state doesn't happen */
11421 if (!kind)
11422 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011423 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011424 case LUA_ERRMEM:
11425 if (!kind)
11426 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011427 lua_settop(L, 0);
11428 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011429 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011430 ha_alert("Lua init: %s: %s\n", kind, trace);
11431 return_status = 0;
11432 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011433 }
Thierry Fournier670db242020-11-28 10:49:59 +010011434 if (!return_status)
11435 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011436 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011437
11438 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011439 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011440}
11441
Thierry Fournierb8cef172020-11-28 15:37:17 +010011442int hlua_post_init()
11443{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011444 int ret;
11445 int i;
11446 int errors;
11447 char *err = NULL;
11448 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011449 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011450
Willy Tarreaub1310492021-08-30 09:35:18 +020011451#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011452 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011453 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011454 int saved_used_backed = global.ssl_used_backend;
11455 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011456 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011457 global.ssl_used_backend = saved_used_backed;
11458 }
11459#endif
11460
Thierry Fournierc7492592020-11-28 23:57:24 +010011461 /* Perform post init of common thread */
11462 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011463 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011464 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11465 if (ret == 0)
11466 return 0;
11467
11468 /* init remaining lua states and load files */
11469 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11470
11471 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011472 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011473
11474 /* Init lua state */
11475 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11476
11477 /* Load lua files */
11478 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11479 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11480 if (ret != 0) {
11481 ha_alert("Lua init: %s\n", err);
11482 return 0;
11483 }
11484 }
11485 }
11486
11487 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011488 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011489
11490 /* Execute post init for all states */
11491 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11492
11493 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011494 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011495
11496 /* run post init */
11497 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11498 if (ret == 0)
11499 return 0;
11500 }
11501
11502 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011503 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011504
11505 /* control functions registering. Each function must have:
11506 * - only the function_ref[0] set positive and all other to -1
11507 * - only the function_ref[0] set to -1 and all other positive
11508 * This ensure a same reference is not used both in shared
11509 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011510 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011511 * complicated to found for the end user.
11512 */
11513 errors = 0;
11514 list_for_each_entry(fcn, &referenced_functions, l) {
11515 ret = 0;
11516 for (i = 1; i < global.nbthread + 1; i++) {
11517 if (fcn->function_ref[i] == -1)
11518 ret--;
11519 else
11520 ret++;
11521 }
11522 if (abs(ret) != global.nbthread) {
11523 ha_alert("Lua function '%s' is not referenced in all thread. "
11524 "Expect function in all thread or in none thread.\n", fcn->name);
11525 errors++;
11526 continue;
11527 }
11528
11529 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011530 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11531 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011532 "exclusive.\n", fcn->name);
11533 errors++;
11534 }
11535 }
11536
Christopher Faulet69c581a2021-05-31 08:54:04 +020011537 /* Do the same with registered filters */
11538 list_for_each_entry(reg_flt, &referenced_filters, l) {
11539 ret = 0;
11540 for (i = 1; i < global.nbthread + 1; i++) {
11541 if (reg_flt->flt_ref[i] == -1)
11542 ret--;
11543 else
11544 ret++;
11545 }
11546 if (abs(ret) != global.nbthread) {
11547 ha_alert("Lua filter '%s' is not referenced in all thread. "
11548 "Expect function in all thread or in none thread.\n", reg_flt->name);
11549 errors++;
11550 continue;
11551 }
11552
11553 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11554 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11555 "and per-thread Lua context (through lua-load-per-thread). these two context "
11556 "exclusive.\n", fcn->name);
11557 errors++;
11558 }
11559 }
11560
11561
Thierry Fournier59f11be2020-11-29 00:37:41 +010011562 if (errors > 0)
11563 return 0;
11564
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011565 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011566 * -1 in order to have probably a segfault if someone use it
11567 */
11568 hlua_state_id = -1;
11569
11570 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011571}
11572
Willy Tarreau32f61e22015-03-18 17:54:59 +010011573/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11574 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11575 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011576 * allocation. <nsize> is the requested new size. A new allocation is
11577 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011578 * zero. This one verifies that the limits are respected but is optimized
11579 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011580 *
11581 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11582 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11583 * that and will simply allocate zero as if it were the result of malloc(0),
11584 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11585 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011586 */
11587static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11588{
11589 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011590 size_t limit, old, new;
11591
11592 /* a limit of ~0 means unlimited and boot complete, so there's no need
11593 * for accounting anymore.
11594 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011595 if (likely(~zone->limit == 0)) {
11596 if (!nsize)
11597 ha_free(&ptr);
11598 else
11599 ptr = realloc(ptr, nsize);
11600 return ptr;
11601 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011602
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011603 if (!ptr)
11604 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011605
Willy Tarreaucdb53462020-12-02 12:12:00 +010011606 /* enforce strict limits across all threads */
11607 limit = zone->limit;
11608 old = _HA_ATOMIC_LOAD(&zone->allocated);
11609 do {
11610 new = old + nsize - osize;
11611 if (unlikely(nsize && limit && new > limit))
11612 return NULL;
11613 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011614
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011615 if (!nsize)
11616 ha_free(&ptr);
11617 else
11618 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011619
11620 if (unlikely(!ptr && nsize)) // failed
11621 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11622
11623 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011624 return ptr;
11625}
11626
Thierry Fournierecb83c22020-11-28 15:49:44 +010011627/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011628 * We are in the initialisation process of HAProxy, this abort() is
11629 * tolerated.
11630 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011631lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011632{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011633 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011634 int idx;
11635 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011636 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011637 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011638 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011639 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011640 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011641 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011642
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011643 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011644 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011645
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011646 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011647 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011648 *context = NULL;
11649
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011650 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011651 * the Lua function can fail with an abort. We are in the initialisation
11652 * process of HAProxy, this abort() is tolerated.
11653 */
11654
Thierry Fournier3c539322020-11-28 16:05:05 +010011655 /* Call post initialisation function in safe environment. */
11656 if (setjmp(safe_ljmp_env) != 0) {
11657 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011658 if (lua_type(L, -1) == LUA_TSTRING)
11659 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011660 else
11661 error_msg = "critical error";
11662 fprintf(stderr, "Lua init: %s.\n", error_msg);
11663 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011664 } else {
11665 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011666 }
11667
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011668 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011669 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011670#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11671#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11672#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011673 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011674#endif
11675#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011676 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011677#endif
11678#undef HLUA_PREPEND_PATH_TOSTRING
11679#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011680
Thierry Fournier59f11be2020-11-29 00:37:41 +010011681 /* Apply configured prepend path */
11682 list_for_each_entry(pp, &prepend_path_list, l)
11683 hlua_prepend_path(L, pp->type, pp->path);
11684
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011685 /*
11686 *
11687 * Create "core" object.
11688 *
11689 */
11690
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011691 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011692 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011693
Thierry Fournierecb83c22020-11-28 15:49:44 +010011694 /* set the thread id */
11695 hlua_class_const_int(L, "thread", thread_num);
11696
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011697 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011698 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011699 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011700
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011701 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011702 hlua_class_function(L, "register_init", hlua_register_init);
11703 hlua_class_function(L, "register_task", hlua_register_task);
11704 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11705 hlua_class_function(L, "register_converters", hlua_register_converters);
11706 hlua_class_function(L, "register_action", hlua_register_action);
11707 hlua_class_function(L, "register_service", hlua_register_service);
11708 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011709 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011710 hlua_class_function(L, "yield", hlua_yield);
11711 hlua_class_function(L, "set_nice", hlua_set_nice);
11712 hlua_class_function(L, "sleep", hlua_sleep);
11713 hlua_class_function(L, "msleep", hlua_msleep);
11714 hlua_class_function(L, "add_acl", hlua_add_acl);
11715 hlua_class_function(L, "del_acl", hlua_del_acl);
11716 hlua_class_function(L, "set_map", hlua_set_map);
11717 hlua_class_function(L, "del_map", hlua_del_map);
11718 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011719 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011720 hlua_class_function(L, "log", hlua_log);
11721 hlua_class_function(L, "Debug", hlua_log_debug);
11722 hlua_class_function(L, "Info", hlua_log_info);
11723 hlua_class_function(L, "Warning", hlua_log_warning);
11724 hlua_class_function(L, "Alert", hlua_log_alert);
11725 hlua_class_function(L, "done", hlua_done);
11726 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011727
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011728 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011729
11730 /*
11731 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011732 * Create "act" object.
11733 *
11734 */
11735
11736 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011737 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011738
11739 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011740 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11741 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11742 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11743 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11744 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11745 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11746 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11747 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011748
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011749 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011750
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011751 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011752
11753 /*
11754 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011755 * Create "Filter" object.
11756 *
11757 */
11758
11759 /* This table entry is the object "filter" base. */
11760 lua_newtable(L);
11761
11762 /* push flags and constants */
11763 hlua_class_const_int(L, "CONTINUE", 1);
11764 hlua_class_const_int(L, "WAIT", 0);
11765 hlua_class_const_int(L, "ERROR", -1);
11766
11767 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
11768
Christopher Fauletc404f112020-02-26 15:03:09 +010011769 hlua_class_function(L, "wake_time", hlua_set_wake_time);
11770 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
11771 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
11772
Christopher Faulet69c581a2021-05-31 08:54:04 +020011773 lua_setglobal(L, "filter");
11774
11775 /*
11776 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011777 * Register class Map
11778 *
11779 */
11780
11781 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011782 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011783
11784 /* register pattern types. */
11785 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011786 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011787 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011788 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011789 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011790 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011791
11792 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011793 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011794
11795 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011796 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011797
Ilya Shipitsind4259502020-04-08 01:07:56 +050011798 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011799 lua_pushstring(L, "__index");
11800 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011801
11802 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011803 hlua_class_function(L, "lookup", hlua_map_lookup);
11804 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011805
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011806 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011807
Thierry Fournier45e78d72016-02-19 18:34:46 +010011808 /* Register previous table in the registry with reference and named entry.
11809 * The function hlua_register_metatable() pops the stack, so we
11810 * previously create a copy of the table.
11811 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011812 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
11813 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011814
11815 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011816 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011817
11818 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011819 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011820
11821 /*
11822 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011823 * Register class Channel
11824 *
11825 */
11826
11827 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011828 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011829
Ilya Shipitsind4259502020-04-08 01:07:56 +050011830 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011831 lua_pushstring(L, "__index");
11832 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011833
11834 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011835 hlua_class_function(L, "data", hlua_channel_get_data);
11836 hlua_class_function(L, "line", hlua_channel_get_line);
11837 hlua_class_function(L, "set", hlua_channel_set_data);
11838 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011839 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011840 hlua_class_function(L, "prepend", hlua_channel_prepend);
11841 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011842 hlua_class_function(L, "send", hlua_channel_send);
11843 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011844 hlua_class_function(L, "input", hlua_channel_get_in_len);
11845 hlua_class_function(L, "output", hlua_channel_get_out_len);
11846 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011847 hlua_class_function(L, "is_full", hlua_channel_is_full);
11848 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011849
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011850 /* Deprecated API */
11851 hlua_class_function(L, "get", hlua_channel_get);
11852 hlua_class_function(L, "dup", hlua_channel_dup);
11853 hlua_class_function(L, "getline", hlua_channel_getline);
11854 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
11855 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
11856
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011857 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011858
11859 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011860 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011861
11862 /*
11863 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011864 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011865 *
11866 */
11867
11868 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011869 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011870
Ilya Shipitsind4259502020-04-08 01:07:56 +050011871 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011872 lua_pushstring(L, "__index");
11873 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011874
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011875 /* Browse existing fetches and create the associated
11876 * object method.
11877 */
11878 sf = NULL;
11879 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011880 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11881 * by an underscore.
11882 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011883 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011884 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011885 if (*p == '.' || *p == '-' || *p == '+')
11886 *p = '_';
11887
11888 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011889 lua_pushstring(L, trash.area);
11890 lua_pushlightuserdata(L, sf);
11891 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
11892 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011893 }
11894
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011895 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011896
11897 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011898 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011899
11900 /*
11901 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011902 * Register class Converters
11903 *
11904 */
11905
11906 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011907 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011908
11909 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011910 lua_pushstring(L, "__index");
11911 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011912
11913 /* Browse existing converters and create the associated
11914 * object method.
11915 */
11916 sc = NULL;
11917 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011918 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11919 * by an underscore.
11920 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011921 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011922 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011923 if (*p == '.' || *p == '-' || *p == '+')
11924 *p = '_';
11925
11926 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011927 lua_pushstring(L, trash.area);
11928 lua_pushlightuserdata(L, sc);
11929 lua_pushcclosure(L, hlua_run_sample_conv, 1);
11930 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011931 }
11932
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011933 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011934
11935 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011936 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011937
11938 /*
11939 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011940 * Register class HTTP
11941 *
11942 */
11943
11944 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011945 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011946
Ilya Shipitsind4259502020-04-08 01:07:56 +050011947 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011948 lua_pushstring(L, "__index");
11949 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011950
11951 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011952 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
11953 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
11954 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
11955 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
11956 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
11957 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
11958 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
11959 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
11960 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
11961 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011962
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011963 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
11964 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
11965 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
11966 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
11967 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
11968 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
11969 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011970
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011971 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011972
11973 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011974 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011975
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011976 /*
11977 *
11978 * Register class HTTPMessage
11979 *
11980 */
11981
11982 /* Create and fill the metatable. */
11983 lua_newtable(L);
11984
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011985 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011986 lua_pushstring(L, "__index");
11987 lua_newtable(L);
11988
11989 /* Register Lua functions. */
11990 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
11991 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
11992 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
11993 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
11994 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
11995 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
11996 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
11997 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
11998 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
11999 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12000 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12001 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12002 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12003 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12004 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12005 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12006 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12007 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12008
12009 hlua_class_function(L, "body", hlua_http_msg_get_body);
12010 hlua_class_function(L, "set", hlua_http_msg_set_data);
12011 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12012 hlua_class_function(L, "append", hlua_http_msg_append);
12013 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12014 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12015 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12016 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12017
12018 hlua_class_function(L, "send", hlua_http_msg_send);
12019 hlua_class_function(L, "forward", hlua_http_msg_forward);
12020
12021 lua_rawset(L, -3);
12022
12023 /* Register previous table in the registry with reference and named entry. */
12024 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012025
12026 /*
12027 *
12028 * Register class HTTPClient
12029 *
12030 */
12031
12032 /* Create and fill the metatable. */
12033 lua_newtable(L);
12034 lua_pushstring(L, "__index");
12035 lua_newtable(L);
12036 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012037 hlua_class_function(L, "head", hlua_httpclient_head);
12038 hlua_class_function(L, "put", hlua_httpclient_put);
12039 hlua_class_function(L, "post", hlua_httpclient_post);
12040 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012041 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012042 /* Register the garbage collector entry. */
12043 lua_pushstring(L, "__gc");
12044 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12045 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12046
William Lallemand3956c4e2021-09-21 16:25:15 +020012047
12048
12049 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012050 /*
12051 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012052 * Register class AppletTCP
12053 *
12054 */
12055
12056 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012057 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012058
Ilya Shipitsind4259502020-04-08 01:07:56 +050012059 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012060 lua_pushstring(L, "__index");
12061 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012062
12063 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012064 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12065 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12066 hlua_class_function(L, "send", hlua_applet_tcp_send);
12067 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12068 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12069 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12070 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12071 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012072
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012073 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012074
12075 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012076 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012077
12078 /*
12079 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012080 * Register class AppletHTTP
12081 *
12082 */
12083
12084 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012085 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012086
Ilya Shipitsind4259502020-04-08 01:07:56 +050012087 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012088 lua_pushstring(L, "__index");
12089 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012090
12091 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012092 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12093 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12094 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12095 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12096 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12097 hlua_class_function(L, "getline", hlua_applet_http_getline);
12098 hlua_class_function(L, "receive", hlua_applet_http_recv);
12099 hlua_class_function(L, "send", hlua_applet_http_send);
12100 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12101 hlua_class_function(L, "set_status", hlua_applet_http_status);
12102 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012103
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012104 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012105
12106 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012107 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012108
12109 /*
12110 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012111 * Register class TXN
12112 *
12113 */
12114
12115 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012116 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012117
Ilya Shipitsind4259502020-04-08 01:07:56 +050012118 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012119 lua_pushstring(L, "__index");
12120 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012121
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012122 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012123 hlua_class_function(L, "set_priv", hlua_set_priv);
12124 hlua_class_function(L, "get_priv", hlua_get_priv);
12125 hlua_class_function(L, "set_var", hlua_set_var);
12126 hlua_class_function(L, "unset_var", hlua_unset_var);
12127 hlua_class_function(L, "get_var", hlua_get_var);
12128 hlua_class_function(L, "done", hlua_txn_done);
12129 hlua_class_function(L, "reply", hlua_txn_reply_new);
12130 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12131 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12132 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12133 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12134 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12135 hlua_class_function(L, "deflog", hlua_txn_deflog);
12136 hlua_class_function(L, "log", hlua_txn_log);
12137 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12138 hlua_class_function(L, "Info", hlua_txn_log_info);
12139 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12140 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012141
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012142 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012143
12144 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012145 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012146
12147 /*
12148 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012149 * Register class reply
12150 *
12151 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012152 lua_newtable(L);
12153 lua_pushstring(L, "__index");
12154 lua_newtable(L);
12155 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12156 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12157 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12158 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12159 lua_settable(L, -3); /* Sets the __index entry. */
12160 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012161
12162
12163 /*
12164 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012165 * Register class Socket
12166 *
12167 */
12168
12169 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012170 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012171
Ilya Shipitsind4259502020-04-08 01:07:56 +050012172 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012173 lua_pushstring(L, "__index");
12174 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012175
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012176#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012177 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012178#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012179 hlua_class_function(L, "connect", hlua_socket_connect);
12180 hlua_class_function(L, "send", hlua_socket_send);
12181 hlua_class_function(L, "receive", hlua_socket_receive);
12182 hlua_class_function(L, "close", hlua_socket_close);
12183 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12184 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12185 hlua_class_function(L, "setoption", hlua_socket_setoption);
12186 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012187
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012188 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012189
12190 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012191 lua_pushstring(L, "__gc");
12192 lua_pushcclosure(L, hlua_socket_gc, 0);
12193 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012194
12195 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012196 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012197
Thierry Fournieraafc7772020-12-04 11:47:47 +010012198 lua_atpanic(L, hlua_panic_safe);
12199
12200 return L;
12201}
12202
12203void hlua_init(void) {
12204 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012205 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012206#ifdef USE_OPENSSL
12207 struct srv_kw *kw;
12208 int tmp_error;
12209 char *error;
12210 char *args[] = { /* SSL client configuration. */
12211 "ssl",
12212 "verify",
12213 "none",
12214 NULL
12215 };
12216#endif
12217
12218 /* Init post init function list head */
12219 for (i = 0; i < MAX_THREADS + 1; i++)
12220 LIST_INIT(&hlua_init_functions[i]);
12221
12222 /* Init state for common/shared lua parts */
12223 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012224 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012225 hlua_states[0] = hlua_init_state(0);
12226
12227 /* Init state 1 for thread 0. We have at least one thread. */
12228 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012229 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012230 hlua_states[1] = hlua_init_state(1);
12231
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012232 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012233 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012234 if (!socket_proxy) {
12235 fprintf(stderr, "Lua init: %s\n", errmsg);
12236 exit(1);
12237 }
12238 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012239
12240 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012241 socket_tcp = new_server(socket_proxy);
12242 if (!socket_tcp) {
12243 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12244 exit(1);
12245 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012246
12247#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012248 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012249 socket_ssl = new_server(socket_proxy);
12250 if (!socket_ssl) {
12251 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12252 exit(1);
12253 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012254
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012255 socket_ssl->use_ssl = 1;
12256 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012257
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012258 for (i = 0; args[i] != NULL; i++) {
12259 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012260 /*
12261 *
12262 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012263 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012264 * features like client certificates and ssl_verify.
12265 *
12266 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012267 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012268 if (tmp_error != 0) {
12269 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12270 abort(); /* This must be never arrives because the command line
12271 not editable by the user. */
12272 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012273 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012274 }
12275 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012276#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012277
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012278}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012279
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012280static void hlua_deinit()
12281{
Willy Tarreau186f3762020-12-04 11:48:12 +010012282 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012283 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12284
12285 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12286 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012287
12288 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12289 if (hlua_states[thr])
12290 lua_close(hlua_states[thr]);
12291 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012292
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012293 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012294
Willy Tarreau0f143af2021-03-05 10:41:48 +010012295#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012296 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012297#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012298
12299 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012300}
12301
12302REGISTER_POST_DEINIT(hlua_deinit);
12303
Willy Tarreau80713382018-11-26 10:19:54 +010012304static void hlua_register_build_options(void)
12305{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012306 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012307
Willy Tarreaubb57d942016-12-21 19:04:56 +010012308 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12309 hap_register_build_opts(ptr, 1);
12310}
Willy Tarreau80713382018-11-26 10:19:54 +010012311
12312INITCALL0(STG_REGISTER, hlua_register_build_options);