blob: ab92ff79b862282ce9edd478f3b2300e4cc57caa [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;
2556 struct stream *s;
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;
2577 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002578
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002579 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002580 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002581 lua_pushnil(L);
2582 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002583 }
2584
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002585 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002586 xref_unlock(&socket->xref, peer);
2587 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002588}
2589
2590/* Returns information about my connection side. */
2591static int hlua_socket_getsockname(struct lua_State *L)
2592{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002593 struct hlua_socket *socket;
2594 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002595 struct appctx *appctx;
2596 struct xref *peer;
2597 struct stream_interface *si;
2598 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002599 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002600
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002601 MAY_LJMP(check_args(L, 1, "getsockname"));
2602
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002603 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002604
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002605 /* Check if we run on the same thread than the xreator thread.
2606 * We cannot access to the socket if the thread is different.
2607 */
2608 if (socket->tid != tid)
2609 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2610
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002611 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002612 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002613 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002614 lua_pushnil(L);
2615 return 1;
2616 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002617 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2618 si = appctx->owner;
2619 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002620
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002621 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002622 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002623 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002624 lua_pushnil(L);
2625 return 1;
2626 }
2627
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002628 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002629 xref_unlock(&socket->xref, peer);
2630 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002631}
2632
2633/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002634static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002635 .obj_type = OBJ_TYPE_APPLET,
2636 .name = "<LUA_TCP>",
2637 .fct = hlua_socket_handler,
2638 .release = hlua_socket_release,
2639};
2640
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002641__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002642{
2643 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002644 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002645 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002646 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002647 struct stream_interface *si;
2648 struct stream *s;
2649
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002650 /* Get hlua struct, or NULL if we execute from main lua state */
2651 hlua = hlua_gethlua(L);
2652 if (!hlua)
2653 return 0;
2654
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002655 /* Check if we run on the same thread than the xreator thread.
2656 * We cannot access to the socket if the thread is different.
2657 */
2658 if (socket->tid != tid)
2659 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2660
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002661 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002662 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002663 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002664 lua_pushnil(L);
2665 lua_pushstring(L, "Can't connect");
2666 return 2;
2667 }
2668 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2669 si = appctx->owner;
2670 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002671
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002672 /* Check if we run on the same thread than the xreator thread.
2673 * We cannot access to the socket if the thread is different.
2674 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002675 if (socket->tid != tid) {
2676 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002677 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002678 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002679
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002680 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002681 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002682 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002683 lua_pushnil(L);
2684 lua_pushstring(L, "Can't connect");
2685 return 2;
2686 }
2687
Willy Tarreaue09101e2018-10-16 17:37:12 +02002688 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002689
2690 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002691 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002692 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002693 lua_pushinteger(L, 1);
2694 return 1;
2695 }
2696
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002697 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2698 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002699 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002700 }
2701 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002702 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002703 return 0;
2704}
2705
2706/* This function fail or initite the connection. */
2707__LJMP static int hlua_socket_connect(struct lua_State *L)
2708{
2709 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002710 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002711 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002712 struct hlua *hlua;
2713 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002714 int low, high;
2715 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002716 struct xref *peer;
2717 struct stream_interface *si;
2718 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002719
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002720 if (lua_gettop(L) < 2)
2721 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002722
2723 /* Get args. */
2724 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002725
2726 /* Check if we run on the same thread than the xreator thread.
2727 * We cannot access to the socket if the thread is different.
2728 */
2729 if (socket->tid != tid)
2730 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2731
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002732 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002733 if (lua_gettop(L) >= 3) {
2734 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002735 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002736
Tim Duesterhus6edab862018-01-06 19:04:45 +01002737 /* Force the ip to end with a colon, to support IPv6 addresses
2738 * that are not enclosed within square brackets.
2739 */
2740 if (port > 0) {
2741 luaL_buffinit(L, &b);
2742 luaL_addstring(&b, ip);
2743 luaL_addchar(&b, ':');
2744 luaL_pushresult(&b);
2745 ip = lua_tolstring(L, lua_gettop(L), NULL);
2746 }
2747 }
2748
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002749 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002750 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002751 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002752 lua_pushnil(L);
2753 return 1;
2754 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002755
2756 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002757 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 +02002758 if (!addr) {
2759 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002760 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002761 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002762
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002763 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002764 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002765 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002766 if (port == -1) {
2767 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002768 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002769 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002770 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2771 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002772 if (port == -1) {
2773 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002774 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002775 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002776 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002777 }
2778 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002779
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002780 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2781 si = appctx->owner;
2782 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002783
Willy Tarreau9b7587a2020-10-15 07:32:10 +02002784 if (!sockaddr_alloc(&s->target_addr, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002785 xref_unlock(&socket->xref, peer);
2786 WILL_LJMP(luaL_error(L, "connect: internal error"));
2787 }
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002788 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002789
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002790 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002791 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002792 if (!hlua)
2793 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002794
2795 /* inform the stream that we want to be notified whenever the
2796 * connection completes.
2797 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002798 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002799 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002800 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002801
Willy Tarreauf31af932020-01-14 09:59:38 +01002802 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002803
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002804 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2805 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002806 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002807 }
2808 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002809
2810 task_wakeup(s->task, TASK_WOKEN_INIT);
2811 /* Return yield waiting for connection. */
2812
Willy Tarreau9635e032018-10-16 17:52:55 +02002813 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002814
2815 return 0;
2816}
2817
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002818#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002819__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2820{
2821 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002822 struct xref *peer;
2823 struct appctx *appctx;
2824 struct stream_interface *si;
2825 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002826
2827 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2828 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002829
2830 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002831 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002832 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002833 lua_pushnil(L);
2834 return 1;
2835 }
2836 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2837 si = appctx->owner;
2838 s = si_strm(si);
2839
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002840 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002841 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002842 return MAY_LJMP(hlua_socket_connect(L));
2843}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002844#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002845
2846__LJMP static int hlua_socket_setoption(struct lua_State *L)
2847{
2848 return 0;
2849}
2850
2851__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2852{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002853 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002854 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002855 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002856 struct xref *peer;
2857 struct appctx *appctx;
2858 struct stream_interface *si;
2859 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002860
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002861 MAY_LJMP(check_args(L, 2, "settimeout"));
2862
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002863 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002864
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002865 /* convert the timeout to millis */
2866 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002867
Thierry Fournier17a921b2018-03-08 09:59:02 +01002868 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002869 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002870 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2871
Mark Lakes56cc1252018-03-27 09:48:06 +02002872 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002873 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002874
2875 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002876 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002877 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002878
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002879 /* Check if we run on the same thread than the xreator thread.
2880 * We cannot access to the socket if the thread is different.
2881 */
2882 if (socket->tid != tid)
2883 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2884
Mark Lakes56cc1252018-03-27 09:48:06 +02002885 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002886 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002887 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002888 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2889 WILL_LJMP(lua_error(L));
2890 return 0;
2891 }
2892 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2893 si = appctx->owner;
2894 s = si_strm(si);
2895
Cyril Bonté7bb63452018-08-17 23:51:02 +02002896 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002897 s->req.rto = tmout;
2898 s->req.wto = tmout;
2899 s->res.rto = tmout;
2900 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002901 s->req.rex = tick_add_ifset(now_ms, tmout);
2902 s->req.wex = tick_add_ifset(now_ms, tmout);
2903 s->res.rex = tick_add_ifset(now_ms, tmout);
2904 s->res.wex = tick_add_ifset(now_ms, tmout);
2905
2906 s->task->expire = tick_add_ifset(now_ms, tmout);
2907 task_queue(s->task);
2908
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002909 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910
Thierry Fourniere9636f12018-03-08 09:54:32 +01002911 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002912 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002913}
2914
2915__LJMP static int hlua_socket_new(lua_State *L)
2916{
2917 struct hlua_socket *socket;
2918 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002919 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002920 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002921
2922 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002923 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002924 hlua_pusherror(L, "socket: full stack");
2925 goto out_fail_conf;
2926 }
2927
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002928 /* Create the object: obj[0] = userdata. */
2929 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002930 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002931 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002932 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002933 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002934
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002935 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002936 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002937 hlua_pusherror(L, "socket: uninitialized pools.");
2938 goto out_fail_conf;
2939 }
2940
Willy Tarreau87b09662015-04-03 00:22:06 +02002941 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002942 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2943 lua_setmetatable(L, -2);
2944
Willy Tarreaud420a972015-04-06 00:39:18 +02002945 /* Create the applet context */
Willy Tarreaue6124462021-09-13 10:07:38 +02002946 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002947 if (!appctx) {
2948 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002949 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002950 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002951
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002952 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002953 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002954 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2955 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002956
Willy Tarreaud420a972015-04-06 00:39:18 +02002957 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002958 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002959 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002960 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002961 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002962 }
2963
Christopher Faulet26256f82020-09-14 11:40:13 +02002964 strm = stream_new(sess, &appctx->obj_type, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002965 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002966 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002967 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002968 }
2969
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002970 /* Initialise cross reference between stream and Lua socket object. */
2971 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002972
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002973 /* Configure "right" stream interface. this "si" is used to connect
2974 * and retrieve data from the server. The connection is initialized
2975 * with the "struct server".
2976 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002977 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002978
2979 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002980 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002981 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002982
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002983 return 1;
2984
Willy Tarreaud420a972015-04-06 00:39:18 +02002985 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002986 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002987 out_fail_sess:
2988 appctx_free(appctx);
2989 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002990 WILL_LJMP(lua_error(L));
2991 return 0;
2992}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002993
2994/*
2995 *
2996 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002997 * Class Channel
2998 *
2999 *
3000 */
3001
3002/* Returns the struct hlua_channel join to the class channel in the
3003 * stack entry "ud" or throws an argument error.
3004 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003005__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003006{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003007 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003008}
3009
Willy Tarreau47860ed2015-03-10 14:07:50 +01003010/* Pushes the channel onto the top of the stack. If the stask does not have a
3011 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003012 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003013static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003014{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003015 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003016 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003017 return 0;
3018
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003019 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003020 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003021 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003022
3023 /* Pop a class sesison metatable and affect it to the userdata. */
3024 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3025 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003026 return 1;
3027}
3028
Christopher Faulet9f55a502020-02-25 15:21:02 +01003029/* Helper function returning a filter attached to a channel at the position <ud>
3030 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003031 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003032 * initialized.
3033 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003034static 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 +01003035{
3036 struct filter *filter = NULL;
3037
3038 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3039 struct hlua_flt_ctx *flt_ctx;
3040
3041 filter = lua_touserdata (L, -1);
3042 flt_ctx = filter->ctx;
3043 if (hlua_filter_from_payload(filter)) {
3044 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3045 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3046 }
3047 }
3048
3049 lua_pop(L, 1);
3050 return filter;
3051}
3052
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003053/* Copies <len> bytes of data present in the channel's buffer, starting at the
3054* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003055* responsibility to ensure <len> and <offset> are valid. It always return the
3056* length of the built string. <len> may be 0, in this case, an empty string is
3057* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003058*/
3059static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003060{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003061 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003062 luaL_Buffer b;
3063
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003064 block1 = len;
3065 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3066 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3067 block2 = len - block1;
3068
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003069 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003070 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3071 if (block2)
3072 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003073 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003074 return len;
3075}
3076
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003077/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3078 * function returns -1 if data cannot be copied. Otherwise, it returns the
3079 * number of bytes copied.
3080 */
3081static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3082{
3083 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003084
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003085 /* Nothing to do, just return */
3086 if (unlikely(istlen(str) == 0))
3087 goto end;
3088
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003089 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003090 ret = -1;
3091 goto end;
3092 }
3093 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3094
3095 end:
3096 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003097}
3098
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003099/* Removes <len> bytes of data at the absolute position <offset>.
3100 */
3101static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3102{
3103 size_t end = offset + len;
3104
3105 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3106 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3107 b_data(&chn->buf) - end, -len);
3108 b_sub(&chn->buf, len);
3109}
3110
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003111/* Copies input data in the channel's buffer. It is possible to set a specific
3112 * offset (0 by default) and a length (all remaining input data starting for the
3113 * offset by default). If there is not enough input data and more data can be
3114 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003115 *
3116 * From an action, All input data are considered. For a filter, the offset and
3117 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003118 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003119__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003120{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003121 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003122 struct filter *filter;
3123 size_t input, output;
3124 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003125
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003126 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003127
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003128 output = co_data(chn);
3129 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003130
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003131 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3132 if (filter && !hlua_filter_from_payload(filter))
3133 WILL_LJMP(lua_error(L));
3134
3135 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003136 if (lua_gettop(L) > 1) {
3137 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3138 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003139 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003140 offset += output;
3141 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003142 lua_pushfstring(L, "offset out of range.");
3143 WILL_LJMP(lua_error(L));
3144 }
3145 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003146 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003147 if (lua_gettop(L) == 3) {
3148 len = MAY_LJMP(luaL_checkinteger(L, 3));
3149 if (!len)
3150 goto dup;
3151 if (len == -1)
3152 len = global.tune.bufsize;
3153 if (len < 0) {
3154 lua_pushfstring(L, "length out of range.");
3155 WILL_LJMP(lua_error(L));
3156 }
3157 }
3158
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003159 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003160 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3161 /* Yield waiting for more data, as requested */
3162 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3163 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003164 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003165 }
3166
3167 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003168 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003169 return 1;
3170}
3171
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003172/* Copies the first line (including the trailing LF) of input data in the
3173 * channel's buffer. It is possible to set a specific offset (0 by default) and
3174 * a length (all remaining input data starting for the offset by default). If
3175 * there is not enough input data and more data can be received, the function
3176 * yields. If a length is explicitly specified, no more data are
3177 * copied. Otherwise, if no LF is found and more data can be received, this
3178 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003179 *
3180 * From an action, All input data are considered. For a filter, the offset and
3181 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003182 */
3183__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003184{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003185 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003186 struct filter *filter;
3187 size_t l, input, output;
3188 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003189
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003190 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003191 output = co_data(chn);
3192 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003193
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003194 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3195 if (filter && !hlua_filter_from_payload(filter))
3196 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003197
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003198 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003199 if (lua_gettop(L) > 1) {
3200 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3201 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003202 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003203 offset += output;
3204 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003205 lua_pushfstring(L, "offset out of range.");
3206 WILL_LJMP(lua_error(L));
3207 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003208 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003209
3210 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003211 if (lua_gettop(L) == 3) {
3212 len = MAY_LJMP(luaL_checkinteger(L, 3));
3213 if (!len)
3214 goto dup;
3215 if (len == -1)
3216 len = global.tune.bufsize;
3217 if (len < 0) {
3218 lua_pushfstring(L, "length out of range.");
3219 WILL_LJMP(lua_error(L));
3220 }
3221 }
3222
3223 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003224 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003225 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003226 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003227 len = l+1;
3228 goto dup;
3229 }
3230 }
3231
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003232 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003233 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3234 /* Yield waiting for more data */
3235 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3236 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003237 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003238 }
3239
3240 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003241 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003242 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003243}
3244
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003245/* [ DEPRECATED ]
3246 *
3247 * Duplicate all input data foud in the channel's buffer. The data are not
3248 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003249 *
3250 * From an action, All input data are considered. For a filter, the offset and
3251 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003252 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003253__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003254{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003255 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003256 struct filter *filter;
3257 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003258
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003259 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003260 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003261 if (IS_HTX_STRM(chn_strm(chn))) {
3262 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3263 WILL_LJMP(lua_error(L));
3264 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003265
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003266 offset = co_data(chn);
3267 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003268
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003269 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3270 if (filter && !hlua_filter_from_payload(filter))
3271 WILL_LJMP(lua_error(L));
3272
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003273 if (!ci_data(chn) && channel_input_closed(chn)) {
3274 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003275 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003276 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003277
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003278 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003279 return 1;
3280}
3281
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003282/* [ DEPRECATED ]
3283 *
3284 * Get all input data foud in the channel's buffer. The data are removed from
3285 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3286 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003287 *
3288 * From an action, All input data are considered. For a filter, the offset and
3289 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003290 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003291__LJMP static int hlua_channel_get(lua_State *L)
3292{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003293 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003294 struct filter *filter;
3295 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003296 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003297
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003298 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003299 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3300 if (IS_HTX_STRM(chn_strm(chn))) {
3301 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3302 WILL_LJMP(lua_error(L));
3303 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003304
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003305 offset = co_data(chn);
3306 len = ci_data(chn);
3307
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003308 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3309 if (filter && !hlua_filter_from_payload(filter))
3310 WILL_LJMP(lua_error(L));
3311
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003312 if (!ci_data(chn) && channel_input_closed(chn)) {
3313 lua_pushnil(L);
3314 return 1;
3315 }
3316
3317 ret = _hlua_channel_dup(chn, L, offset, len);
3318 _hlua_channel_delete(chn, offset, ret);
3319 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003320}
3321
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003322/* This functions consumes and returns one line. If the channel is closed,
3323 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003324 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003325 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003326 *
3327 * From an action, All input data are considered. For a filter, the offset and
3328 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003329 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003330__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003331{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003332 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003333 struct filter *filter;
3334 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003335 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003336
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003337 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003338
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003339 offset = co_data(chn);
3340 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003341
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003342 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3343 if (filter && !hlua_filter_from_payload(filter))
3344 WILL_LJMP(lua_error(L));
3345
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003346 if (!ci_data(chn) && channel_input_closed(chn)) {
3347 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003348 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003349 }
3350
3351 for (l = 0; l < len; l++) {
3352 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3353 len = l+1;
3354 goto dup;
3355 }
3356 }
3357
3358 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3359 /* Yield waiting for more data */
3360 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3361 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003362
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003363 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003364 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003365 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003366 return 1;
3367}
3368
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003369/* [ DEPRECATED ]
3370 *
3371 * Check arguments for the function "hlua_channel_getline_yield".
3372 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003373__LJMP static int hlua_channel_getline(lua_State *L)
3374{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003375 struct channel *chn;
3376
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003377 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003378 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3379 if (IS_HTX_STRM(chn_strm(chn))) {
3380 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3381 WILL_LJMP(lua_error(L));
3382 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003383 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3384}
3385
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003386/* Retrieves a given amount of input data at the given offset. By default all
3387 * available input data are returned. The offset may be negactive to start from
3388 * the end of input data. The length may be -1 to set it to the maximum buffer
3389 * size.
3390 */
3391__LJMP static int hlua_channel_get_data(lua_State *L)
3392{
3393 struct channel *chn;
3394
3395 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3396 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3397 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3398 if (IS_HTX_STRM(chn_strm(chn))) {
3399 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3400 WILL_LJMP(lua_error(L));
3401 }
3402 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3403}
3404
3405/* Retrieves a given amount of input data at the given offset. By default all
3406 * available input data are returned. The offset may be negactive to start from
3407 * the end of input data. The length may be -1 to set it to the maximum buffer
3408 * size.
3409 */
3410__LJMP static int hlua_channel_get_line(lua_State *L)
3411{
3412 struct channel *chn;
3413
3414 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3415 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3416 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3417 if (IS_HTX_STRM(chn_strm(chn))) {
3418 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3419 WILL_LJMP(lua_error(L));
3420 }
3421 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3422}
3423
3424/* Appends a string into the input side of channel. It returns the length of the
3425 * written string, or -1 if the channel is closed or if the buffer size is too
3426 * little for the data. 0 may be returned if nothing is copied. This function
3427 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003428 *
3429 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003430 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003431__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003432{
Christopher Faulet23976d92021-08-06 09:59:49 +02003433 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003434 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003435 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003436 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003437 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003438
3439 MAY_LJMP(check_args(L, 2, "append"));
3440 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003441 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003442 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003443 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003444 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003445 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003446
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003447 offset = co_data(chn);
3448 len = ci_data(chn);
3449
3450 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3451 if (filter && !hlua_filter_from_payload(filter))
3452 WILL_LJMP(lua_error(L));
3453
3454 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3455 if (ret > 0 && filter) {
3456 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3457
3458 flt_update_offsets(filter, chn, ret);
3459 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3460 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003461 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003462 return 1;
3463}
3464
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003465/* Prepends a string into the input side of channel. It returns the length of the
3466 * written string, or -1 if the channel is closed or if the buffer size is too
3467 * little for the data. 0 may be returned if nothing is copied. This function
3468 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003469 *
3470 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003471 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003472__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003473{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003474 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003475 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003476 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003477 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003478 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003479
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003480 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003481 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003482 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3483 if (IS_HTX_STRM(chn_strm(chn))) {
3484 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3485 WILL_LJMP(lua_error(L));
3486 }
3487
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003488 offset = co_data(chn);
3489 len = ci_data(chn);
3490
3491 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3492 if (filter && !hlua_filter_from_payload(filter))
3493 WILL_LJMP(lua_error(L));
3494
3495 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3496 if (ret > 0 && filter) {
3497 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3498
3499 flt_update_offsets(filter, chn, ret);
3500 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3501 }
3502
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003503 lua_pushinteger(L, ret);
3504 return 1;
3505}
3506
3507/* Inserts a given amount of input data at the given offset by a string
3508 * content. By default the string is appended at the end of input data. It
3509 * returns the length of the written string, or -1 if the channel is closed or
3510 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003511 *
3512 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003513 */
3514__LJMP static int hlua_channel_insert_data(lua_State *L)
3515{
3516 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003517 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003518 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003519 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003520 int ret, offset;
3521
3522 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3523 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3524 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3525 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003526
3527 output = co_data(chn);
3528 input = ci_data(chn);
3529
3530 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3531 if (filter && !hlua_filter_from_payload(filter))
3532 WILL_LJMP(lua_error(L));
3533
3534 offset = input + output;
3535 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003536 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003537 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003538 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003539 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003540 if (offset < output || offset > output + input) {
3541 lua_pushfstring(L, "offset out of range.");
3542 WILL_LJMP(lua_error(L));
3543 }
3544 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003545 if (IS_HTX_STRM(chn_strm(chn))) {
3546 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3547 WILL_LJMP(lua_error(L));
3548 }
3549
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003550 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3551 if (ret > 0 && filter) {
3552 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003553
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003554 flt_update_offsets(filter, chn, ret);
3555 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003556 }
3557
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003558 lua_pushinteger(L, ret);
3559 return 1;
3560}
3561/* Replaces a given amount of input data at the given offset by a string
3562 * content. By default all remaining data are removed (offset = 0 and len =
3563 * -1). It returns the length of the written string, or -1 if the channel is
3564 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003565 *
3566 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003567 */
3568__LJMP static int hlua_channel_set_data(lua_State *L)
3569{
3570 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003571 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003572 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003573 size_t sz, input, output;
3574 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003575
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003576 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3577 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3578 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3579 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003580
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003581 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003582 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003583 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003584 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003585
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003586 output = co_data(chn);
3587 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003588
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3590 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003591 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003592
3593 offset = output;
3594 if (lua_gettop(L) > 2) {
3595 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3596 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003597 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003598 offset += output;
3599 if (offset < output || offset > input + output) {
3600 lua_pushfstring(L, "offset out of range.");
3601 WILL_LJMP(lua_error(L));
3602 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003603 }
3604
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003605 len = output + input - offset;
3606 if (lua_gettop(L) == 4) {
3607 len = MAY_LJMP(luaL_checkinteger(L, 4));
3608 if (!len)
3609 goto set;
3610 if (len == -1)
3611 len = output + input - offset;
3612 if (len < 0 || offset + len > output + input) {
3613 lua_pushfstring(L, "length out of range.");
3614 WILL_LJMP(lua_error(L));
3615 }
3616 }
3617
3618 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003619 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003620 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003621 lua_pushinteger(L, -1);
3622 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623 _hlua_channel_delete(chn, offset, len);
3624 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3625 if (filter) {
3626 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3627
3628 len -= (ret > 0 ? ret : 0);
3629 flt_update_offsets(filter, chn, -len);
3630 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3631 }
3632
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003633 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003634 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003635 return 1;
3636}
3637
3638/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003639 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003640 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003641 *
3642 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003643 */
3644__LJMP static int hlua_channel_del_data(lua_State *L)
3645{
3646 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003647 struct filter *filter;
3648 size_t input, output;
3649 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003650
3651 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3652 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3653 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003654
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003655 if (IS_HTX_STRM(chn_strm(chn))) {
3656 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3657 WILL_LJMP(lua_error(L));
3658 }
3659
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003660 output = co_data(chn);
3661 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003662
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003663 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3664 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003665 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003666
3667 offset = output;
3668 if (lua_gettop(L) > 2) {
3669 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3670 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003671 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003672 offset += output;
3673 if (offset < output || offset > input + output) {
3674 lua_pushfstring(L, "offset out of range.");
3675 WILL_LJMP(lua_error(L));
3676 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003677 }
3678
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003679 len = output + input - offset;
3680 if (lua_gettop(L) == 4) {
3681 len = MAY_LJMP(luaL_checkinteger(L, 4));
3682 if (!len)
3683 goto end;
3684 if (len == -1)
3685 len = output + input - offset;
3686 if (len < 0 || offset + len > output + input) {
3687 lua_pushfstring(L, "length out of range.");
3688 WILL_LJMP(lua_error(L));
3689 }
3690 }
3691
3692 _hlua_channel_delete(chn, offset, len);
3693 if (filter) {
3694 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3695
3696 flt_update_offsets(filter, chn, -len);
3697 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3698 }
3699
3700 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003701 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003702 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003703}
3704
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003705/* Append data in the output side of the buffer. This data is immediately
3706 * sent. The function returns the amount of data written. If the buffer
3707 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003708 * if the channel is closed.
3709 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003710__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003711{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003712 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003713 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003714 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003715 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003716 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003717 struct hlua *hlua;
3718
3719 /* Get hlua struct, or NULL if we execute from main lua state */
3720 hlua = hlua_gethlua(L);
3721 if (!hlua) {
3722 lua_pushnil(L);
3723 return 1;
3724 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003725
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003726 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3727 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3728 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003729
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003730 offset = co_data(chn);
3731 len = ci_data(chn);
3732
3733 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3734 if (filter && !hlua_filter_from_payload(filter))
3735 WILL_LJMP(lua_error(L));
3736
3737
Willy Tarreau47860ed2015-03-10 14:07:50 +01003738 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003739 lua_pushinteger(L, -1);
3740 return 1;
3741 }
3742
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003743 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003744 if (len > sz -l) {
3745 if (filter) {
3746 lua_pushinteger(L, -1);
3747 return 1;
3748 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003749 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003750 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003751
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003752 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003753 if (ret == -1) {
3754 lua_pop(L, 1);
3755 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003756 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003757 }
3758 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003759 if (filter) {
3760 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3761
3762
3763 flt_update_offsets(filter, chn, ret);
3764 FLT_OFF(filter, chn) += ret;
3765 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3766 }
3767 else
3768 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003769
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003770 l += ret;
3771 lua_pop(L, 1);
3772 lua_pushinteger(L, l);
3773 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003774
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003775 if (l < sz) {
3776 /* Yield only if the channel's output is not empty.
3777 * Otherwise it means we cannot add more data. */
3778 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003779 return 1;
3780
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003781 /* If we are waiting for space in the response buffer, we
3782 * must set the flag WAKERESWR. This flag required the task
3783 * wake up if any activity is detected on the response buffer.
3784 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003785 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003786 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003787 else
3788 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003789 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003790 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003791
3792 return 1;
3793}
3794
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003795/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003796 * yield the LUA process, and resume it without checking the
3797 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003798 *
3799 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003800 */
3801__LJMP static int hlua_channel_send(lua_State *L)
3802{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003803 struct channel *chn;
3804
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003805 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003806 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3807 if (IS_HTX_STRM(chn_strm(chn))) {
3808 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3809 WILL_LJMP(lua_error(L));
3810 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003811 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003812 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003813}
3814
3815/* This function forward and amount of butes. The data pass from
3816 * the input side of the buffer to the output side, and can be
3817 * forwarded. This function never fails.
3818 *
3819 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003820 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003821 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003822__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003823{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003824 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003825 struct filter *filter;
3826 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003827 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003828 struct hlua *hlua;
3829
3830 /* Get hlua struct, or NULL if we execute from main lua state */
3831 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003832 if (!hlua) {
3833 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003834 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003835 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003836
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003837 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003839 l = MAY_LJMP(luaL_checkinteger(L, -1));
3840
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003841 offset = co_data(chn);
3842 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003843
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003844 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3845 if (filter && !hlua_filter_from_payload(filter))
3846 WILL_LJMP(lua_error(L));
3847
3848 max = fwd - l;
3849 if (max > len)
3850 max = len;
3851
3852 if (filter) {
3853 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3854
3855 FLT_OFF(filter, chn) += max;
3856 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3857 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3858 }
3859 else
3860 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003861
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003862 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003863 lua_pop(L, 1);
3864 lua_pushinteger(L, l);
3865
3866 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003867 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003868 /* The the input channel or the output channel are closed, we
3869 * must return the amount of data forwarded.
3870 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003871 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003872 return 1;
3873
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003874 /* If we are waiting for space data in the response buffer, we
3875 * must set the flag WAKERESWR. This flag required the task
3876 * wake up if any activity is detected on the response buffer.
3877 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003878 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003879 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003880 else
3881 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003882
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003883 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003884 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003885 }
3886
3887 return 1;
3888}
3889
3890/* Just check the input and prepare the stack for the previous
3891 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003892 *
3893 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003894 */
3895__LJMP static int hlua_channel_forward(lua_State *L)
3896{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003897 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003898
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003899 MAY_LJMP(check_args(L, 2, "forward"));
3900 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3901 if (IS_HTX_STRM(chn_strm(chn))) {
3902 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3903 WILL_LJMP(lua_error(L));
3904 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003905 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003906 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003907}
3908
3909/* Just returns the number of bytes available in the input
3910 * side of the buffer. This function never fails.
3911 */
3912__LJMP static int hlua_channel_get_in_len(lua_State *L)
3913{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003914 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003915 struct filter *filter;
3916 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003917
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003918 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003919 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003920
3921 output = co_data(chn);
3922 input = ci_data(chn);
3923 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3924 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3925 lua_pushinteger(L, input);
3926 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003927 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003928
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003929 lua_pushinteger(L, htx->data - co_data(chn));
3930 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003931 return 1;
3932}
3933
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003934/* Returns true if the channel is full. */
3935__LJMP static int hlua_channel_is_full(lua_State *L)
3936{
3937 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003938
3939 MAY_LJMP(check_args(L, 1, "is_full"));
3940 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003941 /* ignore the reserve, we are not on a producer side (ie in an
3942 * applet).
3943 */
3944 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003945 return 1;
3946}
3947
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003948/* Returns true if the channel may still receive data. */
3949__LJMP static int hlua_channel_may_recv(lua_State *L)
3950{
3951 struct channel *chn;
3952
3953 MAY_LJMP(check_args(L, 1, "may_recv"));
3954 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3955 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3956 return 1;
3957}
3958
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003959/* Returns true if the channel is the response channel. */
3960__LJMP static int hlua_channel_is_resp(lua_State *L)
3961{
3962 struct channel *chn;
3963
3964 MAY_LJMP(check_args(L, 1, "is_resp"));
3965 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3966
3967 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3968 return 1;
3969}
3970
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003971/* Just returns the number of bytes available in the output
3972 * side of the buffer. This function never fails.
3973 */
3974__LJMP static int hlua_channel_get_out_len(lua_State *L)
3975{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003976 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003977 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003978
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003979 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003980 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003981
3982 output = co_data(chn);
3983 input = ci_data(chn);
3984 hlua_channel_filter(L, 1, chn, &output, &input);
3985
3986 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003987 return 1;
3988}
3989
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003990/*
3991 *
3992 *
3993 * Class Fetches
3994 *
3995 *
3996 */
3997
3998/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003999 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004000 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004001__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004002{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004003 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004004}
4005
4006/* This function creates and push in the stack a fetch object according
4007 * with a current TXN.
4008 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004009static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004010{
Willy Tarreau7073c472015-04-06 11:15:40 +02004011 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004012
4013 /* Check stack size. */
4014 if (!lua_checkstack(L, 3))
4015 return 0;
4016
4017 /* Create the object: obj[0] = userdata.
4018 * Note that the base of the Fetches object is the
4019 * transaction object.
4020 */
4021 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004022 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004023 lua_rawseti(L, -2, 0);
4024
Willy Tarreau7073c472015-04-06 11:15:40 +02004025 hsmp->s = txn->s;
4026 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004027 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004028 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004029
4030 /* Pop a class sesison metatable and affect it to the userdata. */
4031 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4032 lua_setmetatable(L, -2);
4033
4034 return 1;
4035}
4036
4037/* This function is an LUA binding. It is called with each sample-fetch.
4038 * It uses closure argument to store the associated sample-fetch. It
4039 * returns only one argument or throws an error. An error is thrown
4040 * only if an error is encountered during the argument parsing. If
4041 * the "sample-fetch" function fails, nil is returned.
4042 */
4043__LJMP static int hlua_run_sample_fetch(lua_State *L)
4044{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004045 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004046 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004047 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004048 int i;
4049 struct sample smp;
4050
4051 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004052 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004053
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004054 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004055 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004056
Thierry FOURNIERca988662015-12-20 18:43:03 +01004057 /* Check execution authorization. */
4058 if (f->use & SMP_USE_HTTP_ANY &&
4059 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4060 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4061 "is not available in Lua services", f->kw);
4062 WILL_LJMP(lua_error(L));
4063 }
4064
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004065 /* Get extra arguments. */
4066 for (i = 0; i < lua_gettop(L) - 1; i++) {
4067 if (i >= ARGM_NBARGS)
4068 break;
4069 hlua_lua2arg(L, i + 2, &args[i]);
4070 }
4071 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004072 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004073
4074 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004075 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004076
4077 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004078 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004079 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004080 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004081 }
4082
4083 /* Initialise the sample. */
4084 memset(&smp, 0, sizeof(smp));
4085
4086 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004087 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004088 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004089 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004090 lua_pushstring(L, "");
4091 else
4092 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004093 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004094 }
4095
4096 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004097 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004098 hlua_smp2lua_str(L, &smp);
4099 else
4100 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004101
4102 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004103 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004104 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004105
4106 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004107 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004108 WILL_LJMP(lua_error(L));
4109 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004110}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004111
4112/*
4113 *
4114 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004115 * Class Converters
4116 *
4117 *
4118 */
4119
4120/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004121 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004122 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004123__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004124{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004125 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004126}
4127
4128/* This function creates and push in the stack a Converters object
4129 * according with a current TXN.
4130 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004131static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004132{
Willy Tarreau7073c472015-04-06 11:15:40 +02004133 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004134
4135 /* Check stack size. */
4136 if (!lua_checkstack(L, 3))
4137 return 0;
4138
4139 /* Create the object: obj[0] = userdata.
4140 * Note that the base of the Converters object is the
4141 * same than the TXN object.
4142 */
4143 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004144 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004145 lua_rawseti(L, -2, 0);
4146
Willy Tarreau7073c472015-04-06 11:15:40 +02004147 hsmp->s = txn->s;
4148 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004149 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004150 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004151
Willy Tarreau87b09662015-04-03 00:22:06 +02004152 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004153 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4154 lua_setmetatable(L, -2);
4155
4156 return 1;
4157}
4158
4159/* This function is an LUA binding. It is called with each converter.
4160 * It uses closure argument to store the associated converter. It
4161 * returns only one argument or throws an error. An error is thrown
4162 * only if an error is encountered during the argument parsing. If
4163 * the converter function function fails, nil is returned.
4164 */
4165__LJMP static int hlua_run_sample_conv(lua_State *L)
4166{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004167 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004168 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004169 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004170 int i;
4171 struct sample smp;
4172
4173 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004174 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004175
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004176 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004177 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004178
4179 /* Get extra arguments. */
4180 for (i = 0; i < lua_gettop(L) - 2; i++) {
4181 if (i >= ARGM_NBARGS)
4182 break;
4183 hlua_lua2arg(L, i + 3, &args[i]);
4184 }
4185 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004186 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004187
4188 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004189 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004190
4191 /* Run the special args checker. */
4192 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4193 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004194 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004195 }
4196
4197 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004198 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004199 if (!hlua_lua2smp(L, 2, &smp)) {
4200 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004201 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004202 }
4203
Willy Tarreau1777ea62016-03-10 16:15:46 +01004204 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4205
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004206 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004207 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004208 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004209 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004210 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004211 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004212 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4213 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004214 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004215 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004216 }
4217
4218 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004219 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004220 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004221 lua_pushstring(L, "");
4222 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004223 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004224 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004225 }
4226
4227 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004228 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004229 hlua_smp2lua_str(L, &smp);
4230 else
4231 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004232 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004233 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004234 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004235
4236 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004237 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004238 WILL_LJMP(lua_error(L));
4239 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004240}
4241
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004242/*
4243 *
4244 *
4245 * Class AppletTCP
4246 *
4247 *
4248 */
4249
4250/* Returns a struct hlua_txn if the stack entry "ud" is
4251 * a class stream, otherwise it throws an error.
4252 */
4253__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4254{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004255 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004256}
4257
4258/* This function creates and push in the stack an Applet object
4259 * according with a current TXN.
4260 */
4261static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4262{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004263 struct hlua_appctx *luactx;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004264 struct stream_interface *si = ctx->owner;
4265 struct stream *s = si_strm(si);
4266 struct proxy *p = s->be;
4267
4268 /* Check stack size. */
4269 if (!lua_checkstack(L, 3))
4270 return 0;
4271
4272 /* Create the object: obj[0] = userdata.
4273 * Note that the base of the Converters object is the
4274 * same than the TXN object.
4275 */
4276 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004277 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004278 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004279 luactx->appctx = ctx;
4280 luactx->htxn.s = s;
4281 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004282
4283 /* Create the "f" field that contains a list of fetches. */
4284 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004285 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004286 return 0;
4287 lua_settable(L, -3);
4288
4289 /* Create the "sf" field that contains a list of stringsafe fetches. */
4290 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004291 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004292 return 0;
4293 lua_settable(L, -3);
4294
4295 /* Create the "c" field that contains a list of converters. */
4296 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004297 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004298 return 0;
4299 lua_settable(L, -3);
4300
4301 /* Create the "sc" field that contains a list of stringsafe converters. */
4302 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004303 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004304 return 0;
4305 lua_settable(L, -3);
4306
4307 /* Pop a class stream metatable and affect it to the table. */
4308 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4309 lua_setmetatable(L, -2);
4310
4311 return 1;
4312}
4313
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004314__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4315{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004316 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004317 struct stream *s;
4318 const char *name;
4319 size_t len;
4320 struct sample smp;
4321
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004322 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4323 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004324
4325 /* It is useles to retrieve the stream, but this function
4326 * runs only in a stream context.
4327 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004328 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004329 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004330 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004331
4332 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004333 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004334 hlua_lua2smp(L, 3, &smp);
4335
4336 /* Store the sample in a variable. */
4337 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004338
4339 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4340 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4341 else
4342 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4343
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004344 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004345}
4346
4347__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4348{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004349 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004350 struct stream *s;
4351 const char *name;
4352 size_t len;
4353 struct sample smp;
4354
4355 MAY_LJMP(check_args(L, 2, "unset_var"));
4356
4357 /* It is useles to retrieve the stream, but this function
4358 * runs only in a stream context.
4359 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004360 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004361 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004362 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004363
4364 /* Unset the variable. */
4365 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004366 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4367 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004368}
4369
4370__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4371{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004372 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004373 struct stream *s;
4374 const char *name;
4375 size_t len;
4376 struct sample smp;
4377
4378 MAY_LJMP(check_args(L, 2, "get_var"));
4379
4380 /* It is useles to retrieve the stream, but this function
4381 * runs only in a stream context.
4382 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004383 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004384 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004385 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004386
4387 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004388 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004389 lua_pushnil(L);
4390 return 1;
4391 }
4392
4393 return hlua_smp2lua(L, &smp);
4394}
4395
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004396__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4397{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004398 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4399 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004400 struct hlua *hlua;
4401
4402 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004403 if (!s->hlua)
4404 return 0;
4405 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004406
4407 MAY_LJMP(check_args(L, 2, "set_priv"));
4408
4409 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004410 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004411
4412 /* Get and store new value. */
4413 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4414 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4415
4416 return 0;
4417}
4418
4419__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4420{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004421 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4422 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004423 struct hlua *hlua;
4424
4425 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004426 if (!s->hlua) {
4427 lua_pushnil(L);
4428 return 1;
4429 }
4430 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004431
4432 /* Push configuration index in the stack. */
4433 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4434
4435 return 1;
4436}
4437
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004438/* If expected data not yet available, it returns a yield. This function
4439 * consumes the data in the buffer. It returns a string containing the
4440 * data. This string can be empty.
4441 */
4442__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4443{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004444 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4445 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004446 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004447 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004448 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004449 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004450 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004451
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004452 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004453 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004454
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004455 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004456 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004457 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004458 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004459 }
4460
4461 /* End of data: commit the total strings and return. */
4462 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004463 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004464 return 1;
4465 }
4466
4467 /* Ensure that the block 2 length is usable. */
4468 if (ret == 1)
4469 len2 = 0;
4470
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004471 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004472 luaL_addlstring(&luactx->b, blk1, len1);
4473 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004474
4475 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004476 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004477 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004478 return 1;
4479}
4480
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004481/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004482__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4483{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004484 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004485
4486 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004487 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004488
4489 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4490}
4491
4492/* If expected data not yet available, it returns a yield. This function
4493 * consumes the data in the buffer. It returns a string containing the
4494 * data. This string can be empty.
4495 */
4496__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4497{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004498 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4499 struct stream_interface *si = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004500 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004501 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004502 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004503 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004504 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004505 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004506
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004507 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004508 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004509
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004510 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004511 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004512 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004513 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004514 }
4515
4516 /* End of data: commit the total strings and return. */
4517 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004518 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004519 return 1;
4520 }
4521
4522 /* Ensure that the block 2 length is usable. */
4523 if (ret == 1)
4524 len2 = 0;
4525
4526 if (len == -1) {
4527
4528 /* If len == -1, catenate all the data avalaile and
4529 * yield because we want to get all the data until
4530 * the end of data stream.
4531 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004532 luaL_addlstring(&luactx->b, blk1, len1);
4533 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004534 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004535 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004536 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004537
4538 } else {
4539
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004540 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004541 if (len1 > len)
4542 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004543 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004544 len -= len1;
4545
4546 /* Copy the second block. */
4547 if (len2 > len)
4548 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004549 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004550 len -= len2;
4551
4552 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004553 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004554
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004555 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004556 if (len > 0) {
4557 lua_pushinteger(L, len);
4558 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004559 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004560 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004561 }
4562
4563 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004564 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004565 return 1;
4566 }
4567
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004568 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004569 hlua_pusherror(L, "Lua: internal error");
4570 WILL_LJMP(lua_error(L));
4571 return 0;
4572}
4573
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004574/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004575__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4576{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004577 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004578 int len = -1;
4579
4580 if (lua_gettop(L) > 2)
4581 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4582 if (lua_gettop(L) >= 2) {
4583 len = MAY_LJMP(luaL_checkinteger(L, 2));
4584 lua_pop(L, 1);
4585 }
4586
4587 /* Confirm or set the required length */
4588 lua_pushinteger(L, len);
4589
4590 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004591 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004592
4593 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4594}
4595
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004596/* Append data in the output side of the buffer. This data is immediately
4597 * sent. The function returns the amount of data written. If the buffer
4598 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004599 * if the channel is closed.
4600 */
4601__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4602{
4603 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004604 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004605 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4606 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004607 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004608 struct channel *chn = si_ic(si);
4609 int max;
4610
4611 /* Get the max amount of data which can write as input in the channel. */
4612 max = channel_recv_max(chn);
4613 if (max > (len - l))
4614 max = len - l;
4615
4616 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004617 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004618
4619 /* update counters. */
4620 l += max;
4621 lua_pop(L, 1);
4622 lua_pushinteger(L, l);
4623
4624 /* If some data is not send, declares the situation to the
4625 * applet, and returns a yield.
4626 */
4627 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004628 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004629 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004630 }
4631
4632 return 1;
4633}
4634
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004635/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004636 * yield the LUA process, and resume it without checking the
4637 * input arguments.
4638 */
4639__LJMP static int hlua_applet_tcp_send(lua_State *L)
4640{
4641 MAY_LJMP(check_args(L, 2, "send"));
4642 lua_pushinteger(L, 0);
4643
4644 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4645}
4646
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004647/*
4648 *
4649 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004650 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004651 *
4652 *
4653 */
4654
4655/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004656 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004657 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004658__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004659{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004660 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004661}
4662
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004663/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004664 * according with a current TXN.
4665 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004666static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004667{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004668 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004669 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004670 struct stream_interface *si = ctx->owner;
4671 struct stream *s = si_strm(si);
4672 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004673 struct htx *htx;
4674 struct htx_blk *blk;
4675 struct htx_sl *sl;
4676 struct ist path;
4677 unsigned long long len = 0;
4678 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004679 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004680
4681 /* Check stack size. */
4682 if (!lua_checkstack(L, 3))
4683 return 0;
4684
4685 /* Create the object: obj[0] = userdata.
4686 * Note that the base of the Converters object is the
4687 * same than the TXN object.
4688 */
4689 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004690 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004691 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004692 luactx->appctx = ctx;
4693 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4694 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4695 luactx->htxn.s = s;
4696 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004697
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004698 /* Create the "f" field that contains a list of fetches. */
4699 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004700 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004701 return 0;
4702 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004703
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004704 /* Create the "sf" field that contains a list of stringsafe fetches. */
4705 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004706 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004707 return 0;
4708 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004709
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004710 /* Create the "c" field that contains a list of converters. */
4711 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004712 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004713 return 0;
4714 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004715
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004716 /* Create the "sc" field that contains a list of stringsafe converters. */
4717 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004718 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004719 return 0;
4720 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004721
Christopher Fauleta2097962019-07-15 16:25:33 +02004722 htx = htxbuf(&s->req.buf);
4723 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004724 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004725 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004726
Christopher Fauleta2097962019-07-15 16:25:33 +02004727 /* Stores the request method. */
4728 lua_pushstring(L, "method");
4729 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4730 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004731
Christopher Fauleta2097962019-07-15 16:25:33 +02004732 /* Stores the http version. */
4733 lua_pushstring(L, "version");
4734 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4735 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004736
Christopher Fauleta2097962019-07-15 16:25:33 +02004737 /* creates an array of headers. hlua_http_get_headers() crates and push
4738 * the array on the top of the stack.
4739 */
4740 lua_pushstring(L, "headers");
4741 htxn.s = s;
4742 htxn.p = px;
4743 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004744 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004745 return 0;
4746 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004747
Amaury Denoyellec453f952021-07-06 11:40:12 +02004748 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4749 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004750 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004751 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004752
Christopher Fauleta2097962019-07-15 16:25:33 +02004753 p = path.ptr;
4754 end = path.ptr + path.len;
4755 q = p;
4756 while (q < end && *q != '?')
4757 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004758
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004759 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004760 lua_pushstring(L, "path");
4761 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004762 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004763
Christopher Fauleta2097962019-07-15 16:25:33 +02004764 /* Stores the query string. */
4765 lua_pushstring(L, "qs");
4766 if (*q == '?')
4767 q++;
4768 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004769 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004770 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004771
Christopher Fauleta2097962019-07-15 16:25:33 +02004772 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4773 struct htx_blk *blk = htx_get_blk(htx, pos);
4774 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004775
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004776 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004777 break;
4778 if (type == HTX_BLK_DATA)
4779 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004780 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004781 if (htx->extra != ULLONG_MAX)
4782 len += htx->extra;
4783
4784 /* Stores the request path. */
4785 lua_pushstring(L, "length");
4786 lua_pushinteger(L, len);
4787 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004788
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004789 /* Create an empty array of HTTP request headers. */
4790 lua_pushstring(L, "response");
4791 lua_newtable(L);
4792 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004793
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004794 /* Pop a class stream metatable and affect it to the table. */
4795 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4796 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004797
4798 return 1;
4799}
4800
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004801__LJMP static int hlua_applet_http_set_var(lua_State *L)
4802{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004803 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004804 struct stream *s;
4805 const char *name;
4806 size_t len;
4807 struct sample smp;
4808
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004809 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4810 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004811
4812 /* It is useles to retrieve the stream, but this function
4813 * runs only in a stream context.
4814 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004815 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004816 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004817 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004818
4819 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004820 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004821 hlua_lua2smp(L, 3, &smp);
4822
4823 /* Store the sample in a variable. */
4824 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004825
4826 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4827 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4828 else
4829 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4830
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004831 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004832}
4833
4834__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4835{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004836 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004837 struct stream *s;
4838 const char *name;
4839 size_t len;
4840 struct sample smp;
4841
4842 MAY_LJMP(check_args(L, 2, "unset_var"));
4843
4844 /* It is useles to retrieve the stream, but this function
4845 * runs only in a stream context.
4846 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004847 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004848 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004849 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004850
4851 /* Unset the variable. */
4852 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004853 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4854 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004855}
4856
4857__LJMP static int hlua_applet_http_get_var(lua_State *L)
4858{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004859 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004860 struct stream *s;
4861 const char *name;
4862 size_t len;
4863 struct sample smp;
4864
4865 MAY_LJMP(check_args(L, 2, "get_var"));
4866
4867 /* It is useles to retrieve the stream, but this function
4868 * runs only in a stream context.
4869 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004870 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004871 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004872 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004873
4874 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004875 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004876 lua_pushnil(L);
4877 return 1;
4878 }
4879
4880 return hlua_smp2lua(L, &smp);
4881}
4882
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004883__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4884{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004885 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4886 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004887 struct hlua *hlua;
4888
4889 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004890 if (!s->hlua)
4891 return 0;
4892 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004893
4894 MAY_LJMP(check_args(L, 2, "set_priv"));
4895
4896 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004897 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004898
4899 /* Get and store new value. */
4900 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4901 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4902
4903 return 0;
4904}
4905
4906__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4907{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004908 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4909 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004910 struct hlua *hlua;
4911
4912 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004913 if (!s->hlua) {
4914 lua_pushnil(L);
4915 return 1;
4916 }
4917 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004918
4919 /* Push configuration index in the stack. */
4920 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4921
4922 return 1;
4923}
4924
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004925/* If expected data not yet available, it returns a yield. This function
4926 * consumes the data in the buffer. It returns a string containing the
4927 * data. This string can be empty.
4928 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004929__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004930{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004931 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4932 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004933 struct channel *req = si_oc(si);
4934 struct htx *htx;
4935 struct htx_blk *blk;
4936 size_t count;
4937 int stop = 0;
4938
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004939 htx = htx_from_buf(&req->buf);
4940 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004941 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004942
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004943 while (count && !stop && blk) {
4944 enum htx_blk_type type = htx_get_blk_type(blk);
4945 uint32_t sz = htx_get_blksz(blk);
4946 struct ist v;
4947 uint32_t vlen;
4948 char *nl;
4949
4950 vlen = sz;
4951 if (vlen > count) {
4952 if (type != HTX_BLK_DATA)
4953 break;
4954 vlen = count;
4955 }
4956
4957 switch (type) {
4958 case HTX_BLK_UNUSED:
4959 break;
4960
4961 case HTX_BLK_DATA:
4962 v = htx_get_blk_value(htx, blk);
4963 v.len = vlen;
4964 nl = istchr(v, '\n');
4965 if (nl != NULL) {
4966 stop = 1;
4967 vlen = nl - v.ptr + 1;
4968 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004969 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004970 break;
4971
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004972 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004973 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004974 stop = 1;
4975 break;
4976
4977 default:
4978 break;
4979 }
4980
4981 co_set_data(req, co_data(req) - vlen);
4982 count -= vlen;
4983 if (sz == vlen)
4984 blk = htx_remove_blk(htx, blk);
4985 else {
4986 htx_cut_data_blk(htx, blk, vlen);
4987 break;
4988 }
4989 }
4990
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004991 /* The message was fully consumed and no more data are expected
4992 * (EOM flag set).
4993 */
4994 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
4995 stop = 1;
4996
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004997 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004998 if (!stop) {
4999 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005000 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005001 }
5002
5003 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005004 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005005 return 1;
5006}
5007
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005008
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005009/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005010__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005011{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005012 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005013
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005014 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005015 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005016
Christopher Fauleta2097962019-07-15 16:25:33 +02005017 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005018}
5019
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005020/* If expected data not yet available, it returns a yield. This function
5021 * consumes the data in the buffer. It returns a string containing the
5022 * data. This string can be empty.
5023 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005024__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005025{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005026 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5027 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005028 struct channel *req = si_oc(si);
5029 struct htx *htx;
5030 struct htx_blk *blk;
5031 size_t count;
5032 int len;
5033
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005034 htx = htx_from_buf(&req->buf);
5035 len = MAY_LJMP(luaL_checkinteger(L, 2));
5036 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005037 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005038 while (count && len && blk) {
5039 enum htx_blk_type type = htx_get_blk_type(blk);
5040 uint32_t sz = htx_get_blksz(blk);
5041 struct ist v;
5042 uint32_t vlen;
5043
5044 vlen = sz;
5045 if (len > 0 && vlen > len)
5046 vlen = len;
5047 if (vlen > count) {
5048 if (type != HTX_BLK_DATA)
5049 break;
5050 vlen = count;
5051 }
5052
5053 switch (type) {
5054 case HTX_BLK_UNUSED:
5055 break;
5056
5057 case HTX_BLK_DATA:
5058 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005059 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005060 break;
5061
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005062 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005063 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005064 len = 0;
5065 break;
5066
5067 default:
5068 break;
5069 }
5070
5071 co_set_data(req, co_data(req) - vlen);
5072 count -= vlen;
5073 if (len > 0)
5074 len -= vlen;
5075 if (sz == vlen)
5076 blk = htx_remove_blk(htx, blk);
5077 else {
5078 htx_cut_data_blk(htx, blk, vlen);
5079 break;
5080 }
5081 }
5082
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005083 /* The message was fully consumed and no more data are expected
5084 * (EOM flag set).
5085 */
5086 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5087 len = 0;
5088
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005089 htx_to_buf(htx, &req->buf);
5090
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005091 /* If we are no other data available, yield waiting for new data. */
5092 if (len) {
5093 if (len > 0) {
5094 lua_pushinteger(L, len);
5095 lua_replace(L, 2);
5096 }
5097 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005098 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005099 }
5100
5101 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005102 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005103 return 1;
5104}
5105
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005106/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005107__LJMP static int hlua_applet_http_recv(lua_State *L)
5108{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005109 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005110 int len = -1;
5111
5112 /* Check arguments. */
5113 if (lua_gettop(L) > 2)
5114 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5115 if (lua_gettop(L) >= 2) {
5116 len = MAY_LJMP(luaL_checkinteger(L, 2));
5117 lua_pop(L, 1);
5118 }
5119
Christopher Fauleta2097962019-07-15 16:25:33 +02005120 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005121
Christopher Fauleta2097962019-07-15 16:25:33 +02005122 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005123 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005124
Christopher Fauleta2097962019-07-15 16:25:33 +02005125 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005126}
5127
5128/* Append data in the output side of the buffer. This data is immediately
5129 * sent. The function returns the amount of data written. If the buffer
5130 * cannot contain the data, the function yields. The function returns -1
5131 * if the channel is closed.
5132 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005133__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005134{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005135 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5136 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005137 struct channel *res = si_ic(si);
5138 struct htx *htx = htx_from_buf(&res->buf);
5139 const char *data;
5140 size_t len;
5141 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5142 int max;
5143
Christopher Faulet9060fc02019-07-03 11:39:30 +02005144 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005145 if (!max)
5146 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005147
5148 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5149
5150 /* Get the max amount of data which can write as input in the channel. */
5151 if (max > (len - l))
5152 max = len - l;
5153
5154 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005155 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005156 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005157
5158 /* update counters. */
5159 l += max;
5160 lua_pop(L, 1);
5161 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005162
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005163 /* If some data is not send, declares the situation to the
5164 * applet, and returns a yield.
5165 */
5166 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005167 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005168 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005169 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005170 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005171 }
5172
Christopher Fauleta2097962019-07-15 16:25:33 +02005173 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005174 return 1;
5175}
5176
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005177/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005178 * yield the LUA process, and resume it without checking the
5179 * input arguments.
5180 */
5181__LJMP static int hlua_applet_http_send(lua_State *L)
5182{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005183 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005184
5185 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005186 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005187 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5188 WILL_LJMP(lua_error(L));
5189 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005190
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005191 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005192 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005193
Christopher Fauleta2097962019-07-15 16:25:33 +02005194 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005195}
5196
5197__LJMP static int hlua_applet_http_addheader(lua_State *L)
5198{
5199 const char *name;
5200 int ret;
5201
5202 MAY_LJMP(hlua_checkapplet_http(L, 1));
5203 name = MAY_LJMP(luaL_checkstring(L, 2));
5204 MAY_LJMP(luaL_checkstring(L, 3));
5205
5206 /* Push in the stack the "response" entry. */
5207 ret = lua_getfield(L, 1, "response");
5208 if (ret != LUA_TTABLE) {
5209 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5210 "is expected as an array. %s found", lua_typename(L, ret));
5211 WILL_LJMP(lua_error(L));
5212 }
5213
5214 /* check if the header is already registered if it is not
5215 * the case, register it.
5216 */
5217 ret = lua_getfield(L, -1, name);
5218 if (ret == LUA_TNIL) {
5219
5220 /* Entry not found. */
5221 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5222
5223 /* Insert the new header name in the array in the top of the stack.
5224 * It left the new array in the top of the stack.
5225 */
5226 lua_newtable(L);
5227 lua_pushvalue(L, 2);
5228 lua_pushvalue(L, -2);
5229 lua_settable(L, -4);
5230
5231 } else if (ret != LUA_TTABLE) {
5232
5233 /* corruption error. */
5234 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5235 "is expected as an array. %s found", name, lua_typename(L, ret));
5236 WILL_LJMP(lua_error(L));
5237 }
5238
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005239 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005240 * the header value as new entry.
5241 */
5242 lua_pushvalue(L, 3);
5243 ret = lua_rawlen(L, -2);
5244 lua_rawseti(L, -2, ret + 1);
5245 lua_pushboolean(L, 1);
5246 return 1;
5247}
5248
5249__LJMP static int hlua_applet_http_status(lua_State *L)
5250{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005251 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005252 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005253 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005254
5255 if (status < 100 || status > 599) {
5256 lua_pushboolean(L, 0);
5257 return 1;
5258 }
5259
Willy Tarreau7e702d12021-04-28 17:59:21 +02005260 luactx->appctx->ctx.hlua_apphttp.status = status;
5261 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005262 lua_pushboolean(L, 1);
5263 return 1;
5264}
5265
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005266
Christopher Fauleta2097962019-07-15 16:25:33 +02005267__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005268{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005269 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5270 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005271 struct channel *res = si_ic(si);
5272 struct htx *htx;
5273 struct htx_sl *sl;
5274 struct h1m h1m;
5275 const char *status, *reason;
5276 const char *name, *value;
5277 size_t nlen, vlen;
5278 unsigned int flags;
5279
5280 /* Send the message at once. */
5281 htx = htx_from_buf(&res->buf);
5282 h1m_init_res(&h1m);
5283
5284 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005285 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5286 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005287 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005288 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5289 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005290 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5291 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5292 }
5293 else {
5294 flags = HTX_SL_F_IS_RESP;
5295 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5296 }
5297 if (!sl) {
5298 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005299 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005300 WILL_LJMP(lua_error(L));
5301 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005302 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005303
5304 /* Get the array associated to the field "response" in the object AppletHTTP. */
5305 lua_pushvalue(L, 0);
5306 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5307 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005308 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005309 WILL_LJMP(lua_error(L));
5310 }
5311
5312 /* Browse the list of headers. */
5313 lua_pushnil(L);
5314 while(lua_next(L, -2) != 0) {
5315 /* We expect a string as -2. */
5316 if (lua_type(L, -2) != LUA_TSTRING) {
5317 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005318 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005319 lua_typename(L, lua_type(L, -2)));
5320 WILL_LJMP(lua_error(L));
5321 }
5322 name = lua_tolstring(L, -2, &nlen);
5323
5324 /* We expect an array as -1. */
5325 if (lua_type(L, -1) != LUA_TTABLE) {
5326 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 +02005327 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005328 name,
5329 lua_typename(L, lua_type(L, -1)));
5330 WILL_LJMP(lua_error(L));
5331 }
5332
5333 /* Browse the table who is on the top of the stack. */
5334 lua_pushnil(L);
5335 while(lua_next(L, -2) != 0) {
5336 int id;
5337
5338 /* We expect a number as -2. */
5339 if (lua_type(L, -2) != LUA_TNUMBER) {
5340 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 +02005341 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342 name,
5343 lua_typename(L, lua_type(L, -2)));
5344 WILL_LJMP(lua_error(L));
5345 }
5346 id = lua_tointeger(L, -2);
5347
5348 /* We expect a string as -2. */
5349 if (lua_type(L, -1) != LUA_TSTRING) {
5350 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 +02005351 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005352 name, id,
5353 lua_typename(L, lua_type(L, -1)));
5354 WILL_LJMP(lua_error(L));
5355 }
5356 value = lua_tolstring(L, -1, &vlen);
5357
5358 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005359 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5360 int ret;
5361
5362 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5363 if (ret < 0) {
5364 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5365 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5366 name);
5367 WILL_LJMP(lua_error(L));
5368 }
5369 else if (ret == 0)
5370 goto next; /* Skip it */
5371 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005372 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5373 struct ist v = ist2(value, vlen);
5374 int ret;
5375
5376 ret = h1_parse_cont_len_header(&h1m, &v);
5377 if (ret < 0) {
5378 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005379 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005380 name);
5381 WILL_LJMP(lua_error(L));
5382 }
5383 else if (ret == 0)
5384 goto next; /* Skip it */
5385 }
5386
5387 /* Add a new header */
5388 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5389 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005390 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005391 name);
5392 WILL_LJMP(lua_error(L));
5393 }
5394 next:
5395 /* Remove the array from the stack, and get next element with a remaining string. */
5396 lua_pop(L, 1);
5397 }
5398
5399 /* Remove the array from the stack, and get next element with a remaining string. */
5400 lua_pop(L, 1);
5401 }
5402
5403 if (h1m.flags & H1_MF_CHNK)
5404 h1m.flags &= ~H1_MF_CLEN;
5405 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5406 h1m.flags |= H1_MF_XFER_LEN;
5407
5408 /* Uset HTX start-line flags */
5409 if (h1m.flags & H1_MF_XFER_ENC)
5410 flags |= HTX_SL_F_XFER_ENC;
5411 if (h1m.flags & H1_MF_XFER_LEN) {
5412 flags |= HTX_SL_F_XFER_LEN;
5413 if (h1m.flags & H1_MF_CHNK)
5414 flags |= HTX_SL_F_CHNK;
5415 else if (h1m.flags & H1_MF_CLEN)
5416 flags |= HTX_SL_F_CLEN;
5417 if (h1m.body_len == 0)
5418 flags |= HTX_SL_F_BODYLESS;
5419 }
5420 sl->flags |= flags;
5421
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005422 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005423 * and the status code implies the presence of a message body, we must
5424 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005425 * for the keepalive compliance. If the applet announces a transfer-encoding
5426 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005427 */
5428 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005429 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5430 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5431 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005432 /* Add a new header */
5433 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5434 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5435 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005436 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005437 WILL_LJMP(lua_error(L));
5438 }
5439 }
5440
5441 /* Finalize headers. */
5442 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5443 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005444 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005445 WILL_LJMP(lua_error(L));
5446 }
5447
5448 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5449 b_reset(&res->buf);
5450 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5451 WILL_LJMP(lua_error(L));
5452 }
5453
5454 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005455 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005456
5457 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005458 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005459 return 0;
5460
5461}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005462/* We will build the status line and the headers of the HTTP response.
5463 * We will try send at once if its not possible, we give back the hand
5464 * waiting for more room.
5465 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005466__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005467{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005468 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5469 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005470 struct channel *res = si_ic(si);
5471
5472 if (co_data(res)) {
5473 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005474 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005475 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005476 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005477}
5478
5479
Christopher Fauleta2097962019-07-15 16:25:33 +02005480__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005481{
Christopher Fauleta2097962019-07-15 16:25:33 +02005482 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005483}
5484
Christopher Fauleta2097962019-07-15 16:25:33 +02005485/*
5486 *
5487 *
5488 * Class HTTP
5489 *
5490 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005491 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005492
5493/* Returns a struct hlua_txn if the stack entry "ud" is
5494 * a class stream, otherwise it throws an error.
5495 */
5496__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005497{
Christopher Fauleta2097962019-07-15 16:25:33 +02005498 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5499}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005500
Christopher Fauleta2097962019-07-15 16:25:33 +02005501/* This function creates and push in the stack a HTTP object
5502 * according with a current TXN.
5503 */
5504static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5505{
5506 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005507
Christopher Fauleta2097962019-07-15 16:25:33 +02005508 /* Check stack size. */
5509 if (!lua_checkstack(L, 3))
5510 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005511
Christopher Fauleta2097962019-07-15 16:25:33 +02005512 /* Create the object: obj[0] = userdata.
5513 * Note that the base of the Converters object is the
5514 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005515 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005516 lua_newtable(L);
5517 htxn = lua_newuserdata(L, sizeof(*htxn));
5518 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005519
5520 htxn->s = txn->s;
5521 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005522 htxn->dir = txn->dir;
5523 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005524
5525 /* Pop a class stream metatable and affect it to the table. */
5526 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5527 lua_setmetatable(L, -2);
5528
5529 return 1;
5530}
5531
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005532/* This function creates and returns an array containing the status-line
5533 * elements. This function does not fails.
5534 */
5535__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5536{
5537 /* Create the table. */
5538 lua_newtable(L);
5539
5540 if (sl->flags & HTX_SL_F_IS_RESP) {
5541 lua_pushstring(L, "version");
5542 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5543 lua_settable(L, -3);
5544 lua_pushstring(L, "code");
5545 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5546 lua_settable(L, -3);
5547 lua_pushstring(L, "reason");
5548 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5549 lua_settable(L, -3);
5550 }
5551 else {
5552 lua_pushstring(L, "method");
5553 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5554 lua_settable(L, -3);
5555 lua_pushstring(L, "uri");
5556 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5557 lua_settable(L, -3);
5558 lua_pushstring(L, "version");
5559 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5560 lua_settable(L, -3);
5561 }
5562 return 1;
5563}
5564
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005565/* This function creates ans returns an array of HTTP headers.
5566 * This function does not fails. It is used as wrapper with the
5567 * 2 following functions.
5568 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005569__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005570{
Christopher Fauleta2097962019-07-15 16:25:33 +02005571 struct htx *htx;
5572 int32_t pos;
5573
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005574 /* Create the table. */
5575 lua_newtable(L);
5576
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005577
Christopher Fauleta2097962019-07-15 16:25:33 +02005578 htx = htxbuf(&msg->chn->buf);
5579 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5580 struct htx_blk *blk = htx_get_blk(htx, pos);
5581 enum htx_blk_type type = htx_get_blk_type(blk);
5582 struct ist n, v;
5583 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005584
Christopher Fauleta2097962019-07-15 16:25:33 +02005585 if (type == HTX_BLK_HDR) {
5586 n = htx_get_blk_name(htx,blk);
5587 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005588 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005589 else if (type == HTX_BLK_EOH)
5590 break;
5591 else
5592 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005593
Christopher Fauleta2097962019-07-15 16:25:33 +02005594 /* Check for existing entry:
5595 * assume that the table is on the top of the stack, and
5596 * push the key in the stack, the function lua_gettable()
5597 * perform the lookup.
5598 */
5599 lua_pushlstring(L, n.ptr, n.len);
5600 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005601
Christopher Fauleta2097962019-07-15 16:25:33 +02005602 switch (lua_type(L, -1)) {
5603 case LUA_TNIL:
5604 /* Table not found, create it. */
5605 lua_pop(L, 1); /* remove the nil value. */
5606 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5607 lua_newtable(L); /* create and push empty table. */
5608 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5609 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5610 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005611 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005612
Christopher Fauleta2097962019-07-15 16:25:33 +02005613 case LUA_TTABLE:
5614 /* Entry found: push the value in the table. */
5615 len = lua_rawlen(L, -1);
5616 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5617 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5618 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5619 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005620
Christopher Fauleta2097962019-07-15 16:25:33 +02005621 default:
5622 /* Other cases are errors. */
5623 hlua_pusherror(L, "internal error during the parsing of headers.");
5624 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005625 }
5626 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005627 return 1;
5628}
5629
5630__LJMP static int hlua_http_req_get_headers(lua_State *L)
5631{
5632 struct hlua_txn *htxn;
5633
5634 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5635 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5636
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005637 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005638 WILL_LJMP(lua_error(L));
5639
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005640 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005641}
5642
5643__LJMP static int hlua_http_res_get_headers(lua_State *L)
5644{
5645 struct hlua_txn *htxn;
5646
5647 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5648 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5649
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005650 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005651 WILL_LJMP(lua_error(L));
5652
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005653 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005654}
5655
5656/* This function replace full header, or just a value in
5657 * the request or in the response. It is a wrapper fir the
5658 * 4 following functions.
5659 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005660__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005661{
5662 size_t name_len;
5663 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5664 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5665 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005666 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005667 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005668
Dragan Dosen26743032019-04-30 15:54:36 +02005669 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005670 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5671
Christopher Fauleta2097962019-07-15 16:25:33 +02005672 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005673 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005674 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005675 return 0;
5676}
5677
5678__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5679{
5680 struct hlua_txn *htxn;
5681
5682 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5683 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5684
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005685 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005686 WILL_LJMP(lua_error(L));
5687
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005688 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005689}
5690
5691__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5692{
5693 struct hlua_txn *htxn;
5694
5695 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5696 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5697
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005698 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005699 WILL_LJMP(lua_error(L));
5700
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005701 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005702}
5703
5704__LJMP static int hlua_http_req_rep_val(lua_State *L)
5705{
5706 struct hlua_txn *htxn;
5707
5708 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5709 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5710
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005711 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005712 WILL_LJMP(lua_error(L));
5713
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005714 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005715}
5716
5717__LJMP static int hlua_http_res_rep_val(lua_State *L)
5718{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005719 struct hlua_txn *htxn;
5720
5721 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5722 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5723
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005724 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005725 WILL_LJMP(lua_error(L));
5726
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005727 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005728}
5729
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005730/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005731 * It is a wrapper for the 2 following functions.
5732 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005733__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005734{
5735 size_t len;
5736 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005737 struct htx *htx = htxbuf(&msg->chn->buf);
5738 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005739
Christopher Fauleta2097962019-07-15 16:25:33 +02005740 ctx.blk = NULL;
5741 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5742 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005743 return 0;
5744}
5745
5746__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5747{
5748 struct hlua_txn *htxn;
5749
5750 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5751 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5752
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005753 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005754 WILL_LJMP(lua_error(L));
5755
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005756 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005757}
5758
5759__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5760{
5761 struct hlua_txn *htxn;
5762
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005763 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005764 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5765
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005766 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005767 WILL_LJMP(lua_error(L));
5768
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005769 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005770}
5771
5772/* This function adds an header. It is a wrapper used by
5773 * the 2 following functions.
5774 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005775__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005776{
5777 size_t name_len;
5778 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5779 size_t value_len;
5780 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005781 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005782
Christopher Fauleta2097962019-07-15 16:25:33 +02005783 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5784 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005785 return 0;
5786}
5787
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005788__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5789{
5790 struct hlua_txn *htxn;
5791
5792 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5793 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5794
5795 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5796 WILL_LJMP(lua_error(L));
5797
5798 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5799}
5800
5801__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5802{
5803 struct hlua_txn *htxn;
5804
5805 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5806 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5807
5808 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5809 WILL_LJMP(lua_error(L));
5810
5811 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5812}
5813
5814static int hlua_http_req_set_hdr(lua_State *L)
5815{
5816 struct hlua_txn *htxn;
5817
5818 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5819 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5820
5821 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5822 WILL_LJMP(lua_error(L));
5823
5824 hlua_http_del_hdr(L, &htxn->s->txn->req);
5825 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5826}
5827
5828static int hlua_http_res_set_hdr(lua_State *L)
5829{
5830 struct hlua_txn *htxn;
5831
5832 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5833 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5834
5835 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5836 WILL_LJMP(lua_error(L));
5837
5838 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5839 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5840}
5841
5842/* This function set the method. */
5843static int hlua_http_req_set_meth(lua_State *L)
5844{
5845 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5846 size_t name_len;
5847 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5848
5849 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5850 WILL_LJMP(lua_error(L));
5851
5852 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5853 return 1;
5854}
5855
5856/* This function set the method. */
5857static int hlua_http_req_set_path(lua_State *L)
5858{
5859 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5860 size_t name_len;
5861 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5862
5863 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5864 WILL_LJMP(lua_error(L));
5865
5866 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5867 return 1;
5868}
5869
5870/* This function set the query-string. */
5871static int hlua_http_req_set_query(lua_State *L)
5872{
5873 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5874 size_t name_len;
5875 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5876
5877 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5878 WILL_LJMP(lua_error(L));
5879
5880 /* Check length. */
5881 if (name_len > trash.size - 1) {
5882 lua_pushboolean(L, 0);
5883 return 1;
5884 }
5885
5886 /* Add the mark question as prefix. */
5887 chunk_reset(&trash);
5888 trash.area[trash.data++] = '?';
5889 memcpy(trash.area + trash.data, name, name_len);
5890 trash.data += name_len;
5891
5892 lua_pushboolean(L,
5893 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5894 return 1;
5895}
5896
5897/* This function set the uri. */
5898static int hlua_http_req_set_uri(lua_State *L)
5899{
5900 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5901 size_t name_len;
5902 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5903
5904 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5905 WILL_LJMP(lua_error(L));
5906
5907 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5908 return 1;
5909}
5910
5911/* This function set the response code & optionally reason. */
5912static int hlua_http_res_set_status(lua_State *L)
5913{
5914 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5915 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5916 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5917 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5918
5919 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5920 WILL_LJMP(lua_error(L));
5921
5922 http_res_set_status(code, reason, htxn->s);
5923 return 0;
5924}
5925
5926/*
5927 *
5928 *
5929 * Class HTTPMessage
5930 *
5931 *
5932 */
5933
5934/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5935 * otherwise it throws an error.
5936 */
5937__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5938{
5939 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5940}
5941
5942/* Creates and pushes on the stack a HTTP object according with a current TXN.
5943 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005944static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005945{
5946 /* Check stack size. */
5947 if (!lua_checkstack(L, 3))
5948 return 0;
5949
5950 lua_newtable(L);
5951 lua_pushlightuserdata(L, msg);
5952 lua_rawseti(L, -2, 0);
5953
5954 /* Create the "channel" field that contains the request channel object. */
5955 lua_pushstring(L, "channel");
5956 if (!hlua_channel_new(L, msg->chn))
5957 return 0;
5958 lua_rawset(L, -3);
5959
5960 /* Pop a class stream metatable and affect it to the table. */
5961 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5962 lua_setmetatable(L, -2);
5963
5964 return 1;
5965}
5966
5967/* Helper function returning a filter attached to the HTTP message at the
5968 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05005969 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005970 * filled with output and input length respectively.
5971 */
5972static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5973{
5974 struct channel *chn = msg->chn;
5975 struct htx *htx = htxbuf(&chn->buf);
5976 struct filter *filter = NULL;
5977
5978 *offset = co_data(msg->chn);
5979 *len = htx->data - co_data(msg->chn);
5980
5981 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5982 filter = lua_touserdata (L, -1);
5983 if (msg->msg_state >= HTTP_MSG_DATA) {
5984 struct hlua_flt_ctx *flt_ctx = filter->ctx;
5985
5986 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
5987 *len = flt_ctx->cur_len[CHN_IDX(chn)];
5988 }
5989 }
5990
5991 lua_pop(L, 1);
5992 return filter;
5993}
5994
5995/* Returns true if the channel attached to the HTTP message is the response
5996 * channel.
5997 */
5998__LJMP static int hlua_http_msg_is_resp(lua_State *L)
5999{
6000 struct http_msg *msg;
6001
6002 MAY_LJMP(check_args(L, 1, "is_resp"));
6003 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6004
6005 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6006 return 1;
6007}
6008
6009/* Returns an array containing the elements status-line of the HTTP message. It relies
6010 * on hlua_http_get_stline().
6011 */
6012__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6013{
6014 struct http_msg *msg;
6015 struct htx *htx;
6016 struct htx_sl *sl;
6017
6018 MAY_LJMP(check_args(L, 1, "get_stline"));
6019 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6020
6021 if (msg->msg_state > HTTP_MSG_BODY)
6022 WILL_LJMP(lua_error(L));
6023
6024 htx = htxbuf(&msg->chn->buf);
6025 sl = http_get_stline(htx);
6026 if (!sl)
6027 return 0;
6028 return hlua_http_get_stline(L, sl);
6029}
6030
6031/* Returns an array containing all headers of the HTTP message. it relies on
6032 * hlua_http_get_headers().
6033 */
6034__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6035{
6036 struct http_msg *msg;
6037
6038 MAY_LJMP(check_args(L, 1, "get_headers"));
6039 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6040
6041 if (msg->msg_state > HTTP_MSG_BODY)
6042 WILL_LJMP(lua_error(L));
6043
6044 return hlua_http_get_headers(L, msg);
6045}
6046
6047/* Deletes all occurrences of an header in the HTTP message matching on its
6048 * name. It relies on hlua_http_del_hdr().
6049 */
6050__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6051{
6052 struct http_msg *msg;
6053
6054 MAY_LJMP(check_args(L, 2, "del_header"));
6055 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6056
6057 if (msg->msg_state > HTTP_MSG_BODY)
6058 WILL_LJMP(lua_error(L));
6059
6060 return hlua_http_del_hdr(L, msg);
6061}
6062
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006063/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006064 * message given its name against a regex and replaces it if it matches. It
6065 * relies on hlua_http_rep_hdr().
6066 */
6067__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6068{
6069 struct http_msg *msg;
6070
6071 MAY_LJMP(check_args(L, 4, "rep_header"));
6072 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6073
6074 if (msg->msg_state > HTTP_MSG_BODY)
6075 WILL_LJMP(lua_error(L));
6076
6077 return hlua_http_rep_hdr(L, msg, 1);
6078}
6079
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006080/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006081 * message given its name against a regex and replaces it if it matches. It
6082 * relies on hlua_http_rep_hdr().
6083 */
6084__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6085{
6086 struct http_msg *msg;
6087
6088 MAY_LJMP(check_args(L, 4, "rep_value"));
6089 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6090
6091 if (msg->msg_state > HTTP_MSG_BODY)
6092 WILL_LJMP(lua_error(L));
6093
6094 return hlua_http_rep_hdr(L, msg, 0);
6095}
6096
6097/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6098__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6099{
6100 struct http_msg *msg;
6101
6102 MAY_LJMP(check_args(L, 3, "add_header"));
6103 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6104
6105 if (msg->msg_state > HTTP_MSG_BODY)
6106 WILL_LJMP(lua_error(L));
6107
6108 return hlua_http_add_hdr(L, msg);
6109}
6110
6111/* Add an header in the HTTP message removing existing headers with the same
6112 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6113 */
6114__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6115{
6116 struct http_msg *msg;
6117
6118 MAY_LJMP(check_args(L, 3, "set_header"));
6119 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6120
6121 if (msg->msg_state > HTTP_MSG_BODY)
6122 WILL_LJMP(lua_error(L));
6123
6124 hlua_http_del_hdr(L, msg);
6125 return hlua_http_add_hdr(L, msg);
6126}
6127
6128/* Rewrites the request method. It relies on http_req_replace_stline(). */
6129__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6130{
6131 struct stream *s;
6132 struct http_msg *msg;
6133 const char *name;
6134 size_t name_len;
6135
6136 MAY_LJMP(check_args(L, 2, "set_method"));
6137 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6138 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6139
6140 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6141 WILL_LJMP(lua_error(L));
6142
6143 s = chn_strm(msg->chn);
6144 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6145 return 1;
6146}
6147
6148/* Rewrites the request path. It relies on http_req_replace_stline(). */
6149__LJMP static int hlua_http_msg_set_path(lua_State *L)
6150{
6151 struct stream *s;
6152 struct http_msg *msg;
6153 const char *name;
6154 size_t name_len;
6155
6156 MAY_LJMP(check_args(L, 2, "set_path"));
6157 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6158 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6159
6160 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6161 WILL_LJMP(lua_error(L));
6162
6163 s = chn_strm(msg->chn);
6164 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6165 return 1;
6166}
6167
6168/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6169__LJMP static int hlua_http_msg_set_query(lua_State *L)
6170{
6171 struct stream *s;
6172 struct http_msg *msg;
6173 const char *name;
6174 size_t name_len;
6175
6176 MAY_LJMP(check_args(L, 2, "set_query"));
6177 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6178 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6179
6180 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6181 WILL_LJMP(lua_error(L));
6182
6183 /* Check length. */
6184 if (name_len > trash.size - 1) {
6185 lua_pushboolean(L, 0);
6186 return 1;
6187 }
6188
6189 /* Add the mark question as prefix. */
6190 chunk_reset(&trash);
6191 trash.area[trash.data++] = '?';
6192 memcpy(trash.area + trash.data, name, name_len);
6193 trash.data += name_len;
6194
6195 s = chn_strm(msg->chn);
6196 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6197 return 1;
6198}
6199
6200/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6201__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6202{
6203 struct stream *s;
6204 struct http_msg *msg;
6205 const char *name;
6206 size_t name_len;
6207
6208 MAY_LJMP(check_args(L, 2, "set_uri"));
6209 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6210 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6211
6212 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6213 WILL_LJMP(lua_error(L));
6214
6215 s = chn_strm(msg->chn);
6216 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6217 return 1;
6218}
6219
6220/* Rewrites the response status code. It relies on http_res_set_status(). */
6221__LJMP static int hlua_http_msg_set_status(lua_State *L)
6222{
6223 struct http_msg *msg;
6224 unsigned int code;
6225 const char *reason;
6226 size_t reason_len;
6227
6228 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6229 code = MAY_LJMP(luaL_checkinteger(L, 2));
6230 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6231
6232 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6233 WILL_LJMP(lua_error(L));
6234
6235 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6236 return 1;
6237}
6238
6239/* Returns true if the HTTP message is full. */
6240__LJMP static int hlua_http_msg_is_full(lua_State *L)
6241{
6242 struct http_msg *msg;
6243
6244 MAY_LJMP(check_args(L, 1, "is_full"));
6245 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6246 lua_pushboolean(L, channel_full(msg->chn, 0));
6247 return 1;
6248}
6249
6250/* Returns true if the HTTP message may still receive data. */
6251__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6252{
6253 struct http_msg *msg;
6254 struct htx *htx;
6255
6256 MAY_LJMP(check_args(L, 1, "may_recv"));
6257 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6258 htx = htxbuf(&msg->chn->buf);
6259 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6260 return 1;
6261}
6262
6263/* Returns true if the HTTP message EOM was received */
6264__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6265{
6266 struct http_msg *msg;
6267 struct htx *htx;
6268
6269 MAY_LJMP(check_args(L, 1, "may_recv"));
6270 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6271 htx = htxbuf(&msg->chn->buf);
6272 lua_pushboolean(L, !htx_expect_more(htx));
6273 return 1;
6274}
6275
6276/* Returns the number of bytes available in the input side of the HTTP
6277 * message. This function never fails.
6278 */
6279__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6280{
6281 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006282 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006283
6284 MAY_LJMP(check_args(L, 1, "input"));
6285 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006286 hlua_http_msg_filter(L, 1, msg, &output, &input);
6287 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006288 return 1;
6289}
6290
6291/* Returns the number of bytes available in the output side of the HTTP
6292 * message. This function never fails.
6293 */
6294__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6295{
6296 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006297 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006298
6299 MAY_LJMP(check_args(L, 1, "output"));
6300 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006301 hlua_http_msg_filter(L, 1, msg, &output, &input);
6302 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006303 return 1;
6304}
6305
6306/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6307 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006308 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006309 * block. This function is called during the payload filtering, so the headers
6310 * are already scheduled for output (from the filter point of view).
6311 */
6312static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6313{
6314 struct htx *htx = htxbuf(&msg->chn->buf);
6315 struct htx_blk *blk;
6316 struct htx_ret htxret;
6317 luaL_Buffer b;
6318 int ret = 0;
6319
6320 luaL_buffinit(L, &b);
6321 htxret = htx_find_offset(htx, offset);
6322 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6323 enum htx_blk_type type = htx_get_blk_type(blk);
6324 struct ist v;
6325
6326 switch (type) {
6327 case HTX_BLK_UNUSED:
6328 break;
6329
6330 case HTX_BLK_DATA:
6331 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006332 v = istadv(v, offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006333 if (v.len > len)
6334 v.len = len;
6335
6336 luaL_addlstring(&b, v.ptr, v.len);
6337 ret += v.len;
6338 break;
6339
6340 default:
vishnu0af4bd72021-10-24 06:46:24 +05306341 if (!ret)
6342 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006343 goto end;
6344 }
6345 offset = 0;
6346 }
6347
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006348end:
vishnu0af4bd72021-10-24 06:46:24 +05306349 if (!ret && (htx->flags & HTX_FL_EOM))
6350 goto no_data;
6351 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006352 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306353
6354 no_data:
6355 /* Remove the empty string and push nil on the stack */
6356 lua_pop(L, 1);
6357 lua_pushnil(L);
6358 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006359}
6360
6361/* Copies the string <str> to the HTTP message <msg> at the offset
6362 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006363 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006364 * the filter context.
6365 */
6366static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6367{
6368 struct htx *htx = htx_from_buf(&msg->chn->buf);
6369 struct htx_ret htxret;
6370 int /*max, */ret = 0;
6371
6372 /* Nothing to do, just return */
6373 if (unlikely(istlen(str) == 0))
6374 goto end;
6375
6376 if (istlen(str) > htx_free_data_space(htx)) {
6377 ret = -1;
6378 goto end;
6379 }
6380
6381 htxret = htx_find_offset(htx, offset);
6382 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6383 if (!htx_add_last_data(htx, str))
6384 goto end;
6385 }
6386 else {
6387 struct ist v = htx_get_blk_value(htx, htxret.blk);
6388 v.ptr += htxret.ret;
6389 v.len = 0;
6390 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6391 goto end;
6392 }
6393 ret = str.len;
6394 if (ret) {
6395 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6396 flt_update_offsets(filter, msg->chn, ret);
6397 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6398 }
6399
6400 end:
6401 htx_to_buf(htx, &msg->chn->buf);
6402 return ret;
6403}
6404
6405/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6406 * position <offset>. It stops on the first non-DATA HTX block. This function is
6407 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006408 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006409 * update the filter context.
6410 */
6411static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6412{
6413 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6414 struct htx *htx = htx_from_buf(&msg->chn->buf);
6415 struct htx_blk *blk;
6416 struct htx_ret htxret;
6417 size_t ret = 0;
6418
6419 /* Be sure <len> is always the amount of DATA to remove */
6420 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6421 htx_truncate(htx, offset);
6422 ret = len;
6423 goto end;
6424 }
6425
6426 htxret = htx_find_offset(htx, offset);
6427 blk = htxret.blk;
6428 if (htxret.ret) {
6429 struct ist v;
6430
6431 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6432 goto end;
6433 v = htx_get_blk_value(htx, blk);
6434 v.ptr += htxret.ret;
6435 if (v.len > len)
6436 v.len = len;
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006437 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006438 len -= v.len;
6439 ret += v.len;
6440 }
6441
6442
6443 while (blk && len) {
6444 enum htx_blk_type type = htx_get_blk_type(blk);
6445 uint32_t sz = htx_get_blksz(blk);
6446
6447 switch (type) {
6448 case HTX_BLK_UNUSED:
6449 break;
6450
6451 case HTX_BLK_DATA:
6452 if (len < sz) {
6453 htx_cut_data_blk(htx, blk, len);
6454 ret += len;
6455 goto end;
6456 }
6457 break;
6458
6459 default:
6460 goto end;
6461 }
6462
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006463 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006464 len -= sz;
6465 ret += sz;
6466 blk = htx_remove_blk(htx, blk);
6467 }
6468
6469end:
6470 flt_update_offsets(filter, msg->chn, -ret);
6471 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6472 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6473 * to loose the EOM flag if the message is empty.
6474 */
6475}
6476
6477/* Copies input data found in an HTTP message. Unlike the channel function used
6478 * to duplicate raw data, this one can only be called inside a filter, from
6479 * http_payload callback. So it cannot yield. An exception is returned if it is
6480 * called from another callback. If nothing was copied, a nil value is pushed on
6481 * the stack.
6482 */
6483__LJMP static int hlua_http_msg_get_body(lua_State *L)
6484{
6485 struct http_msg *msg;
6486 struct filter *filter;
6487 size_t output, input;
6488 int offset, len;
6489
6490 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6491 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6492 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6493
6494 if (msg->msg_state < HTTP_MSG_DATA)
6495 WILL_LJMP(lua_error(L));
6496
6497 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6498 if (!filter || !hlua_filter_from_payload(filter))
6499 WILL_LJMP(lua_error(L));
6500
6501 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6502 lua_pushnil(L);
6503 return 1;
6504 }
6505
6506 offset = output;
6507 if (lua_gettop(L) > 1) {
6508 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6509 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006510 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006511 offset += output;
6512 if (offset < output || offset > input + output) {
6513 lua_pushfstring(L, "offset out of range.");
6514 WILL_LJMP(lua_error(L));
6515 }
6516 }
6517 len = output + input - offset;
6518 if (lua_gettop(L) == 3) {
6519 len = MAY_LJMP(luaL_checkinteger(L, 3));
6520 if (!len)
6521 goto dup;
6522 if (len == -1)
6523 len = global.tune.bufsize;
6524 if (len < 0) {
6525 lua_pushfstring(L, "length out of range.");
6526 WILL_LJMP(lua_error(L));
6527 }
6528 }
6529
6530 dup:
6531 _hlua_http_msg_dup(msg, L, offset, len);
6532 return 1;
6533}
6534
6535/* Appends a string to the HTTP message, after all existing DATA blocks but
6536 * before the trailers, if any. It returns the amount of data written or -1 if
6537 * nothing was copied. Unlike the channel function used to append data, this one
6538 * can only be called inside a filter, from http_payload callback. So it cannot
6539 * yield. An exception is returned if it is called from another callback.
6540 */
6541__LJMP static int hlua_http_msg_append(lua_State *L)
6542{
6543 struct http_msg *msg;
6544 struct filter *filter;
6545 const char *str;
6546 size_t offset, len, sz;
6547 int ret;
6548
6549 MAY_LJMP(check_args(L, 2, "append"));
6550 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6551
6552 if (msg->msg_state < HTTP_MSG_DATA)
6553 WILL_LJMP(lua_error(L));
6554
6555 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6556 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6557 if (!filter || !hlua_filter_from_payload(filter))
6558 WILL_LJMP(lua_error(L));
6559
6560 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6561 lua_pushinteger(L, ret);
6562 return 1;
6563}
6564
6565/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6566 * returns the amount of data written or -1 if nothing was copied. Unlike the
6567 * channel function used to prepend data, this one can only be called inside a
6568 * filter, from http_payload callback. So it cannot yield. An exception is
6569 * returned if it is called from another callback.
6570 */
6571__LJMP static int hlua_http_msg_prepend(lua_State *L)
6572{
6573 struct http_msg *msg;
6574 struct filter *filter;
6575 const char *str;
6576 size_t offset, len, sz;
6577 int ret;
6578
6579 MAY_LJMP(check_args(L, 2, "prepend"));
6580 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006581
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006582 if (msg->msg_state < HTTP_MSG_DATA)
6583 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006584
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006585 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6586 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6587 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006588 WILL_LJMP(lua_error(L));
6589
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006590 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6591 lua_pushinteger(L, ret);
6592 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006593}
6594
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006595/* Inserts a string to the HTTP message at a given offset. By default the string
6596 * is appended at the end of DATA blocks. It returns the amount of data written
6597 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6598 * this one can only be called inside a filter, from http_payload callback. So
6599 * it cannot yield. An exception is returned if it is called from another
6600 * callback.
6601 */
6602__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006603{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006604 struct http_msg *msg;
6605 struct filter *filter;
6606 const char *str;
6607 size_t input, output, sz;
6608 int offset;
6609 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006610
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006611 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6612 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6613 MAY_LJMP(check_args(L, 2, "insert"));
6614 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006615
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006616 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006617 WILL_LJMP(lua_error(L));
6618
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006619 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6620 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6621 if (!filter || !hlua_filter_from_payload(filter))
6622 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006623
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006624 offset = input + output;
6625 if (lua_gettop(L) > 2) {
6626 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6627 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006628 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006629 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006630 if (offset < output || offset > output + input) {
6631 lua_pushfstring(L, "offset out of range.");
6632 WILL_LJMP(lua_error(L));
6633 }
6634 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006635
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006636 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6637 lua_pushinteger(L, ret);
6638 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006639}
6640
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006641/* Removes a given amount of data from the HTTP message at a given offset. By
6642 * default all DATA blocks are removed. It returns the amount of data
6643 * removed. Unlike the channel function used to remove data, this one can only
6644 * be called inside a filter, from http_payload callback. So it cannot yield. An
6645 * exception is returned if it is called from another callback.
6646 */
6647__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006648{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006649 struct http_msg *msg;
6650 struct filter *filter;
6651 size_t input, output;
6652 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006653
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006654 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6655 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6656 MAY_LJMP(check_args(L, 2, "insert"));
6657 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006658
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006659 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006660 WILL_LJMP(lua_error(L));
6661
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006662 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6663 if (!filter || !hlua_filter_from_payload(filter))
6664 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006665
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006666 offset = input + output;
6667 if (lua_gettop(L) > 2) {
6668 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6669 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006670 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006671 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006672 if (offset < output || offset > output + input) {
6673 lua_pushfstring(L, "offset out of range.");
6674 WILL_LJMP(lua_error(L));
6675 }
6676 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006677
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006678 len = output + input - offset;
6679 if (lua_gettop(L) == 4) {
6680 len = MAY_LJMP(luaL_checkinteger(L, 4));
6681 if (!len)
6682 goto end;
6683 if (len == -1)
6684 len = output + input - offset;
6685 if (len < 0 || offset + len > output + input) {
6686 lua_pushfstring(L, "length out of range.");
6687 WILL_LJMP(lua_error(L));
6688 }
6689 }
6690
6691 _hlua_http_msg_delete(msg, filter, offset, len);
6692
6693 end:
6694 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006695 return 1;
6696}
6697
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006698/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006699 * all remaining data are removed, accordingly to the filter context. It returns
6700 * the amount of data written or -1 if nothing was copied. Unlike the channel
6701 * function used to replace data, this one can only be called inside a filter,
6702 * from http_payload callback. So it cannot yield. An exception is returned if
6703 * it is called from another callback.
6704 */
6705__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006706{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006707 struct http_msg *msg;
6708 struct filter *filter;
6709 struct htx *htx;
6710 const char *str;
6711 size_t input, output, sz;
6712 int offset, len;
6713 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006714
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006715 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6716 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6717 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6718
6719 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006720 WILL_LJMP(lua_error(L));
6721
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006722 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6723 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6724 if (!filter || !hlua_filter_from_payload(filter))
6725 WILL_LJMP(lua_error(L));
6726
6727 offset = output;
6728 if (lua_gettop(L) > 2) {
6729 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6730 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006731 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006732 offset += output;
6733 if (offset < output || offset > input + output) {
6734 lua_pushfstring(L, "offset out of range.");
6735 WILL_LJMP(lua_error(L));
6736 }
6737 }
6738
6739 len = output + input - offset;
6740 if (lua_gettop(L) == 4) {
6741 len = MAY_LJMP(luaL_checkinteger(L, 4));
6742 if (!len)
6743 goto set;
6744 if (len == -1)
6745 len = output + input - offset;
6746 if (len < 0 || offset + len > output + input) {
6747 lua_pushfstring(L, "length out of range.");
6748 WILL_LJMP(lua_error(L));
6749 }
6750 }
6751
6752 set:
6753 /* Be sure we can copied the string once input data will be removed. */
6754 htx = htx_from_buf(&msg->chn->buf);
6755 if (sz > htx_free_data_space(htx) + len)
6756 lua_pushinteger(L, -1);
6757 else {
6758 _hlua_http_msg_delete(msg, filter, offset, len);
6759 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6760 lua_pushinteger(L, ret);
6761 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006762 return 1;
6763}
6764
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006765/* Prepends data into an HTTP message and forward it, from the filter point of
6766 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6767 * the channel function used to send data, this one can only be called inside a
6768 * filter, from http_payload callback. So it cannot yield. An exception is
6769 * returned if it is called from another callback.
6770 */
6771__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006772{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006773 struct http_msg *msg;
6774 struct filter *filter;
6775 struct htx *htx;
6776 const char *str;
6777 size_t offset, len, sz;
6778 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006779
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006780 MAY_LJMP(check_args(L, 2, "send"));
6781 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6782
6783 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006784 WILL_LJMP(lua_error(L));
6785
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006786 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6787 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6788 if (!filter || !hlua_filter_from_payload(filter))
6789 WILL_LJMP(lua_error(L));
6790
6791 /* Return an error if the channel's output is closed */
6792 if (unlikely(channel_output_closed(msg->chn))) {
6793 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006794 return 1;
6795 }
6796
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006797 htx = htx_from_buf(&msg->chn->buf);
6798 if (sz > htx_free_data_space(htx)) {
6799 lua_pushinteger(L, -1);
6800 return 1;
6801 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006802
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006803 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6804 if (ret > 0) {
6805 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6806
6807 FLT_OFF(filter, msg->chn) += ret;
6808 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6809 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6810 }
6811
6812 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006813 return 1;
6814}
6815
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006816/* Forwards a given amount of bytes. It return -1 if the channel's output is
6817 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6818 * channel function used to forward data, this one can only be called inside a
6819 * filter, from http_payload callback. So it cannot yield. An exception is
6820 * returned if it is called from another callback. All other functions deal with
6821 * DATA block, this one not.
6822*/
6823__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006824{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006825 struct http_msg *msg;
6826 struct filter *filter;
6827 size_t offset, len;
6828 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006829
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006830 MAY_LJMP(check_args(L, 2, "forward"));
6831 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6832
6833 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006834 WILL_LJMP(lua_error(L));
6835
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006836 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6837 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6838 if (!filter || !hlua_filter_from_payload(filter))
6839 WILL_LJMP(lua_error(L));
6840
6841 /* Nothing to do, just return */
6842 if (!fwd)
6843 goto end;
6844
6845 /* Return an error if the channel's output is closed */
6846 if (unlikely(channel_output_closed(msg->chn))) {
6847 ret = -1;
6848 goto end;
6849 }
6850
6851 ret = fwd;
6852 if (ret > len)
6853 ret = len;
6854
6855 if (ret) {
6856 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6857
6858 FLT_OFF(filter, msg->chn) += ret;
6859 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6860 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6861 }
6862
6863 end:
6864 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006865 return 1;
6866}
6867
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006868/* Set EOM flag on the HTX message.
6869 *
6870 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6871 * really know how to do without this feature.
6872 */
6873__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006874{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006875 struct http_msg *msg;
6876 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006877
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006878 MAY_LJMP(check_args(L, 1, "set_eom"));
6879 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6880 htx = htxbuf(&msg->chn->buf);
6881 htx->flags |= HTX_FL_EOM;
6882 return 0;
6883}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006884
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006885/* Unset EOM flag on the HTX message.
6886 *
6887 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6888 * really know how to do without this feature.
6889 */
6890__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6891{
6892 struct http_msg *msg;
6893 struct htx *htx;
6894
6895 MAY_LJMP(check_args(L, 1, "set_eom"));
6896 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6897 htx = htxbuf(&msg->chn->buf);
6898 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006899 return 0;
6900}
6901
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006902/*
6903 *
6904 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006905 * Class HTTPClient
6906 *
6907 *
6908 */
6909__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6910{
6911 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6912}
6913
William Lallemandf77f1de2021-09-28 19:10:38 +02006914
6915/* stops the httpclient and ask it to kill itself */
6916__LJMP static int hlua_httpclient_gc(lua_State *L)
6917{
6918 struct hlua_httpclient *hlua_hc;
6919
6920 MAY_LJMP(check_args(L, 1, "__gc"));
6921
6922 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6923
6924 httpclient_stop_and_destroy(hlua_hc->hc);
6925
6926 hlua_hc->hc = NULL;
6927
6928
6929 return 0;
6930}
6931
6932
William Lallemand3956c4e2021-09-21 16:25:15 +02006933__LJMP static int hlua_httpclient_new(lua_State *L)
6934{
6935 struct hlua_httpclient *hlua_hc;
6936 struct hlua *hlua;
6937
6938 /* Get hlua struct, or NULL if we execute from main lua state */
6939 hlua = hlua_gethlua(L);
6940 if (!hlua)
6941 return 0;
6942
6943 /* Check stack size. */
6944 if (!lua_checkstack(L, 3)) {
6945 hlua_pusherror(L, "httpclient: full stack");
6946 goto err;
6947 }
6948 /* Create the object: obj[0] = userdata. */
6949 lua_newtable(L);
6950 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6951 lua_rawseti(L, -2, 0);
6952 memset(hlua_hc, 0, sizeof(*hlua_hc));
6953
6954 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6955 if (!hlua_hc->hc)
6956 goto err;
6957
6958 /* Pop a class stream metatable and affect it to the userdata. */
6959 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6960 lua_setmetatable(L, -2);
6961
6962 return 1;
6963
6964 err:
6965 WILL_LJMP(lua_error(L));
6966 return 0;
6967}
6968
6969
6970/*
6971 * Callback of the httpclient, this callback wakes the lua task up, once the
6972 * httpclient receives some data
6973 *
6974 */
6975
6976static void hlua_httpclient_res_cb(struct httpclient *hc)
6977{
6978 struct hlua *hlua = hc->caller;
6979
6980 if (!hlua || !hlua->task)
6981 return;
6982
6983 task_wakeup(hlua->task, TASK_WOKEN_MSG);
6984}
6985
6986/*
William Lallemandd7df73a2021-09-23 17:54:00 +02006987 * Fill the lua stack with headers from the httpclient response
6988 * This works the same way as the hlua_http_get_headers() function
6989 */
6990__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
6991{
6992 struct http_hdr *hdr;
6993
6994 lua_newtable(L);
6995
William Lallemandef574b22021-10-05 16:19:31 +02006996 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02006997 struct ist n, v;
6998 int len;
6999
7000 n = hdr->n;
7001 v = hdr->v;
7002
7003 /* Check for existing entry:
7004 * assume that the table is on the top of the stack, and
7005 * push the key in the stack, the function lua_gettable()
7006 * perform the lookup.
7007 */
7008
7009 lua_pushlstring(L, n.ptr, n.len);
7010 lua_gettable(L, -2);
7011
7012 switch (lua_type(L, -1)) {
7013 case LUA_TNIL:
7014 /* Table not found, create it. */
7015 lua_pop(L, 1); /* remove the nil value. */
7016 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7017 lua_newtable(L); /* create and push empty table. */
7018 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7019 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7020 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7021 break;
7022
7023 case LUA_TTABLE:
7024 /* Entry found: push the value in the table. */
7025 len = lua_rawlen(L, -1);
7026 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7027 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7028 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7029 break;
7030
7031 default:
7032 /* Other cases are errors. */
7033 hlua_pusherror(L, "internal error during the parsing of headers.");
7034 WILL_LJMP(lua_error(L));
7035 }
7036 }
7037 return 1;
7038}
7039
7040/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007041 * For each yield, checks if there is some data in the httpclient and push them
7042 * in the lua buffer, once the httpclient finished its job, push the result on
7043 * the stack
7044 */
William Lallemanddc2cc902021-10-26 11:43:26 +02007045__LJMP static int hlua_httpclient_send_yield(lua_State *L, int status, lua_KContext ctx)
William Lallemand3956c4e2021-09-21 16:25:15 +02007046{
7047 struct buffer *tr;
7048 int res;
7049 struct hlua *hlua = hlua_gethlua(L);
7050 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7051
7052
7053 tr = get_trash_chunk();
7054
7055 res = httpclient_res_xfer(hlua_hc->hc, tr);
7056 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7057
7058 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7059
7060 luaL_pushresult(&hlua_hc->b);
7061 lua_settable(L, -3);
7062
7063 lua_pushstring(L, "status");
7064 lua_pushinteger(L, hlua_hc->hc->res.status);
7065 lua_settable(L, -3);
7066
7067
7068 lua_pushstring(L, "reason");
7069 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7070 lua_settable(L, -3);
7071
William Lallemandd7df73a2021-09-23 17:54:00 +02007072 lua_pushstring(L, "headers");
7073 hlua_httpclient_get_headers(L, hlua_hc);
7074 lua_settable(L, -3);
7075
William Lallemand3956c4e2021-09-21 16:25:15 +02007076 return 1;
7077 }
7078
7079 if (httpclient_data(hlua_hc->hc))
7080 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7081
7082
William Lallemanddc2cc902021-10-26 11:43:26 +02007083 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_send_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007084 return 0;
7085}
7086
William Lallemand746e6f32021-10-06 10:57:44 +02007087
7088/*
7089 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7090 *
7091 * Caller must free the result
7092 */
7093struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7094{
7095 struct http_hdr hdrs[global.tune.max_http_hdr];
7096 struct http_hdr *result = NULL;
7097 uint32_t hdr_num = 0;
7098
7099 lua_pushnil(L);
7100 while (lua_next(L, -2) != 0) {
7101 struct ist name, value;
7102 const char *n, *v;
7103 size_t nlen, vlen;
7104
7105 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7106 /* Skip element if the key is not a string or if the value is not a table */
7107 goto next_hdr;
7108 }
7109
7110 n = lua_tolstring(L, -2, &nlen);
7111 name = ist2(n, nlen);
7112
7113 /* Loop on header's values */
7114 lua_pushnil(L);
7115 while (lua_next(L, -2)) {
7116 if (!lua_isstring(L, -1)) {
7117 /* Skip the value if it is not a string */
7118 goto next_value;
7119 }
7120
7121 v = lua_tolstring(L, -1, &vlen);
7122 value = ist2(v, vlen);
7123 name = ist2(n, nlen);
7124
7125 hdrs[hdr_num].n = istdup(name);
7126 hdrs[hdr_num].v = istdup(value);
7127
7128 hdr_num++;
7129
7130 next_value:
7131 lua_pop(L, 1);
7132 }
7133
7134 next_hdr:
7135 lua_pop(L, 1);
7136
7137 }
7138
7139 if (hdr_num) {
7140 /* alloc and copy the headers in the httpclient struct */
7141 result = calloc((hdr_num + 1), sizeof(*hdrs));
7142 if (!result)
7143 goto skip_headers;
7144 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7145
7146 result[hdr_num].n = IST_NULL;
7147 result[hdr_num].v = IST_NULL;
7148 }
7149
7150skip_headers:
7151 lua_pop(L, 1);
7152
7153 return result;
7154}
7155
7156
7157
William Lallemand3956c4e2021-09-21 16:25:15 +02007158/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007159 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007160 */
7161
William Lallemanddc2cc902021-10-26 11:43:26 +02007162__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007163{
7164 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007165 struct http_hdr *hdrs = NULL;
7166 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007167 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007168 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007169 const char *body_str = NULL;
William Lallemand746e6f32021-10-06 10:57:44 +02007170 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007171
7172 hlua = hlua_gethlua(L);
7173
7174 if (!hlua || !hlua->task)
7175 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7176 "'frontend', 'backend' or 'task'"));
7177
William Lallemand746e6f32021-10-06 10:57:44 +02007178 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7179 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7180
7181 ret = lua_getfield(L, -1, "url");
7182 if (ret == LUA_TSTRING) {
7183 url_str = lua_tostring(L, -1);
7184 }
7185 lua_pop(L, 1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007186
William Lallemand746e6f32021-10-06 10:57:44 +02007187 ret = lua_getfield(L, -1, "headers");
7188 if (ret == LUA_TTABLE) {
7189 hdrs = hlua_httpclient_table_to_hdrs(L);
7190 }
7191 lua_pop(L, 1);
William Lallemand79416cb2021-09-24 14:51:44 +02007192
William Lallemanddec25c32021-10-25 19:48:37 +02007193 ret = lua_getfield(L, -1, "body");
7194 if (ret == LUA_TSTRING) {
7195 body_str = lua_tostring(L, -1);
7196 }
7197 lua_pop(L, 1);
7198
William Lallemand746e6f32021-10-06 10:57:44 +02007199 if (!url_str) {
7200 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7201 return 0;
7202 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007203
7204 hlua_hc = hlua_checkhttpclient(L, 1);
7205
7206 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007207 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007208
7209 /* update the httpclient callbacks */
7210 hlua_hc->hc->ops.res_stline = hlua_httpclient_res_cb;
7211 hlua_hc->hc->ops.res_headers = hlua_httpclient_res_cb;
7212 hlua_hc->hc->ops.res_payload = hlua_httpclient_res_cb;
7213 hlua_hc->hc->ops.res_end = hlua_httpclient_res_cb;
7214
7215
William Lallemand6137a9e2021-10-26 15:01:53 +02007216 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, ist(body_str));
William Lallemand3956c4e2021-09-21 16:25:15 +02007217
William Lallemand746e6f32021-10-06 10:57:44 +02007218 /* free the temporary headers array */
7219 hdrs_i = hdrs;
7220 while (hdrs_i && isttest(hdrs_i->n)) {
7221 istfree(&hdrs_i->n);
7222 istfree(&hdrs_i->v);
7223 hdrs_i++;
7224 }
7225 ha_free(&hdrs);
7226
7227
William Lallemand6137a9e2021-10-26 15:01:53 +02007228 if (ret != ERR_NONE) {
7229 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7230 return 0;
7231 }
7232
William Lallemand746e6f32021-10-06 10:57:44 +02007233
William Lallemand6137a9e2021-10-26 15:01:53 +02007234 httpclient_start(hlua_hc->hc);
7235
William Lallemand3956c4e2021-09-21 16:25:15 +02007236 /* we return a "res" object */
7237 lua_newtable(L);
7238
7239 luaL_buffinit(L, &hlua_hc->b);
7240 lua_pushstring(L, "body");
7241
William Lallemanddc2cc902021-10-26 11:43:26 +02007242 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_send_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007243 return 0;
7244}
7245
7246/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007247 * Sends an HTTP HEAD request and wait for a response
7248 *
7249 * httpclient:head(url, headers, payload)
7250 */
7251__LJMP static int hlua_httpclient_head(lua_State *L)
7252{
7253 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7254}
7255
7256/*
7257 * Send an HTTP GET request and wait for a response
7258 *
7259 * httpclient:get(url, headers, payload)
7260 */
7261__LJMP static int hlua_httpclient_get(lua_State *L)
7262{
7263 return hlua_httpclient_send(L, HTTP_METH_GET);
7264
7265}
7266
7267/*
7268 * Sends an HTTP PUT request and wait for a response
7269 *
7270 * httpclient:put(url, headers, payload)
7271 */
7272__LJMP static int hlua_httpclient_put(lua_State *L)
7273{
7274 return hlua_httpclient_send(L, HTTP_METH_PUT);
7275}
7276
7277/*
7278 * Send an HTTP POST request and wait for a response
7279 *
7280 * httpclient:post(url, headers, payload)
7281 */
7282__LJMP static int hlua_httpclient_post(lua_State *L)
7283{
7284 return hlua_httpclient_send(L, HTTP_METH_POST);
7285}
7286
7287
7288/*
7289 * Sends an HTTP DELETE request and wait for a response
7290 *
7291 * httpclient:delete(url, headers, payload)
7292 */
7293__LJMP static int hlua_httpclient_delete(lua_State *L)
7294{
7295 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7296}
7297
7298/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007299 *
7300 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007301 * Class TXN
7302 *
7303 *
7304 */
7305
7306/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007307 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007308 */
7309__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7310{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007311 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007312}
7313
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007314__LJMP static int hlua_set_var(lua_State *L)
7315{
7316 struct hlua_txn *htxn;
7317 const char *name;
7318 size_t len;
7319 struct sample smp;
7320
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007321 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7322 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007323
7324 /* It is useles to retrieve the stream, but this function
7325 * runs only in a stream context.
7326 */
7327 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7328 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7329
7330 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007331 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007332 hlua_lua2smp(L, 3, &smp);
7333
7334 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007335 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007336
7337 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7338 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7339 else
7340 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7341
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007342 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007343}
7344
Christopher Faulet85d79c92016-11-09 16:54:56 +01007345__LJMP static int hlua_unset_var(lua_State *L)
7346{
7347 struct hlua_txn *htxn;
7348 const char *name;
7349 size_t len;
7350 struct sample smp;
7351
7352 MAY_LJMP(check_args(L, 2, "unset_var"));
7353
7354 /* It is useles to retrieve the stream, but this function
7355 * runs only in a stream context.
7356 */
7357 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7358 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7359
7360 /* Unset the variable. */
7361 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007362 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7363 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007364}
7365
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007366__LJMP static int hlua_get_var(lua_State *L)
7367{
7368 struct hlua_txn *htxn;
7369 const char *name;
7370 size_t len;
7371 struct sample smp;
7372
7373 MAY_LJMP(check_args(L, 2, "get_var"));
7374
7375 /* It is useles to retrieve the stream, but this function
7376 * runs only in a stream context.
7377 */
7378 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7379 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7380
Willy Tarreau7560dd42016-03-10 16:28:58 +01007381 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007382 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007383 lua_pushnil(L);
7384 return 1;
7385 }
7386
7387 return hlua_smp2lua(L, &smp);
7388}
7389
Willy Tarreau59551662015-03-10 14:23:13 +01007390__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007391{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007392 struct hlua *hlua;
7393
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007394 MAY_LJMP(check_args(L, 2, "set_priv"));
7395
Willy Tarreau87b09662015-04-03 00:22:06 +02007396 /* It is useles to retrieve the stream, but this function
7397 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007398 */
7399 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007400
7401 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007402 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007403 if (!hlua)
7404 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007405
7406 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007407 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007408
7409 /* Get and store new value. */
7410 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7411 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7412
7413 return 0;
7414}
7415
Willy Tarreau59551662015-03-10 14:23:13 +01007416__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007417{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007418 struct hlua *hlua;
7419
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007420 MAY_LJMP(check_args(L, 1, "get_priv"));
7421
Willy Tarreau87b09662015-04-03 00:22:06 +02007422 /* It is useles to retrieve the stream, but this function
7423 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007424 */
7425 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007426
7427 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007428 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007429 if (!hlua) {
7430 lua_pushnil(L);
7431 return 1;
7432 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007433
7434 /* Push configuration index in the stack. */
7435 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7436
7437 return 1;
7438}
7439
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007440/* Create stack entry containing a class TXN. This function
7441 * return 0 if the stack does not contains free slots,
7442 * otherwise it returns 1.
7443 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007444static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007445{
Willy Tarreaude491382015-04-06 11:04:28 +02007446 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007447
7448 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007449 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007450 return 0;
7451
7452 /* NOTE: The allocation never fails. The failure
7453 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007454 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007455 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007456 /* Create the object: obj[0] = userdata. */
7457 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007458 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007459 lua_rawseti(L, -2, 0);
7460
Willy Tarreaude491382015-04-06 11:04:28 +02007461 htxn->s = s;
7462 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007463 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007464 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007465
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007466 /* Create the "f" field that contains a list of fetches. */
7467 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007468 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007469 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007470 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007471
7472 /* Create the "sf" field that contains a list of stringsafe fetches. */
7473 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007474 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007475 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007476 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007477
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007478 /* Create the "c" field that contains a list of converters. */
7479 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007480 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007481 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007482 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007483
7484 /* Create the "sc" field that contains a list of stringsafe converters. */
7485 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007486 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007487 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007488 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007489
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007490 /* Create the "req" field that contains the request channel object. */
7491 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007492 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007493 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007494 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007495
7496 /* Create the "res" field that contains the response channel object. */
7497 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007498 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007499 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007500 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007501
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007502 /* Creates the HTTP object is the current proxy allows http. */
7503 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007504 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007505 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007506 return 0;
7507 }
7508 else
7509 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007510 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007511
Christopher Faulet78c35472020-02-26 17:14:08 +01007512 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7513 /* HTTPMessage object are created when a lua TXN is created from
7514 * a filter context only
7515 */
7516
7517 /* Creates the HTTP-Request object is the current proxy allows http. */
7518 lua_pushstring(L, "http_req");
7519 if (p->mode == PR_MODE_HTTP) {
7520 if (!hlua_http_msg_new(L, &s->txn->req))
7521 return 0;
7522 }
7523 else
7524 lua_pushnil(L);
7525 lua_rawset(L, -3);
7526
7527 /* Creates the HTTP-Response object is the current proxy allows http. */
7528 lua_pushstring(L, "http_res");
7529 if (p->mode == PR_MODE_HTTP) {
7530 if (!hlua_http_msg_new(L, &s->txn->rsp))
7531 return 0;
7532 }
7533 else
7534 lua_pushnil(L);
7535 lua_rawset(L, -3);
7536 }
7537
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007538 /* Pop a class sesison metatable and affect it to the userdata. */
7539 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7540 lua_setmetatable(L, -2);
7541
7542 return 1;
7543}
7544
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007545__LJMP static int hlua_txn_deflog(lua_State *L)
7546{
7547 const char *msg;
7548 struct hlua_txn *htxn;
7549
7550 MAY_LJMP(check_args(L, 2, "deflog"));
7551 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7552 msg = MAY_LJMP(luaL_checkstring(L, 2));
7553
7554 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7555 return 0;
7556}
7557
7558__LJMP static int hlua_txn_log(lua_State *L)
7559{
7560 int level;
7561 const char *msg;
7562 struct hlua_txn *htxn;
7563
7564 MAY_LJMP(check_args(L, 3, "log"));
7565 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7566 level = MAY_LJMP(luaL_checkinteger(L, 2));
7567 msg = MAY_LJMP(luaL_checkstring(L, 3));
7568
7569 if (level < 0 || level >= NB_LOG_LEVELS)
7570 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7571
7572 hlua_sendlog(htxn->s->be, level, msg);
7573 return 0;
7574}
7575
7576__LJMP static int hlua_txn_log_debug(lua_State *L)
7577{
7578 const char *msg;
7579 struct hlua_txn *htxn;
7580
7581 MAY_LJMP(check_args(L, 2, "Debug"));
7582 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7583 msg = MAY_LJMP(luaL_checkstring(L, 2));
7584 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7585 return 0;
7586}
7587
7588__LJMP static int hlua_txn_log_info(lua_State *L)
7589{
7590 const char *msg;
7591 struct hlua_txn *htxn;
7592
7593 MAY_LJMP(check_args(L, 2, "Info"));
7594 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7595 msg = MAY_LJMP(luaL_checkstring(L, 2));
7596 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7597 return 0;
7598}
7599
7600__LJMP static int hlua_txn_log_warning(lua_State *L)
7601{
7602 const char *msg;
7603 struct hlua_txn *htxn;
7604
7605 MAY_LJMP(check_args(L, 2, "Warning"));
7606 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7607 msg = MAY_LJMP(luaL_checkstring(L, 2));
7608 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7609 return 0;
7610}
7611
7612__LJMP static int hlua_txn_log_alert(lua_State *L)
7613{
7614 const char *msg;
7615 struct hlua_txn *htxn;
7616
7617 MAY_LJMP(check_args(L, 2, "Alert"));
7618 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7619 msg = MAY_LJMP(luaL_checkstring(L, 2));
7620 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7621 return 0;
7622}
7623
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007624__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7625{
7626 struct hlua_txn *htxn;
7627 int ll;
7628
7629 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7630 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7631 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7632
7633 if (ll < 0 || ll > 7)
7634 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7635
7636 htxn->s->logs.level = ll;
7637 return 0;
7638}
7639
7640__LJMP static int hlua_txn_set_tos(lua_State *L)
7641{
7642 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007643 int tos;
7644
7645 MAY_LJMP(check_args(L, 2, "set_tos"));
7646 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7647 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7648
Willy Tarreau1a18b542018-12-11 16:37:42 +01007649 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007650 return 0;
7651}
7652
7653__LJMP static int hlua_txn_set_mark(lua_State *L)
7654{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007655 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007656 int mark;
7657
7658 MAY_LJMP(check_args(L, 2, "set_mark"));
7659 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7660 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7661
Lukas Tribus579e3e32019-08-11 18:03:45 +02007662 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007663 return 0;
7664}
7665
Patrick Hemmer268a7072018-05-11 12:52:31 -04007666__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7667{
7668 struct hlua_txn *htxn;
7669
7670 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7671 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7672 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7673 return 0;
7674}
7675
7676__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7677{
7678 struct hlua_txn *htxn;
7679
7680 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7681 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7682 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7683 return 0;
7684}
7685
Christopher Faulet700d9e82020-01-31 12:21:52 +01007686/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007687 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007688 * message and terminate the transaction. It returns 1 on success and 0 on
7689 * error. The Reply must be on top of the stack.
7690 */
7691__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7692{
7693 struct htx *htx;
7694 struct htx_sl *sl;
7695 struct h1m h1m;
7696 const char *status, *reason, *body;
7697 size_t status_len, reason_len, body_len;
7698 int ret, code, flags;
7699
7700 code = 200;
7701 status = "200";
7702 status_len = 3;
7703 ret = lua_getfield(L, -1, "status");
7704 if (ret == LUA_TNUMBER) {
7705 code = lua_tointeger(L, -1);
7706 status = lua_tolstring(L, -1, &status_len);
7707 }
7708 lua_pop(L, 1);
7709
7710 reason = http_get_reason(code);
7711 reason_len = strlen(reason);
7712 ret = lua_getfield(L, -1, "reason");
7713 if (ret == LUA_TSTRING)
7714 reason = lua_tolstring(L, -1, &reason_len);
7715 lua_pop(L, 1);
7716
7717 body = NULL;
7718 body_len = 0;
7719 ret = lua_getfield(L, -1, "body");
7720 if (ret == LUA_TSTRING)
7721 body = lua_tolstring(L, -1, &body_len);
7722 lua_pop(L, 1);
7723
7724 /* Prepare the response before inserting the headers */
7725 h1m_init_res(&h1m);
7726 htx = htx_from_buf(&s->res.buf);
7727 channel_htx_truncate(&s->res, htx);
7728 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7729 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7730 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7731 ist2(status, status_len), ist2(reason, reason_len));
7732 }
7733 else {
7734 flags = HTX_SL_F_IS_RESP;
7735 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7736 ist2(status, status_len), ist2(reason, reason_len));
7737 }
7738 if (!sl)
7739 goto fail;
7740 sl->info.res.status = code;
7741
7742 /* Push in the stack the "headers" entry. */
7743 ret = lua_getfield(L, -1, "headers");
7744 if (ret != LUA_TTABLE)
7745 goto skip_headers;
7746
7747 lua_pushnil(L);
7748 while (lua_next(L, -2) != 0) {
7749 struct ist name, value;
7750 const char *n, *v;
7751 size_t nlen, vlen;
7752
7753 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7754 /* Skip element if the key is not a string or if the value is not a table */
7755 goto next_hdr;
7756 }
7757
7758 n = lua_tolstring(L, -2, &nlen);
7759 name = ist2(n, nlen);
7760 if (isteqi(name, ist("content-length"))) {
7761 /* Always skip content-length header. It will be added
7762 * later with the correct len
7763 */
7764 goto next_hdr;
7765 }
7766
7767 /* Loop on header's values */
7768 lua_pushnil(L);
7769 while (lua_next(L, -2)) {
7770 if (!lua_isstring(L, -1)) {
7771 /* Skip the value if it is not a string */
7772 goto next_value;
7773 }
7774
7775 v = lua_tolstring(L, -1, &vlen);
7776 value = ist2(v, vlen);
7777
7778 if (isteqi(name, ist("transfer-encoding")))
7779 h1_parse_xfer_enc_header(&h1m, value);
7780 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7781 goto fail;
7782
7783 next_value:
7784 lua_pop(L, 1);
7785 }
7786
7787 next_hdr:
7788 lua_pop(L, 1);
7789 }
7790 skip_headers:
7791 lua_pop(L, 1);
7792
7793 /* Update h1m flags: CLEN is set if CHNK is not present */
7794 if (!(h1m.flags & H1_MF_CHNK)) {
7795 const char *clen = ultoa(body_len);
7796
7797 h1m.flags |= H1_MF_CLEN;
7798 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7799 goto fail;
7800 }
7801 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7802 h1m.flags |= H1_MF_XFER_LEN;
7803
7804 /* Update HTX start-line flags */
7805 if (h1m.flags & H1_MF_XFER_ENC)
7806 flags |= HTX_SL_F_XFER_ENC;
7807 if (h1m.flags & H1_MF_XFER_LEN) {
7808 flags |= HTX_SL_F_XFER_LEN;
7809 if (h1m.flags & H1_MF_CHNK)
7810 flags |= HTX_SL_F_CHNK;
7811 else if (h1m.flags & H1_MF_CLEN)
7812 flags |= HTX_SL_F_CLEN;
7813 if (h1m.body_len == 0)
7814 flags |= HTX_SL_F_BODYLESS;
7815 }
7816 sl->flags |= flags;
7817
7818
7819 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007820 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007821 goto fail;
7822
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007823 htx->flags |= HTX_FL_EOM;
7824
Christopher Faulet700d9e82020-01-31 12:21:52 +01007825 /* Now, forward the response and terminate the transaction */
7826 s->txn->status = code;
7827 htx_to_buf(htx, &s->res.buf);
7828 if (!http_forward_proxy_resp(s, 1))
7829 goto fail;
7830
7831 return 1;
7832
7833 fail:
7834 channel_htx_truncate(&s->res, htx);
7835 return 0;
7836}
7837
7838/* Terminate a transaction if called from a lua action. For TCP streams,
7839 * processing is just aborted. Nothing is returned to the client and all
7840 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7841 * is forwarded to the client before terminating the transaction. On success,
7842 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7843 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7844 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007845 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007846__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007847{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007848 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007849 struct stream *s;
7850 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007851
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007852 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007853
Christopher Faulet700d9e82020-01-31 12:21:52 +01007854 /* If the flags NOTERM is set, we cannot terminate the session, so we
7855 * just end the execution of the current lua code. */
7856 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007857 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007858
Christopher Faulet700d9e82020-01-31 12:21:52 +01007859 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007860 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007861 struct channel *req = &s->req;
7862 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007863
Christopher Faulet700d9e82020-01-31 12:21:52 +01007864 channel_auto_read(req);
7865 channel_abort(req);
7866 channel_auto_close(req);
7867 channel_erase(req);
7868
7869 res->wex = tick_add_ifset(now_ms, res->wto);
7870 channel_auto_read(res);
7871 channel_auto_close(res);
7872 channel_shutr_now(res);
7873
7874 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7875 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007876 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007877
Christopher Faulet700d9e82020-01-31 12:21:52 +01007878 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7879 /* No reply or invalid reply */
7880 s->txn->status = 0;
7881 http_reply_and_close(s, 0, NULL);
7882 }
7883 else {
7884 /* Remove extra args to have the reply on top of the stack */
7885 if (lua_gettop(L) > 2)
7886 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007887
Christopher Faulet700d9e82020-01-31 12:21:52 +01007888 if (!hlua_txn_forward_reply(L, s)) {
7889 if (!(s->flags & SF_ERR_MASK))
7890 s->flags |= SF_ERR_PRXCOND;
7891 lua_pushinteger(L, ACT_RET_ERR);
7892 WILL_LJMP(hlua_done(L));
7893 return 0; /* Never reached */
7894 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007895 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007896
Christopher Faulet700d9e82020-01-31 12:21:52 +01007897 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7898 if (htxn->dir == SMP_OPT_DIR_REQ) {
7899 /* let's log the request time */
7900 s->logs.tv_request = now;
7901 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007902 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007903 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007904
Christopher Faulet700d9e82020-01-31 12:21:52 +01007905 done:
7906 if (!(s->flags & SF_ERR_MASK))
7907 s->flags |= SF_ERR_LOCAL;
7908 if (!(s->flags & SF_FINST_MASK))
7909 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007910
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007911 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7912 lua_pushinteger(L, -1);
7913 else
7914 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007915 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007916 return 0;
7917}
7918
Christopher Faulet700d9e82020-01-31 12:21:52 +01007919/*
7920 *
7921 *
7922 * Class REPLY
7923 *
7924 *
7925 */
7926
7927/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
7928 * free slots, the function fails and returns 0;
7929 */
7930static int hlua_txn_reply_new(lua_State *L)
7931{
7932 struct hlua_txn *htxn;
7933 const char *reason, *body = NULL;
7934 int ret, status;
7935
7936 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007937 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007938 hlua_pusherror(L, "txn object is not an HTTP transaction.");
7939 WILL_LJMP(lua_error(L));
7940 }
7941
7942 /* Default value */
7943 status = 200;
7944 reason = http_get_reason(status);
7945
7946 if (lua_istable(L, 2)) {
7947 /* load status and reason from the table argument at index 2 */
7948 ret = lua_getfield(L, 2, "status");
7949 if (ret == LUA_TNIL)
7950 goto reason;
7951 else if (ret != LUA_TNUMBER) {
7952 /* invalid status: ignore the reason */
7953 goto body;
7954 }
7955 status = lua_tointeger(L, -1);
7956
7957 reason:
7958 lua_pop(L, 1); /* restore the stack: remove status */
7959 ret = lua_getfield(L, 2, "reason");
7960 if (ret == LUA_TSTRING)
7961 reason = lua_tostring(L, -1);
7962
7963 body:
7964 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
7965 ret = lua_getfield(L, 2, "body");
7966 if (ret == LUA_TSTRING)
7967 body = lua_tostring(L, -1);
7968 lua_pop(L, 1); /* restore the stack: remove body */
7969 }
7970
7971 /* Create the Reply table */
7972 lua_newtable(L);
7973
7974 /* Add status element */
7975 lua_pushstring(L, "status");
7976 lua_pushinteger(L, status);
7977 lua_settable(L, -3);
7978
7979 /* Add reason element */
7980 reason = http_get_reason(status);
7981 lua_pushstring(L, "reason");
7982 lua_pushstring(L, reason);
7983 lua_settable(L, -3);
7984
7985 /* Add body element, nil if undefined */
7986 lua_pushstring(L, "body");
7987 if (body)
7988 lua_pushstring(L, body);
7989 else
7990 lua_pushnil(L);
7991 lua_settable(L, -3);
7992
7993 /* Add headers element */
7994 lua_pushstring(L, "headers");
7995 lua_newtable(L);
7996
7997 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7998 if (lua_istable(L, 2)) {
7999 /* load headers from the table argument at index 2. If it is a table, copy it. */
8000 ret = lua_getfield(L, 2, "headers");
8001 if (ret == LUA_TTABLE) {
8002 /* stack: [ ... <headers:table>, <table> ] */
8003 lua_pushnil(L);
8004 while (lua_next(L, -2) != 0) {
8005 /* stack: [ ... <headers:table>, <table>, k, v] */
8006 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8007 /* invalid value type, skip it */
8008 lua_pop(L, 1);
8009 continue;
8010 }
8011
8012
8013 /* Duplicate the key and swap it with the value. */
8014 lua_pushvalue(L, -2);
8015 lua_insert(L, -2);
8016 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8017
8018 lua_newtable(L);
8019 lua_insert(L, -2);
8020 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8021
8022 if (lua_isstring(L, -1)) {
8023 /* push the value in the inner table */
8024 lua_rawseti(L, -2, 1);
8025 }
8026 else { /* table */
8027 lua_pushnil(L);
8028 while (lua_next(L, -2) != 0) {
8029 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8030 if (!lua_isstring(L, -1)) {
8031 /* invalid value type, skip it*/
8032 lua_pop(L, 1);
8033 continue;
8034 }
8035 /* push the value in the inner table */
8036 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8037 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8038 }
8039 lua_pop(L, 1);
8040 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8041 }
8042
8043 /* push (k,v) on the stack in the headers table:
8044 * stack: [ ... <headers:table>, <table>, k, k, v ]
8045 */
8046 lua_settable(L, -5);
8047 /* stack: [ ... <headers:table>, <table>, k ] */
8048 }
8049 }
8050 lua_pop(L, 1);
8051 }
8052 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8053 lua_settable(L, -3);
8054 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8055
8056 /* Pop a class sesison metatable and affect it to the userdata. */
8057 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8058 lua_setmetatable(L, -2);
8059 return 1;
8060}
8061
8062/* Set the reply status code, and optionally the reason. If no reason is
8063 * provided, the default one corresponding to the status code is used.
8064 */
8065__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8066{
8067 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8068 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8069
8070 /* First argument (self) must be a table */
8071 luaL_checktype(L, 1, LUA_TTABLE);
8072
8073 if (status < 100 || status > 599) {
8074 lua_pushboolean(L, 0);
8075 return 1;
8076 }
8077 if (!reason)
8078 reason = http_get_reason(status);
8079
8080 lua_pushinteger(L, status);
8081 lua_setfield(L, 1, "status");
8082
8083 lua_pushstring(L, reason);
8084 lua_setfield(L, 1, "reason");
8085
8086 lua_pushboolean(L, 1);
8087 return 1;
8088}
8089
8090/* Add a header into the reply object. Each header name is associated to an
8091 * array of values in the "headers" table. If the header name is not found, a
8092 * new entry is created.
8093 */
8094__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8095{
8096 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8097 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8098 int ret;
8099
8100 /* First argument (self) must be a table */
8101 luaL_checktype(L, 1, LUA_TTABLE);
8102
8103 /* Push in the stack the "headers" entry. */
8104 ret = lua_getfield(L, 1, "headers");
8105 if (ret != LUA_TTABLE) {
8106 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8107 WILL_LJMP(lua_error(L));
8108 }
8109
8110 /* check if the header is already registered. If not, register it. */
8111 ret = lua_getfield(L, -1, name);
8112 if (ret == LUA_TNIL) {
8113 /* Entry not found. */
8114 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8115
8116 /* Insert the new header name in the array in the top of the stack.
8117 * It left the new array in the top of the stack.
8118 */
8119 lua_newtable(L);
8120 lua_pushstring(L, name);
8121 lua_pushvalue(L, -2);
8122 lua_settable(L, -4);
8123 }
8124 else if (ret != LUA_TTABLE) {
8125 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8126 WILL_LJMP(lua_error(L));
8127 }
8128
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008129 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008130 * the header value as new entry.
8131 */
8132 lua_pushstring(L, value);
8133 ret = lua_rawlen(L, -2);
8134 lua_rawseti(L, -2, ret + 1);
8135
8136 lua_pushboolean(L, 1);
8137 return 1;
8138}
8139
8140/* Remove all occurrences of a given header name. */
8141__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8142{
8143 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8144 int ret;
8145
8146 /* First argument (self) must be a table */
8147 luaL_checktype(L, 1, LUA_TTABLE);
8148
8149 /* Push in the stack the "headers" entry. */
8150 ret = lua_getfield(L, 1, "headers");
8151 if (ret != LUA_TTABLE) {
8152 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8153 WILL_LJMP(lua_error(L));
8154 }
8155
8156 lua_pushstring(L, name);
8157 lua_pushnil(L);
8158 lua_settable(L, -3);
8159
8160 lua_pushboolean(L, 1);
8161 return 1;
8162}
8163
8164/* Set the reply's body. Overwrite any existing entry. */
8165__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8166{
8167 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8168
8169 /* First argument (self) must be a table */
8170 luaL_checktype(L, 1, LUA_TTABLE);
8171
8172 lua_pushstring(L, payload);
8173 lua_setfield(L, 1, "body");
8174
8175 lua_pushboolean(L, 1);
8176 return 1;
8177}
8178
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008179__LJMP static int hlua_log(lua_State *L)
8180{
8181 int level;
8182 const char *msg;
8183
8184 MAY_LJMP(check_args(L, 2, "log"));
8185 level = MAY_LJMP(luaL_checkinteger(L, 1));
8186 msg = MAY_LJMP(luaL_checkstring(L, 2));
8187
8188 if (level < 0 || level >= NB_LOG_LEVELS)
8189 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8190
8191 hlua_sendlog(NULL, level, msg);
8192 return 0;
8193}
8194
8195__LJMP static int hlua_log_debug(lua_State *L)
8196{
8197 const char *msg;
8198
8199 MAY_LJMP(check_args(L, 1, "debug"));
8200 msg = MAY_LJMP(luaL_checkstring(L, 1));
8201 hlua_sendlog(NULL, LOG_DEBUG, msg);
8202 return 0;
8203}
8204
8205__LJMP static int hlua_log_info(lua_State *L)
8206{
8207 const char *msg;
8208
8209 MAY_LJMP(check_args(L, 1, "info"));
8210 msg = MAY_LJMP(luaL_checkstring(L, 1));
8211 hlua_sendlog(NULL, LOG_INFO, msg);
8212 return 0;
8213}
8214
8215__LJMP static int hlua_log_warning(lua_State *L)
8216{
8217 const char *msg;
8218
8219 MAY_LJMP(check_args(L, 1, "warning"));
8220 msg = MAY_LJMP(luaL_checkstring(L, 1));
8221 hlua_sendlog(NULL, LOG_WARNING, msg);
8222 return 0;
8223}
8224
8225__LJMP static int hlua_log_alert(lua_State *L)
8226{
8227 const char *msg;
8228
8229 MAY_LJMP(check_args(L, 1, "alert"));
8230 msg = MAY_LJMP(luaL_checkstring(L, 1));
8231 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008232 return 0;
8233}
8234
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008235__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008236{
8237 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008238 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008239 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008240 return 0;
8241}
8242
8243__LJMP static int hlua_sleep(lua_State *L)
8244{
8245 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008246 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008247
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008248 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008249
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008250 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008251 wakeup_ms = tick_add(now_ms, delay);
8252 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008253
Willy Tarreau9635e032018-10-16 17:52:55 +02008254 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008255 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008256}
8257
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008258__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008259{
8260 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008261 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008262
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008263 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008264
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008265 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008266 wakeup_ms = tick_add(now_ms, delay);
8267 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008268
Willy Tarreau9635e032018-10-16 17:52:55 +02008269 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008270 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008271}
8272
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008273/* This functionis an LUA binding. it permits to give back
8274 * the hand at the HAProxy scheduler. It is used when the
8275 * LUA processing consumes a lot of time.
8276 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008277__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008278{
8279 return 0;
8280}
8281
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008282__LJMP static int hlua_yield(lua_State *L)
8283{
Willy Tarreau9635e032018-10-16 17:52:55 +02008284 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008285 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008286}
8287
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008288/* This function change the nice of the currently executed
8289 * task. It is used set low or high priority at the current
8290 * task.
8291 */
Willy Tarreau59551662015-03-10 14:23:13 +01008292__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008293{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008294 struct hlua *hlua;
8295 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008296
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008297 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008298 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008299
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008300 /* Get hlua struct, or NULL if we execute from main lua state */
8301 hlua = hlua_gethlua(L);
8302
8303 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008304 if (!hlua || !hlua->task)
8305 return 0;
8306
8307 if (nice < -1024)
8308 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008309 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008310 nice = 1024;
8311
8312 hlua->task->nice = nice;
8313 return 0;
8314}
8315
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008316/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008317 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8318 * return an E_AGAIN signal, the emmiter of this signal must set a
8319 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008320 *
8321 * Task wrapper are longjmp safe because the only one Lua code
8322 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008323 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008324struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008325{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008326 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008327 enum hlua_exec status;
8328
Christopher Faulet5bc99722018-04-25 10:34:45 +02008329 if (task->thread_mask == MAX_THREADS_MASK)
8330 task_set_affinity(task, tid_bit);
8331
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008332 /* If it is the first call to the task, we must initialize the
8333 * execution timeouts.
8334 */
8335 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008336 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008337
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008338 /* Execute the Lua code. */
8339 status = hlua_ctx_resume(hlua, 1);
8340
8341 switch (status) {
8342 /* finished or yield */
8343 case HLUA_E_OK:
8344 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008345 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008346 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008347 break;
8348
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008349 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008350 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008351 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008352 break;
8353
8354 /* finished with error. */
8355 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008356 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008357 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008358 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008359 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008360 break;
8361
8362 case HLUA_E_ERR:
8363 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008364 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008365 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008366 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008367 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008368 break;
8369 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008370 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008371}
8372
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008373/* This function is an LUA binding that register LUA function to be
8374 * executed after the HAProxy configuration parsing and before the
8375 * HAProxy scheduler starts. This function expect only one LUA
8376 * argument that is a function. This function returns nothing, but
8377 * throws if an error is encountered.
8378 */
8379__LJMP static int hlua_register_init(lua_State *L)
8380{
8381 struct hlua_init_function *init;
8382 int ref;
8383
8384 MAY_LJMP(check_args(L, 1, "register_init"));
8385
8386 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8387
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008388 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008389 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008390 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008391
8392 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008393 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008394 return 0;
8395}
8396
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008397/* This functio is an LUA binding. It permits to register a task
8398 * executed in parallel of the main HAroxy activity. The task is
8399 * created and it is set in the HAProxy scheduler. It can be called
8400 * from the "init" section, "post init" or during the runtime.
8401 *
8402 * Lua prototype:
8403 *
8404 * <none> core.register_task(<function>)
8405 */
8406static int hlua_register_task(lua_State *L)
8407{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008408 struct hlua *hlua = NULL;
8409 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008410 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008411 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008412
8413 MAY_LJMP(check_args(L, 1, "register_task"));
8414
8415 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8416
Thierry Fournier75fc0292020-11-28 13:18:56 +01008417 /* Get the reference state. If the reference is NULL, L is the master
8418 * state, otherwise hlua->T is.
8419 */
8420 hlua = hlua_gethlua(L);
8421 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008422 /* we are in runtime processing */
8423 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008424 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008425 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008426 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008427
Willy Tarreaubafbe012017-11-24 17:34:44 +01008428 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008429 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008430 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008431 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008432
Thierry Fournier59f11be2020-11-29 00:37:41 +01008433 /* We are in the common lua state, execute the task anywhere,
8434 * otherwise, inherit the current thread identifier
8435 */
8436 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008437 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008438 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008439 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008440 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008441 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008442
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008443 task->context = hlua;
8444 task->process = hlua_process_task;
8445
Thierry Fournier021d9862020-11-28 23:42:03 +01008446 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008447 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008448
8449 /* Restore the function in the stack. */
8450 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8451 hlua->nargs = 0;
8452
8453 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008454 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008455
8456 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008457
8458 alloc_error:
8459 task_destroy(task);
8460 hlua_ctx_destroy(hlua);
8461 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8462 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008463}
8464
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008465/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8466 * doesn't allow "yield" functions because the HAProxy engine cannot
8467 * resume converters.
8468 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008469static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008470{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008471 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008472 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008473 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008474
Willy Tarreaube508f12016-03-10 11:47:01 +01008475 if (!stream)
8476 return 0;
8477
Willy Tarreau87b09662015-04-03 00:22:06 +02008478 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008479 * Lua context can be not initialized. This behavior
8480 * permits to save performances because a systematic
8481 * Lua initialization cause 5% performances loss.
8482 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008483 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008484 struct hlua *hlua;
8485
8486 hlua = pool_alloc(pool_head_hlua);
8487 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008488 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8489 return 0;
8490 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008491 HLUA_INIT(hlua);
8492 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008493 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008494 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8495 return 0;
8496 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008497 }
8498
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008499 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008500 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008501
8502 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008503 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008504 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8505 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008506 else
8507 error = "critical error";
8508 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008509 return 0;
8510 }
8511
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008512 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008513 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008514 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008515 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008516 return 0;
8517 }
8518
8519 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008520 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008521
8522 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008523 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008524 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008525 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008526 return 0;
8527 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008528 hlua_smp2lua(stream->hlua->T, smp);
8529 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008530
8531 /* push keywords in the stack. */
8532 if (arg_p) {
8533 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008534 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008535 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008536 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008537 return 0;
8538 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008539 hlua_arg2lua(stream->hlua->T, arg_p);
8540 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008541 }
8542 }
8543
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008544 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008545 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008546
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008547 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008548 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008549 }
8550
8551 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008552 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008553 /* finished. */
8554 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008555 /* If the stack is empty, the function fails. */
8556 if (lua_gettop(stream->hlua->T) <= 0)
8557 return 0;
8558
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008559 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008560 hlua_lua2smp(stream->hlua->T, -1, smp);
8561 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008562 return 1;
8563
8564 /* yield. */
8565 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008566 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008567 return 0;
8568
8569 /* finished with error. */
8570 case HLUA_E_ERRMSG:
8571 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008572 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008573 fcn->name, lua_tostring(stream->hlua->T, -1));
8574 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008575 return 0;
8576
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008577 case HLUA_E_ETMOUT:
8578 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8579 return 0;
8580
8581 case HLUA_E_NOMEM:
8582 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8583 return 0;
8584
8585 case HLUA_E_YIELD:
8586 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8587 return 0;
8588
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008589 case HLUA_E_ERR:
8590 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008591 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008592 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008593
8594 default:
8595 return 0;
8596 }
8597}
8598
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008599/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8600 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008601 * resume sample-fetches. This function will be called by the sample
8602 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008603 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008604static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8605 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008606{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008607 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008608 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008609 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008610 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008611
Willy Tarreaube508f12016-03-10 11:47:01 +01008612 if (!stream)
8613 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008614
Willy Tarreau87b09662015-04-03 00:22:06 +02008615 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008616 * Lua context can be not initialized. This behavior
8617 * permits to save performances because a systematic
8618 * Lua initialization cause 5% performances loss.
8619 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008620 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008621 struct hlua *hlua;
8622
8623 hlua = pool_alloc(pool_head_hlua);
8624 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008625 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8626 return 0;
8627 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008628 hlua->T = NULL;
8629 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008630 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008631 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8632 return 0;
8633 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008634 }
8635
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008636 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008637 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008638
8639 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008640 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008641 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8642 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008643 else
8644 error = "critical error";
8645 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008646 return 0;
8647 }
8648
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008649 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008650 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008651 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008652 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008653 return 0;
8654 }
8655
8656 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008657 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008658
8659 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008660 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008661 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008662 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008663 return 0;
8664 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008665 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008666
8667 /* push keywords in the stack. */
8668 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8669 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008670 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008671 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008672 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008673 return 0;
8674 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008675 hlua_arg2lua(stream->hlua->T, arg_p);
8676 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008677 }
8678
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008679 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008680 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008681
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008682 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008683 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008684 }
8685
8686 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008687 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008688 /* finished. */
8689 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008690 /* If the stack is empty, the function fails. */
8691 if (lua_gettop(stream->hlua->T) <= 0)
8692 return 0;
8693
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008694 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008695 hlua_lua2smp(stream->hlua->T, -1, smp);
8696 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008697
8698 /* Set the end of execution flag. */
8699 smp->flags &= ~SMP_F_MAY_CHANGE;
8700 return 1;
8701
8702 /* yield. */
8703 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008704 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008705 return 0;
8706
8707 /* finished with error. */
8708 case HLUA_E_ERRMSG:
8709 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008710 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008711 fcn->name, lua_tostring(stream->hlua->T, -1));
8712 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008713 return 0;
8714
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008715 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008716 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8717 return 0;
8718
8719 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008720 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8721 return 0;
8722
8723 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008724 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8725 return 0;
8726
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008727 case HLUA_E_ERR:
8728 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008729 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008730 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008731
8732 default:
8733 return 0;
8734 }
8735}
8736
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008737/* This function is an LUA binding used for registering
8738 * "sample-conv" functions. It expects a converter name used
8739 * in the haproxy configuration file, and an LUA function.
8740 */
8741__LJMP static int hlua_register_converters(lua_State *L)
8742{
8743 struct sample_conv_kw_list *sck;
8744 const char *name;
8745 int ref;
8746 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008747 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008748 struct sample_conv *sc;
8749 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008750
8751 MAY_LJMP(check_args(L, 2, "register_converters"));
8752
8753 /* First argument : converter name. */
8754 name = MAY_LJMP(luaL_checkstring(L, 1));
8755
8756 /* Second argument : lua function. */
8757 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8758
Thierry Fournierf67442e2020-11-28 20:41:07 +01008759 /* Check if the converter is already registered */
8760 trash = get_trash_chunk();
8761 chunk_printf(trash, "lua.%s", name);
8762 sc = find_sample_conv(trash->area, trash->data);
8763 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008764 fcn = sc->private;
8765 if (fcn->function_ref[hlua_state_id] != -1) {
8766 ha_warning("Trying to register converter 'lua.%s' more than once. "
8767 "This will become a hard error in version 2.5.\n", name);
8768 }
8769 fcn->function_ref[hlua_state_id] = ref;
8770 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008771 }
8772
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008773 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008774 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008775 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008776 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008777 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008778 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008779 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008780
8781 /* Fill fcn. */
8782 fcn->name = strdup(name);
8783 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008784 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008785 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008786
8787 /* List head */
8788 sck->list.n = sck->list.p = NULL;
8789
8790 /* converter keyword. */
8791 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008792 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008793 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008794 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008795
8796 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8797 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008798 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 +01008799 sck->kw[0].val_args = NULL;
8800 sck->kw[0].in_type = SMP_T_STR;
8801 sck->kw[0].out_type = SMP_T_STR;
8802 sck->kw[0].private = fcn;
8803
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008804 /* Register this new converter */
8805 sample_register_convs(sck);
8806
8807 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008808
8809 alloc_error:
8810 release_hlua_function(fcn);
8811 ha_free(&sck);
8812 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8813 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008814}
8815
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008816/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008817 * "sample-fetch" functions. It expects a converter name used
8818 * in the haproxy configuration file, and an LUA function.
8819 */
8820__LJMP static int hlua_register_fetches(lua_State *L)
8821{
8822 const char *name;
8823 int ref;
8824 int len;
8825 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008826 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008827 struct sample_fetch *sf;
8828 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008829
8830 MAY_LJMP(check_args(L, 2, "register_fetches"));
8831
8832 /* First argument : sample-fetch name. */
8833 name = MAY_LJMP(luaL_checkstring(L, 1));
8834
8835 /* Second argument : lua function. */
8836 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8837
Thierry Fournierf67442e2020-11-28 20:41:07 +01008838 /* Check if the sample-fetch is already registered */
8839 trash = get_trash_chunk();
8840 chunk_printf(trash, "lua.%s", name);
8841 sf = find_sample_fetch(trash->area, trash->data);
8842 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008843 fcn = sf->private;
8844 if (fcn->function_ref[hlua_state_id] != -1) {
8845 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8846 "This will become a hard error in version 2.5.\n", name);
8847 }
8848 fcn->function_ref[hlua_state_id] = ref;
8849 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008850 }
8851
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008852 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008853 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008854 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008855 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008856 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008857 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008858 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008859
8860 /* Fill fcn. */
8861 fcn->name = strdup(name);
8862 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008863 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008864 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008865
8866 /* List head */
8867 sfk->list.n = sfk->list.p = NULL;
8868
8869 /* sample-fetch keyword. */
8870 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008871 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008872 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008873 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008874
8875 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8876 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008877 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 +01008878 sfk->kw[0].val_args = NULL;
8879 sfk->kw[0].out_type = SMP_T_STR;
8880 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8881 sfk->kw[0].val = 0;
8882 sfk->kw[0].private = fcn;
8883
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008884 /* Register this new fetch. */
8885 sample_register_fetches(sfk);
8886
8887 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008888
8889 alloc_error:
8890 release_hlua_function(fcn);
8891 ha_free(&sfk);
8892 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8893 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008894}
8895
Christopher Faulet501465d2020-02-26 14:54:16 +01008896/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008897 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008898__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008899{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008900 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008901 unsigned int delay;
8902 unsigned int wakeup_ms;
8903
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008904 /* Get hlua struct, or NULL if we execute from main lua state */
8905 hlua = hlua_gethlua(L);
8906 if (!hlua) {
8907 return 0;
8908 }
8909
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008910 MAY_LJMP(check_args(L, 1, "wake_time"));
8911
8912 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8913 wakeup_ms = tick_add(now_ms, delay);
8914 hlua->wake_time = wakeup_ms;
8915 return 0;
8916}
8917
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008918/* This function is a wrapper to execute each LUA function declared as an action
8919 * wrapper during the initialisation period. This function may return any
8920 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8921 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8922 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008923 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008924static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02008925 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008926{
8927 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008928 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008929 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008930 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008931
8932 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008933 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
8934 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
8935 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
8936 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008937 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008938 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008939 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008940 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008941
Willy Tarreau87b09662015-04-03 00:22:06 +02008942 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008943 * Lua context can be not initialized. This behavior
8944 * permits to save performances because a systematic
8945 * Lua initialization cause 5% performances loss.
8946 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008947 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008948 struct hlua *hlua;
8949
8950 hlua = pool_alloc(pool_head_hlua);
8951 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008952 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008953 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008954 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008955 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008956 HLUA_INIT(hlua);
8957 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008958 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 +01008959 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008960 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008961 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008962 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008963 }
8964
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008965 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008966 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008967
8968 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008969 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008970 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
8971 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008972 else
8973 error = "critical error";
8974 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008975 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008976 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008977 }
8978
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008979 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008980 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008981 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008982 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008983 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008984 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008985 }
8986
8987 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008988 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 +01008989
Willy Tarreau87b09662015-04-03 00:22:06 +02008990 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008991 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008992 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008993 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008994 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008995 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008996 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008997 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008998
8999 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009000 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009001 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009002 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009003 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009004 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009005 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009006 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009007 lua_pushstring(s->hlua->T, *arg);
9008 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009009 }
9010
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009011 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009012 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009013
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009014 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009015 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009016 }
9017
9018 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009019 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009020 /* finished. */
9021 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009022 /* Catch the return value */
9023 if (lua_gettop(s->hlua->T) > 0)
9024 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009025
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009026 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009027 if (act_ret == ACT_RET_YIELD) {
9028 if (flags & ACT_OPT_FINAL)
9029 goto err_yield;
9030
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009031 if (dir == SMP_OPT_DIR_REQ)
9032 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9033 s->hlua->wake_time);
9034 else
9035 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9036 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009037 }
9038 goto end;
9039
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009040 /* yield. */
9041 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009042 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009043 if (dir == SMP_OPT_DIR_REQ)
9044 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9045 s->hlua->wake_time);
9046 else
9047 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9048 s->hlua->wake_time);
9049
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009050 /* Some actions can be wake up when a "write" event
9051 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009052 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009053 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009054 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009055 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009056 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009057 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009058 act_ret = ACT_RET_YIELD;
9059 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009060
9061 /* finished with error. */
9062 case HLUA_E_ERRMSG:
9063 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009064 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009065 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009066 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009067 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009068
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009069 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009070 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009071 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009072
9073 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009074 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009075 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009076
9077 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009078 err_yield:
9079 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009080 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009081 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009082 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009083
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009084 case HLUA_E_ERR:
9085 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009086 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009087 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009088
9089 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009090 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009091 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009092
9093 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009094 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009095 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009096 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009097}
9098
Willy Tarreau144f84a2021-03-02 16:09:26 +01009099struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009100{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009101 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009102
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009103 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009104 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009105 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009106}
9107
9108static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
9109{
9110 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009111 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009112 struct task *task;
9113 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009114 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009115
Willy Tarreaubafbe012017-11-24 17:34:44 +01009116 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009117 if (!hlua) {
9118 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009119 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009120 return 0;
9121 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009122 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009123 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009124 ctx->ctx.hlua_apptcp.flags = 0;
9125
9126 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009127 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009128 if (!task) {
9129 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009130 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009131 return 0;
9132 }
9133 task->nice = 0;
9134 task->context = ctx;
9135 task->process = hlua_applet_wakeup;
9136 ctx->ctx.hlua_apptcp.task = task;
9137
9138 /* In the execution wrappers linked with a stream, the
9139 * Lua context can be not initialized. This behavior
9140 * permits to save performances because a systematic
9141 * Lua initialization cause 5% performances loss.
9142 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009143 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 +02009144 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009145 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009146 return 0;
9147 }
9148
9149 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009150 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009151
9152 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009153 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009154 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9155 error = lua_tostring(hlua->T, -1);
9156 else
9157 error = "critical error";
9158 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009159 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009160 return 0;
9161 }
9162
9163 /* Check stack available size. */
9164 if (!lua_checkstack(hlua->T, 1)) {
9165 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009166 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009167 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009168 return 0;
9169 }
9170
9171 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009172 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009173
9174 /* Create and and push object stream in the stack. */
9175 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
9176 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009177 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009178 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009179 return 0;
9180 }
9181 hlua->nargs = 1;
9182
9183 /* push keywords in the stack. */
9184 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9185 if (!lua_checkstack(hlua->T, 1)) {
9186 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009187 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009188 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009189 return 0;
9190 }
9191 lua_pushstring(hlua->T, *arg);
9192 hlua->nargs++;
9193 }
9194
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009195 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009196
9197 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009198 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01009199 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009200
9201 return 1;
9202}
9203
Willy Tarreau60409db2019-08-21 14:14:50 +02009204void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009205{
9206 struct stream_interface *si = ctx->owner;
9207 struct stream *strm = si_strm(si);
9208 struct channel *res = si_ic(si);
9209 struct act_rule *rule = ctx->rule;
9210 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009211 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009212
9213 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02009214 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
9215 /* eat the whole request */
9216 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009217 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009218 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009219
9220 /* If the stream is disconnect or closed, ldo nothing. */
9221 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9222 return;
9223
9224 /* Execute the function. */
9225 switch (hlua_ctx_resume(hlua, 1)) {
9226 /* finished. */
9227 case HLUA_E_OK:
9228 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9229
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009230 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02009231 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009232 res->flags |= CF_READ_NULL;
9233 si_shutr(si);
9234 return;
9235
9236 /* yield. */
9237 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009238 if (hlua->wake_time != TICK_ETERNITY)
9239 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009240 return;
9241
9242 /* finished with error. */
9243 case HLUA_E_ERRMSG:
9244 /* Display log. */
9245 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009246 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009247 lua_pop(hlua->T, 1);
9248 goto error;
9249
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009250 case HLUA_E_ETMOUT:
9251 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009252 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009253 goto error;
9254
9255 case HLUA_E_NOMEM:
9256 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009257 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009258 goto error;
9259
9260 case HLUA_E_YIELD: /* unexpected */
9261 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009262 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009263 goto error;
9264
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009265 case HLUA_E_ERR:
9266 /* Display log. */
9267 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009268 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009269 goto error;
9270
9271 default:
9272 goto error;
9273 }
9274
9275error:
9276
9277 /* For all other cases, just close the stream. */
9278 si_shutw(si);
9279 si_shutr(si);
9280 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9281}
9282
9283static void hlua_applet_tcp_release(struct appctx *ctx)
9284{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009285 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009286 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009287 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009288 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009289}
9290
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009291/* The function returns 1 if the initialisation is complete, 0 if
9292 * an errors occurs and -1 if more data are required for initializing
9293 * the applet.
9294 */
9295static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
9296{
9297 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009298 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009299 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009300 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009301 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009302 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009303
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009304 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009305 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009306 if (!hlua) {
9307 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009308 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009309 return 0;
9310 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009311 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009312 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009313 ctx->ctx.hlua_apphttp.left_bytes = -1;
9314 ctx->ctx.hlua_apphttp.flags = 0;
9315
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009316 if (txn->req.flags & HTTP_MSGF_VER_11)
9317 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
9318
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009319 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009320 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009321 if (!task) {
9322 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009323 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009324 return 0;
9325 }
9326 task->nice = 0;
9327 task->context = ctx;
9328 task->process = hlua_applet_wakeup;
9329 ctx->ctx.hlua_apphttp.task = task;
9330
9331 /* In the execution wrappers linked with a stream, the
9332 * Lua context can be not initialized. This behavior
9333 * permits to save performances because a systematic
9334 * Lua initialization cause 5% performances loss.
9335 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009336 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 +02009337 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009338 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009339 return 0;
9340 }
9341
9342 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009343 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009344
9345 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009346 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009347 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9348 error = lua_tostring(hlua->T, -1);
9349 else
9350 error = "critical error";
9351 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009352 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009353 return 0;
9354 }
9355
9356 /* Check stack available size. */
9357 if (!lua_checkstack(hlua->T, 1)) {
9358 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009359 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009360 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009361 return 0;
9362 }
9363
9364 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009365 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009366
9367 /* Create and and push object stream in the stack. */
9368 if (!hlua_applet_http_new(hlua->T, ctx)) {
9369 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009370 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009371 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009372 return 0;
9373 }
9374 hlua->nargs = 1;
9375
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009376 /* push keywords in the stack. */
9377 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9378 if (!lua_checkstack(hlua->T, 1)) {
9379 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009380 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009381 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009382 return 0;
9383 }
9384 lua_pushstring(hlua->T, *arg);
9385 hlua->nargs++;
9386 }
9387
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009388 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009389
9390 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009391 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009392
9393 return 1;
9394}
9395
Willy Tarreau60409db2019-08-21 14:14:50 +02009396void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009397{
9398 struct stream_interface *si = ctx->owner;
9399 struct stream *strm = si_strm(si);
9400 struct channel *req = si_oc(si);
9401 struct channel *res = si_ic(si);
9402 struct act_rule *rule = ctx->rule;
9403 struct proxy *px = strm->be;
9404 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
9405 struct htx *req_htx, *res_htx;
9406
9407 res_htx = htx_from_buf(&res->buf);
9408
9409 /* If the stream is disconnect or closed, ldo nothing. */
9410 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9411 goto out;
9412
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009413 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009414 if (!b_size(&res->buf)) {
9415 si_rx_room_blk(si);
9416 goto out;
9417 }
9418 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009419 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009420 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9421
9422 /* Set the currently running flag. */
9423 if (!HLUA_IS_RUNNING(hlua) &&
9424 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009425 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009426 si_cant_get(si);
9427 goto out;
9428 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009429 }
9430
9431 /* Executes The applet if it is not done. */
9432 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9433
9434 /* Execute the function. */
9435 switch (hlua_ctx_resume(hlua, 1)) {
9436 /* finished. */
9437 case HLUA_E_OK:
9438 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9439 break;
9440
9441 /* yield. */
9442 case HLUA_E_AGAIN:
9443 if (hlua->wake_time != TICK_ETERNITY)
9444 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009445 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009446
9447 /* finished with error. */
9448 case HLUA_E_ERRMSG:
9449 /* Display log. */
9450 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009451 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009452 lua_pop(hlua->T, 1);
9453 goto error;
9454
9455 case HLUA_E_ETMOUT:
9456 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009457 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009458 goto error;
9459
9460 case HLUA_E_NOMEM:
9461 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009462 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009463 goto error;
9464
9465 case HLUA_E_YIELD: /* unexpected */
9466 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009467 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009468 goto error;
9469
9470 case HLUA_E_ERR:
9471 /* Display log. */
9472 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009473 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009474 goto error;
9475
9476 default:
9477 goto error;
9478 }
9479 }
9480
9481 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009482 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9483 goto done;
9484
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009485 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9486 goto error;
9487
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009488 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
9489 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009490 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9491 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009492 }
9493
9494 done:
9495 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009496 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009497 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009498 si_shutr(si);
9499 }
9500
9501 /* eat the whole request */
9502 if (co_data(req)) {
9503 req_htx = htx_from_buf(&req->buf);
9504 co_htx_skip(req, req_htx, co_data(req));
9505 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009506 }
9507 }
9508
9509 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009510 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009511 return;
9512
9513 error:
9514
9515 /* If we are in HTTP mode, and we are not send any
9516 * data, return a 500 server error in best effort:
9517 * if there is no room available in the buffer,
9518 * just close the connection.
9519 */
9520 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009521 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009522
9523 channel_erase(res);
9524 res->buf.data = b_data(err);
9525 memcpy(res->buf.area, b_head(err), b_data(err));
9526 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009527 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009528 }
9529 if (!(strm->flags & SF_ERR_MASK))
9530 strm->flags |= SF_ERR_RESOURCE;
9531 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9532 goto done;
9533}
9534
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009535static void hlua_applet_http_release(struct appctx *ctx)
9536{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009537 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009538 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009539 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009540 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009541}
9542
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009543/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009544 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009545 *
9546 * This function can fail with an abort() due to an Lua critical error.
9547 * We are in the configuration parsing process of HAProxy, this abort() is
9548 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009549 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009550static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9551 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009552{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009553 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009554 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009555
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009556 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009557 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009558 if (!rule->arg.hlua_rule) {
9559 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009560 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009561 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009562
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009563 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009564 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9565 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009566 if (!rule->arg.hlua_rule->args) {
9567 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009568 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009569 }
9570
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009571 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009572 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009573
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009574 /* Expect some arguments */
9575 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009576 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009577 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009578 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009579 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009580 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009581 if (!rule->arg.hlua_rule->args[i]) {
9582 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009583 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009584 }
9585 (*cur_arg)++;
9586 }
9587 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009588
Thierry FOURNIER42148732015-09-02 17:17:33 +02009589 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009590 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009591 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009592
9593 error:
9594 if (rule->arg.hlua_rule) {
9595 if (rule->arg.hlua_rule->args) {
9596 for (i = 0; i < fcn->nargs; i++)
9597 ha_free(&rule->arg.hlua_rule->args[i]);
9598 ha_free(&rule->arg.hlua_rule->args);
9599 }
9600 ha_free(&rule->arg.hlua_rule);
9601 }
9602 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009603}
9604
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009605static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9606 struct act_rule *rule, char **err)
9607{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009608 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009609
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009610 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009611 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009612 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009613 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009614 * the call of this analyzer.
9615 */
9616 if (rule->from != ACT_F_HTTP_REQ) {
9617 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9618 return ACT_RET_PRS_ERR;
9619 }
9620
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009621 /* Memory for the rule. */
9622 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9623 if (!rule->arg.hlua_rule) {
9624 memprintf(err, "out of memory error");
9625 return ACT_RET_PRS_ERR;
9626 }
9627
9628 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009629 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009630
9631 /* TODO: later accept arguments. */
9632 rule->arg.hlua_rule->args = NULL;
9633
9634 /* Add applet pointer in the rule. */
9635 rule->applet.obj_type = OBJ_TYPE_APPLET;
9636 rule->applet.name = fcn->name;
9637 rule->applet.init = hlua_applet_http_init;
9638 rule->applet.fct = hlua_applet_http_fct;
9639 rule->applet.release = hlua_applet_http_release;
9640 rule->applet.timeout = hlua_timeout_applet;
9641
9642 return ACT_RET_PRS_OK;
9643}
9644
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009645/* This function is an LUA binding used for registering
9646 * "sample-conv" functions. It expects a converter name used
9647 * in the haproxy configuration file, and an LUA function.
9648 */
9649__LJMP static int hlua_register_action(lua_State *L)
9650{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009651 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009652 const char *name;
9653 int ref;
9654 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009655 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009656 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009657 struct buffer *trash;
9658 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009659
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009660 /* Initialise the number of expected arguments at 0. */
9661 nargs = 0;
9662
9663 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9664 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009665
9666 /* First argument : converter name. */
9667 name = MAY_LJMP(luaL_checkstring(L, 1));
9668
9669 /* Second argument : environment. */
9670 if (lua_type(L, 2) != LUA_TTABLE)
9671 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9672
9673 /* Third argument : lua function. */
9674 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9675
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009676 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009677 if (lua_gettop(L) >= 4)
9678 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9679
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009680 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009681 lua_pushnil(L);
9682 while (lua_next(L, 2) != 0) {
9683 if (lua_type(L, -1) != LUA_TSTRING)
9684 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9685
Thierry Fournierf67442e2020-11-28 20:41:07 +01009686 /* Check if action exists */
9687 trash = get_trash_chunk();
9688 chunk_printf(trash, "lua.%s", name);
9689 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9690 akw = tcp_req_cont_action(trash->area);
9691 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9692 akw = tcp_res_cont_action(trash->area);
9693 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9694 akw = action_http_req_custom(trash->area);
9695 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9696 akw = action_http_res_custom(trash->area);
9697 } else {
9698 akw = NULL;
9699 }
9700 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009701 fcn = akw->private;
9702 if (fcn->function_ref[hlua_state_id] != -1) {
9703 ha_warning("Trying to register action 'lua.%s' more than once. "
9704 "This will become a hard error in version 2.5.\n", name);
9705 }
9706 fcn->function_ref[hlua_state_id] = ref;
9707
9708 /* pop the environment string. */
9709 lua_pop(L, 1);
9710 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009711 }
9712
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009713 /* Check required environment. Only accepted "http" or "tcp". */
9714 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009715 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009716 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009717 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009718 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009719 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009720 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009721
9722 /* Fill fcn. */
9723 fcn->name = strdup(name);
9724 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009725 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009726 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009727
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009728 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009729 fcn->nargs = nargs;
9730
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009731 /* List head */
9732 akl->list.n = akl->list.p = NULL;
9733
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009734 /* action keyword. */
9735 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009736 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009737 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009738 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009739
9740 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9741
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009742 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009743 akl->kw[0].private = fcn;
9744 akl->kw[0].parse = action_register_lua;
9745
9746 /* select the action registering point. */
9747 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9748 tcp_req_cont_keywords_register(akl);
9749 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9750 tcp_res_cont_keywords_register(akl);
9751 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9752 http_req_keywords_register(akl);
9753 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9754 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009755 else {
9756 release_hlua_function(fcn);
9757 if (akl)
9758 ha_free((char **)&(akl->kw[0].kw));
9759 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009760 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009761 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9762 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009763 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009764
9765 /* pop the environment string. */
9766 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009767
9768 /* reset for next loop */
9769 akl = NULL;
9770 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009771 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009772 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009773
9774 alloc_error:
9775 release_hlua_function(fcn);
9776 ha_free(&akl);
9777 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9778 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009779}
9780
9781static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9782 struct act_rule *rule, char **err)
9783{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009784 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009785
Christopher Faulet280f85b2019-07-15 15:02:04 +02009786 if (px->mode == PR_MODE_HTTP) {
9787 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009788 return ACT_RET_PRS_ERR;
9789 }
9790
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009791 /* Memory for the rule. */
9792 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9793 if (!rule->arg.hlua_rule) {
9794 memprintf(err, "out of memory error");
9795 return ACT_RET_PRS_ERR;
9796 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009797
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009798 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009799 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009800
9801 /* TODO: later accept arguments. */
9802 rule->arg.hlua_rule->args = NULL;
9803
9804 /* Add applet pointer in the rule. */
9805 rule->applet.obj_type = OBJ_TYPE_APPLET;
9806 rule->applet.name = fcn->name;
9807 rule->applet.init = hlua_applet_tcp_init;
9808 rule->applet.fct = hlua_applet_tcp_fct;
9809 rule->applet.release = hlua_applet_tcp_release;
9810 rule->applet.timeout = hlua_timeout_applet;
9811
9812 return 0;
9813}
9814
9815/* This function is an LUA binding used for registering
9816 * "sample-conv" functions. It expects a converter name used
9817 * in the haproxy configuration file, and an LUA function.
9818 */
9819__LJMP static int hlua_register_service(lua_State *L)
9820{
9821 struct action_kw_list *akl;
9822 const char *name;
9823 const char *env;
9824 int ref;
9825 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009826 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009827 struct buffer *trash;
9828 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009829
9830 MAY_LJMP(check_args(L, 3, "register_service"));
9831
9832 /* First argument : converter name. */
9833 name = MAY_LJMP(luaL_checkstring(L, 1));
9834
9835 /* Second argument : environment. */
9836 env = MAY_LJMP(luaL_checkstring(L, 2));
9837
9838 /* Third argument : lua function. */
9839 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9840
Thierry Fournierf67442e2020-11-28 20:41:07 +01009841 /* Check for service already registered */
9842 trash = get_trash_chunk();
9843 chunk_printf(trash, "lua.%s", name);
9844 akw = service_find(trash->area);
9845 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009846 fcn = akw->private;
9847 if (fcn->function_ref[hlua_state_id] != -1) {
9848 ha_warning("Trying to register service 'lua.%s' more than once. "
9849 "This will become a hard error in version 2.5.\n", name);
9850 }
9851 fcn->function_ref[hlua_state_id] = ref;
9852 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009853 }
9854
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009855 /* Allocate and fill the sample fetch keyword struct. */
9856 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9857 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009858 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009859 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009860 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009861 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009862
9863 /* Fill fcn. */
9864 len = strlen("<lua.>") + strlen(name) + 1;
9865 fcn->name = calloc(1, len);
9866 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009867 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009868 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009869 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009870
9871 /* List head */
9872 akl->list.n = akl->list.p = NULL;
9873
9874 /* converter keyword. */
9875 len = strlen("lua.") + strlen(name) + 1;
9876 akl->kw[0].kw = calloc(1, len);
9877 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009878 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009879
9880 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9881
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009882 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009883 if (strcmp(env, "tcp") == 0)
9884 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009885 else if (strcmp(env, "http") == 0)
9886 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009887 else {
9888 release_hlua_function(fcn);
9889 if (akl)
9890 ha_free((char **)&(akl->kw[0].kw));
9891 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009892 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009893 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009894 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009895
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009896 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009897 akl->kw[0].private = fcn;
9898
9899 /* End of array. */
9900 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9901
9902 /* Register this new converter */
9903 service_keywords_register(akl);
9904
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009905 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009906
9907 alloc_error:
9908 release_hlua_function(fcn);
9909 ha_free(&akl);
9910 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9911 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009912}
9913
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009914/* This function initialises Lua cli handler. It copies the
9915 * arguments in the Lua stack and create channel IO objects.
9916 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02009917static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009918{
9919 struct hlua *hlua;
9920 struct hlua_function *fcn;
9921 int i;
9922 const char *error;
9923
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009924 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009925 appctx->ctx.hlua_cli.fcn = private;
9926
Willy Tarreaubafbe012017-11-24 17:34:44 +01009927 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009928 if (!hlua) {
9929 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009930 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009931 }
9932 HLUA_INIT(hlua);
9933 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009934
9935 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05009936 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009937 * applet_http. It is absolutely compatible.
9938 */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009939 appctx->ctx.hlua_cli.task = task_new_here();
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009940 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01009941 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009942 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009943 }
9944 appctx->ctx.hlua_cli.task->nice = 0;
9945 appctx->ctx.hlua_cli.task->context = appctx;
9946 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
9947
9948 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +01009949 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 +01009950 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009951 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009952 }
9953
9954 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009955 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009956 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9957 error = lua_tostring(hlua->T, -1);
9958 else
9959 error = "critical error";
9960 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
9961 goto error;
9962 }
9963
9964 /* Check stack available size. */
9965 if (!lua_checkstack(hlua->T, 2)) {
9966 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9967 goto error;
9968 }
9969
9970 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009971 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009972
9973 /* Once the arguments parsed, the CLI is like an AppletTCP,
9974 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009975 */
9976 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
9977 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9978 goto error;
9979 }
9980 hlua->nargs = 1;
9981
9982 /* push keywords in the stack. */
9983 for (i = 0; *args[i]; i++) {
9984 /* Check stack available size. */
9985 if (!lua_checkstack(hlua->T, 1)) {
9986 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9987 goto error;
9988 }
9989 lua_pushstring(hlua->T, args[i]);
9990 hlua->nargs++;
9991 }
9992
9993 /* We must initialize the execution timeouts. */
9994 hlua->max_time = hlua_timeout_session;
9995
9996 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009997 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009998
9999 /* It's ok */
10000 return 0;
10001
10002 /* It's not ok. */
10003error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010004 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010005 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010006 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010007 return 1;
10008}
10009
10010static int hlua_cli_io_handler_fct(struct appctx *appctx)
10011{
10012 struct hlua *hlua;
10013 struct stream_interface *si;
10014 struct hlua_function *fcn;
10015
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010016 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010017 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +010010018 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010019
10020 /* If the stream is disconnect or closed, ldo nothing. */
10021 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
10022 return 1;
10023
10024 /* Execute the function. */
10025 switch (hlua_ctx_resume(hlua, 1)) {
10026
10027 /* finished. */
10028 case HLUA_E_OK:
10029 return 1;
10030
10031 /* yield. */
10032 case HLUA_E_AGAIN:
10033 /* We want write. */
10034 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +010010035 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010036 /* Set the timeout. */
10037 if (hlua->wake_time != TICK_ETERNITY)
10038 task_schedule(hlua->task, hlua->wake_time);
10039 return 0;
10040
10041 /* finished with error. */
10042 case HLUA_E_ERRMSG:
10043 /* Display log. */
10044 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10045 fcn->name, lua_tostring(hlua->T, -1));
10046 lua_pop(hlua->T, 1);
10047 return 1;
10048
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010049 case HLUA_E_ETMOUT:
10050 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10051 fcn->name);
10052 return 1;
10053
10054 case HLUA_E_NOMEM:
10055 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10056 fcn->name);
10057 return 1;
10058
10059 case HLUA_E_YIELD: /* unexpected */
10060 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10061 fcn->name);
10062 return 1;
10063
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010064 case HLUA_E_ERR:
10065 /* Display log. */
10066 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10067 fcn->name);
10068 return 1;
10069
10070 default:
10071 return 1;
10072 }
10073
10074 return 1;
10075}
10076
10077static void hlua_cli_io_release_fct(struct appctx *appctx)
10078{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010079 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010080 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010081}
10082
10083/* This function is an LUA binding used for registering
10084 * new keywords in the cli. It expects a list of keywords
10085 * which are the "path". It is limited to 5 keywords. A
10086 * description of the command, a function to be executed
10087 * for the parsing and a function for io handlers.
10088 */
10089__LJMP static int hlua_register_cli(lua_State *L)
10090{
10091 struct cli_kw_list *cli_kws;
10092 const char *message;
10093 int ref_io;
10094 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010095 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010096 int index;
10097 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010098 struct buffer *trash;
10099 const char *kw[5];
10100 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010101 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010102
10103 MAY_LJMP(check_args(L, 3, "register_cli"));
10104
10105 /* First argument : an array of maximum 5 keywords. */
10106 if (!lua_istable(L, 1))
10107 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10108
10109 /* Second argument : string with contextual message. */
10110 message = MAY_LJMP(luaL_checkstring(L, 2));
10111
10112 /* Third and fourth argument : lua function. */
10113 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10114
Thierry Fournierf67442e2020-11-28 20:41:07 +010010115 /* Check for CLI service already registered */
10116 trash = get_trash_chunk();
10117 index = 0;
10118 lua_pushnil(L);
10119 memset(kw, 0, sizeof(kw));
10120 while (lua_next(L, 1) != 0) {
10121 if (index >= CLI_PREFIX_KW_NB)
10122 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10123 if (lua_type(L, -1) != LUA_TSTRING)
10124 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10125 kw[index] = lua_tostring(L, -1);
10126 if (index == 0)
10127 chunk_printf(trash, "%s", kw[index]);
10128 else
10129 chunk_appendf(trash, " %s", kw[index]);
10130 index++;
10131 lua_pop(L, 1);
10132 }
10133 cli_kw = cli_find_kw_exact((char **)kw);
10134 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010135 fcn = cli_kw->private;
10136 if (fcn->function_ref[hlua_state_id] != -1) {
10137 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10138 "This will become a hard error in version 2.5.\n", trash->area);
10139 }
10140 fcn->function_ref[hlua_state_id] = ref_io;
10141 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010142 }
10143
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010144 /* Allocate and fill the sample fetch keyword struct. */
10145 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010146 if (!cli_kws) {
10147 errmsg = "Lua out of memory error.";
10148 goto error;
10149 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010150 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010151 if (!fcn) {
10152 errmsg = "Lua out of memory error.";
10153 goto error;
10154 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010155
10156 /* Fill path. */
10157 index = 0;
10158 lua_pushnil(L);
10159 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010160 if (index >= 5) {
10161 errmsg = "1st argument must be a table with a maximum of 5 entries";
10162 goto error;
10163 }
10164 if (lua_type(L, -1) != LUA_TSTRING) {
10165 errmsg = "1st argument must be a table filled with strings";
10166 goto error;
10167 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010168 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010169 if (!cli_kws->kw[0].str_kw[index]) {
10170 errmsg = "Lua out of memory error.";
10171 goto error;
10172 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010173 index++;
10174 lua_pop(L, 1);
10175 }
10176
10177 /* Copy help message. */
10178 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010179 if (!cli_kws->kw[0].usage) {
10180 errmsg = "Lua out of memory error.";
10181 goto error;
10182 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010183
10184 /* Fill fcn io handler. */
10185 len = strlen("<lua.cli>") + 1;
10186 for (i = 0; i < index; i++)
10187 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10188 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010189 if (!fcn->name) {
10190 errmsg = "Lua out of memory error.";
10191 goto error;
10192 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010193 strncat((char *)fcn->name, "<lua.cli", len);
10194 for (i = 0; i < index; i++) {
10195 strncat((char *)fcn->name, ".", len);
10196 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10197 }
10198 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010199 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010200
10201 /* Fill last entries. */
10202 cli_kws->kw[0].private = fcn;
10203 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10204 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10205 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10206
10207 /* Register this new converter */
10208 cli_register_kw(cli_kws);
10209
10210 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010211
10212 error:
10213 release_hlua_function(fcn);
10214 if (cli_kws) {
10215 for (i = 0; i < index; i++)
10216 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10217 ha_free((char **)&(cli_kws->kw[0].usage));
10218 }
10219 ha_free(&cli_kws);
10220 WILL_LJMP(luaL_error(L, errmsg));
10221 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010222}
10223
Christopher Faulet69c581a2021-05-31 08:54:04 +020010224static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10225{
10226 struct hlua_flt_config *conf = fconf->conf;
10227 lua_State *L;
10228 int error, pos, state_id, flt_ref;
10229
10230 state_id = reg_flt_to_stack_id(conf->reg);
10231 L = hlua_states[state_id];
10232 pos = lua_gettop(L);
10233
10234 /* The filter parsing function */
10235 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10236
10237 /* Push the filter class on the stack and resolve all callbacks */
10238 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10239
10240 /* Duplicate the filter class so each filter will have its own copy */
10241 lua_newtable(L);
10242 lua_pushnil(L);
10243
10244 while (lua_next(L, pos+2)) {
10245 lua_pushvalue(L, -2);
10246 lua_insert(L, -2);
10247 lua_settable(L, -4);
10248 }
10249 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10250
10251 /* Remove the original lua filter class from the stack */
10252 lua_pop(L, 1);
10253
10254 /* Push the copy on the stack */
10255 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10256
10257 /* extra args are pushed in a table */
10258 lua_newtable(L);
10259 for (pos = 0; conf->args[pos]; pos++) {
10260 /* Check stack available size. */
10261 if (!lua_checkstack(L, 1)) {
10262 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10263 goto error;
10264 }
10265 lua_pushstring(L, conf->args[pos]);
10266 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10267 }
10268
10269 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10270 switch (error) {
10271 case LUA_OK:
10272 /* replace the filter ref */
10273 conf->ref[state_id] = flt_ref;
10274 break;
10275 case LUA_ERRRUN:
10276 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10277 goto error;
10278 case LUA_ERRMEM:
10279 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10280 goto error;
10281 case LUA_ERRERR:
10282 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10283 goto error;
10284#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10285 case LUA_ERRGCMM:
10286 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10287 goto error;
10288#endif
10289 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010290 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010291 goto error;
10292 }
10293
10294 lua_settop(L, 0);
10295 return 0;
10296
10297 error:
10298 lua_settop(L, 0);
10299 return -1;
10300}
10301
10302static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10303{
10304 struct hlua_flt_config *conf = fconf->conf;
10305 lua_State *L;
10306 int state_id;
10307
10308 if (!conf)
10309 return;
10310
10311 state_id = reg_flt_to_stack_id(conf->reg);
10312 L = hlua_states[state_id];
10313 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10314}
10315
10316static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10317{
10318 struct hlua_flt_config *conf = fconf->conf;
10319 int state_id = reg_flt_to_stack_id(conf->reg);
10320
10321 /* Rely on per-thread init for global scripts */
10322 if (!state_id)
10323 return hlua_filter_init_per_thread(px, fconf);
10324 return 0;
10325}
10326
10327static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10328{
10329
10330 if (fconf->conf) {
10331 struct hlua_flt_config *conf = fconf->conf;
10332 int state_id = reg_flt_to_stack_id(conf->reg);
10333 int pos;
10334
10335 /* Rely on per-thread deinit for global scripts */
10336 if (!state_id)
10337 hlua_filter_deinit_per_thread(px, fconf);
10338
10339 for (pos = 0; conf->args[pos]; pos++)
10340 free(conf->args[pos]);
10341 free(conf->args);
10342 }
10343 ha_free(&fconf->conf);
10344 ha_free((char **)&fconf->id);
10345 ha_free(&fconf->ops);
10346}
10347
10348static int hlua_filter_new(struct stream *s, struct filter *filter)
10349{
10350 struct hlua_flt_config *conf = FLT_CONF(filter);
10351 struct hlua_flt_ctx *flt_ctx = NULL;
10352 int ret = 1;
10353
10354 /* In the execution wrappers linked with a stream, the
10355 * Lua context can be not initialized. This behavior
10356 * permits to save performances because a systematic
10357 * Lua initialization cause 5% performances loss.
10358 */
10359 if (!s->hlua) {
10360 struct hlua *hlua;
10361
10362 hlua = pool_alloc(pool_head_hlua);
10363 if (!hlua) {
10364 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10365 conf->reg->name);
10366 ret = 0;
10367 goto end;
10368 }
10369 HLUA_INIT(hlua);
10370 s->hlua = hlua;
10371 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10372 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10373 conf->reg->name);
10374 ret = 0;
10375 goto end;
10376 }
10377 }
10378
10379 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10380 if (!flt_ctx) {
10381 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10382 conf->reg->name);
10383 ret = 0;
10384 goto end;
10385 }
10386 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10387 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10388 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10389 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10390 conf->reg->name);
10391 ret = 0;
10392 goto end;
10393 }
10394 HLUA_INIT(flt_ctx->hlua[0]);
10395 HLUA_INIT(flt_ctx->hlua[1]);
10396 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10397 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10398 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10399 conf->reg->name);
10400 ret = 0;
10401 goto end;
10402 }
10403
10404 if (!HLUA_IS_RUNNING(s->hlua)) {
10405 /* The following Lua calls can fail. */
10406 if (!SET_SAFE_LJMP(s->hlua)) {
10407 const char *error;
10408
10409 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10410 error = lua_tostring(s->hlua->T, -1);
10411 else
10412 error = "critical error";
10413 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10414 ret = 0;
10415 goto end;
10416 }
10417
10418 /* Check stack size. */
10419 if (!lua_checkstack(s->hlua->T, 1)) {
10420 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010421 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010422 ret = 0;
10423 goto end;
10424 }
10425
10426 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10427 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10428 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10429 conf->reg->name);
10430 RESET_SAFE_LJMP(s->hlua);
10431 ret = 0;
10432 goto end;
10433 }
10434 lua_insert(s->hlua->T, -2);
10435
10436 /* Push the copy on the stack */
10437 s->hlua->nargs = 1;
10438
10439 /* We must initialize the execution timeouts. */
10440 s->hlua->max_time = hlua_timeout_session;
10441
10442 /* At this point the execution is safe. */
10443 RESET_SAFE_LJMP(s->hlua);
10444 }
10445
10446 switch (hlua_ctx_resume(s->hlua, 0)) {
10447 case HLUA_E_OK:
10448 /* Nothing returned or not a table, ignore the filter for current stream */
10449 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10450 ret = 0;
10451 goto end;
10452 }
10453
10454 /* Attached the filter pointer to the ctx */
10455 lua_pushstring(s->hlua->T, "__filter");
10456 lua_pushlightuserdata(s->hlua->T, filter);
10457 lua_settable(s->hlua->T, -3);
10458
10459 /* Save a ref on the filter ctx */
10460 lua_pushvalue(s->hlua->T, 1);
10461 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10462 filter->ctx = flt_ctx;
10463 break;
10464 case HLUA_E_ERRMSG:
10465 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10466 ret = -1;
10467 goto end;
10468 case HLUA_E_ETMOUT:
10469 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10470 ret = 0;
10471 goto end;
10472 case HLUA_E_NOMEM:
10473 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10474 ret = 0;
10475 goto end;
10476 case HLUA_E_AGAIN:
10477 case HLUA_E_YIELD:
10478 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10479 " are not allowed from 'new' function.\n", conf->reg->name);
10480 ret = 0;
10481 goto end;
10482 case HLUA_E_ERR:
10483 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10484 ret = 0;
10485 goto end;
10486 default:
10487 ret = 0;
10488 goto end;
10489 }
10490
10491 end:
10492 if (s->hlua)
10493 lua_settop(s->hlua->T, 0);
10494 if (ret <= 0) {
10495 if (flt_ctx) {
10496 hlua_ctx_destroy(flt_ctx->hlua[0]);
10497 hlua_ctx_destroy(flt_ctx->hlua[1]);
10498 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10499 }
10500 }
10501 return ret;
10502}
10503
10504static void hlua_filter_delete(struct stream *s, struct filter *filter)
10505{
10506 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10507
10508 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10509 hlua_ctx_destroy(flt_ctx->hlua[0]);
10510 hlua_ctx_destroy(flt_ctx->hlua[1]);
10511 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10512 filter->ctx = NULL;
10513}
10514
Christopher Faulet9f55a502020-02-25 15:21:02 +010010515static int hlua_filter_from_payload(struct filter *filter)
10516{
10517 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10518
10519 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10520}
10521
Christopher Fauletc404f112020-02-26 15:03:09 +010010522static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10523 int dir, unsigned int flags)
10524{
10525 struct hlua *flt_hlua;
10526 struct hlua_flt_config *conf = FLT_CONF(filter);
10527 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10528 unsigned int hflags = HLUA_TXN_FLT_CTX;
10529 int ret = 1;
10530
10531 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10532 if (!flt_hlua)
10533 goto end;
10534
10535 if (!HLUA_IS_RUNNING(flt_hlua)) {
10536 int extra_idx = lua_gettop(flt_hlua->T);
10537
10538 /* The following Lua calls can fail. */
10539 if (!SET_SAFE_LJMP(flt_hlua)) {
10540 const char *error;
10541
10542 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10543 error = lua_tostring(flt_hlua->T, -1);
10544 else
10545 error = "critical error";
10546 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10547 goto end;
10548 }
10549
10550 /* Check stack size. */
10551 if (!lua_checkstack(flt_hlua->T, 3)) {
10552 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10553 RESET_SAFE_LJMP(flt_hlua);
10554 goto end;
10555 }
10556
10557 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10558 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10559 RESET_SAFE_LJMP(flt_hlua);
10560 goto end;
10561 }
10562 lua_insert(flt_hlua->T, -2);
10563
10564 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10565 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10566 RESET_SAFE_LJMP(flt_hlua);
10567 goto end;
10568 }
10569 flt_hlua->nargs = 2;
10570
10571 if (flags & HLUA_FLT_CB_ARG_CHN) {
10572 if (dir == SMP_OPT_DIR_REQ)
10573 lua_getfield(flt_hlua->T, -1, "req");
10574 else
10575 lua_getfield(flt_hlua->T, -1, "res");
10576 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10577 lua_pushstring(flt_hlua->T, "__filter");
10578 lua_pushlightuserdata(flt_hlua->T, filter);
10579 lua_settable(flt_hlua->T, -3);
10580 }
10581 flt_hlua->nargs++;
10582 }
10583 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010584 if (dir == SMP_OPT_DIR_REQ)
10585 lua_getfield(flt_hlua->T, -1, "http_req");
10586 else
10587 lua_getfield(flt_hlua->T, -1, "http_res");
10588 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10589 lua_pushstring(flt_hlua->T, "__filter");
10590 lua_pushlightuserdata(flt_hlua->T, filter);
10591 lua_settable(flt_hlua->T, -3);
10592 }
10593 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010594 }
10595
10596 /* Check stack size. */
10597 if (!lua_checkstack(flt_hlua->T, 1)) {
10598 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10599 RESET_SAFE_LJMP(flt_hlua);
10600 goto end;
10601 }
10602
10603 while (extra_idx--) {
10604 lua_pushvalue(flt_hlua->T, 1);
10605 lua_remove(flt_hlua->T, 1);
10606 flt_hlua->nargs++;
10607 }
10608
10609 /* We must initialize the execution timeouts. */
10610 flt_hlua->max_time = hlua_timeout_session;
10611
10612 /* At this point the execution is safe. */
10613 RESET_SAFE_LJMP(flt_hlua);
10614 }
10615
10616 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10617 case HLUA_E_OK:
10618 /* Catch the return value if it required */
10619 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10620 ret = lua_tointeger(flt_hlua->T, -1);
10621 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10622 }
10623
10624 /* Set timeout in the required channel. */
10625 if (flt_hlua->wake_time != TICK_ETERNITY) {
10626 if (dir == SMP_OPT_DIR_REQ)
10627 s->req.analyse_exp = flt_hlua->wake_time;
10628 else
10629 s->res.analyse_exp = flt_hlua->wake_time;
10630 }
10631 break;
10632 case HLUA_E_AGAIN:
10633 /* Set timeout in the required channel. */
10634 if (flt_hlua->wake_time != TICK_ETERNITY) {
10635 if (dir == SMP_OPT_DIR_REQ)
10636 s->req.analyse_exp = flt_hlua->wake_time;
10637 else
10638 s->res.analyse_exp = flt_hlua->wake_time;
10639 }
10640 /* Some actions can be wake up when a "write" event
10641 * is detected on a response channel. This is useful
10642 * only for actions targeted on the requests.
10643 */
10644 if (HLUA_IS_WAKERESWR(flt_hlua))
10645 s->res.flags |= CF_WAKE_WRITE;
10646 if (HLUA_IS_WAKEREQWR(flt_hlua))
10647 s->req.flags |= CF_WAKE_WRITE;
10648 ret = 0;
10649 goto end;
10650 case HLUA_E_ERRMSG:
10651 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10652 ret = -1;
10653 goto end;
10654 case HLUA_E_ETMOUT:
10655 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10656 goto end;
10657 case HLUA_E_NOMEM:
10658 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10659 goto end;
10660 case HLUA_E_YIELD:
10661 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10662 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10663 goto end;
10664 case HLUA_E_ERR:
10665 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10666 goto end;
10667 default:
10668 goto end;
10669 }
10670
10671
10672 end:
10673 return ret;
10674}
10675
10676static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10677{
10678 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10679
10680 flt_ctx->flags = 0;
10681 return hlua_filter_callback(s, filter, "start_analyze",
10682 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10683 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10684}
10685
10686static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10687{
10688 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10689
10690 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10691 return hlua_filter_callback(s, filter, "end_analyze",
10692 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10693 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10694}
10695
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010696static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10697{
10698 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10699
10700 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10701 return hlua_filter_callback(s, filter, "http_headers",
10702 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10703 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10704}
10705
10706static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10707 unsigned int offset, unsigned int len)
10708{
10709 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10710 struct hlua *flt_hlua;
10711 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10712 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10713 int ret;
10714
10715 flt_hlua = flt_ctx->hlua[idx];
10716 flt_ctx->cur_off[idx] = offset;
10717 flt_ctx->cur_len[idx] = len;
10718 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10719 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10720 if (ret != -1) {
10721 ret = flt_ctx->cur_len[idx];
10722 if (lua_gettop(flt_hlua->T) > 0) {
10723 ret = lua_tointeger(flt_hlua->T, -1);
10724 if (ret > flt_ctx->cur_len[idx])
10725 ret = flt_ctx->cur_len[idx];
10726 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10727 }
10728 }
10729 return ret;
10730}
10731
10732static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10733{
10734 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10735
10736 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10737 return hlua_filter_callback(s, filter, "http_end",
10738 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10739 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10740}
10741
Christopher Fauletc404f112020-02-26 15:03:09 +010010742static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10743 unsigned int offset, unsigned int len)
10744{
10745 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10746 struct hlua *flt_hlua;
10747 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10748 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10749 int ret;
10750
10751 flt_hlua = flt_ctx->hlua[idx];
10752 flt_ctx->cur_off[idx] = offset;
10753 flt_ctx->cur_len[idx] = len;
10754 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10755 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10756 if (ret != -1) {
10757 ret = flt_ctx->cur_len[idx];
10758 if (lua_gettop(flt_hlua->T) > 0) {
10759 ret = lua_tointeger(flt_hlua->T, -1);
10760 if (ret > flt_ctx->cur_len[idx])
10761 ret = flt_ctx->cur_len[idx];
10762 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10763 }
10764 }
10765 return ret;
10766}
10767
Christopher Faulet69c581a2021-05-31 08:54:04 +020010768static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10769 struct flt_conf *fconf, char **err, void *private)
10770{
10771 struct hlua_reg_filter *reg_flt = private;
10772 lua_State *L;
10773 struct hlua_flt_config *conf = NULL;
10774 const char *flt_id = NULL;
10775 int state_id, pos, flt_flags = 0;
10776 struct flt_ops *hlua_flt_ops = NULL;
10777
10778 state_id = reg_flt_to_stack_id(reg_flt);
10779 L = hlua_states[state_id];
10780
10781 /* Initialize the filter ops with default callbacks */
10782 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010783 if (!hlua_flt_ops)
10784 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010785 hlua_flt_ops->init = hlua_filter_init;
10786 hlua_flt_ops->deinit = hlua_filter_deinit;
10787 if (state_id) {
10788 /* Set per-thread callback if script is loaded per-thread */
10789 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10790 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10791 }
10792 hlua_flt_ops->attach = hlua_filter_new;
10793 hlua_flt_ops->detach = hlua_filter_delete;
10794
10795 /* Push the filter class on the stack and resolve all callbacks */
10796 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10797
Christopher Fauletc404f112020-02-26 15:03:09 +010010798 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10799 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10800 lua_pop(L, 1);
10801 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10802 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10803 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010804 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10805 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10806 lua_pop(L, 1);
10807 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10808 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10809 lua_pop(L, 1);
10810 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10811 hlua_flt_ops->http_end = hlua_filter_http_end;
10812 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010813 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10814 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10815 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010816
10817 /* Get id and flags of the filter class */
10818 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10819 flt_id = lua_tostring(L, -1);
10820 lua_pop(L, 1);
10821 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10822 flt_flags = lua_tointeger(L, -1);
10823 lua_pop(L, 1);
10824
10825 /* Create the filter config */
10826 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010827 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010828 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010829 conf->reg = reg_flt;
10830
10831 /* duplicate args */
10832 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10833 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010834 if (!conf->args)
10835 goto error;
10836 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010837 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010838 if (!conf->args[pos])
10839 goto error;
10840 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010841 conf->args[pos] = NULL;
10842 *cur_arg += pos + 1;
10843
Christopher Fauletc86bb872021-08-13 08:33:57 +020010844 if (flt_id) {
10845 fconf->id = strdup(flt_id);
10846 if (!fconf->id)
10847 goto error;
10848 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010849 fconf->flags = flt_flags;
10850 fconf->conf = conf;
10851 fconf->ops = hlua_flt_ops;
10852
10853 lua_settop(L, 0);
10854 return 0;
10855
10856 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010857 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010858 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010859 if (conf && conf->args) {
10860 for (pos = 0; conf->args[pos]; pos++)
10861 free(conf->args[pos]);
10862 free(conf->args);
10863 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010864 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010865 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010866 lua_settop(L, 0);
10867 return -1;
10868}
10869
Christopher Fauletc404f112020-02-26 15:03:09 +010010870__LJMP static int hlua_register_data_filter(lua_State *L)
10871{
10872 struct filter *filter;
10873 struct channel *chn;
10874
10875 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10876 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10877 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10878
10879 lua_getfield(L, 1, "__filter");
10880 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10881 filter = lua_touserdata (L, -1);
10882 lua_pop(L, 1);
10883
10884 register_data_filter(chn_strm(chn), chn, filter);
10885 return 1;
10886}
10887
10888__LJMP static int hlua_unregister_data_filter(lua_State *L)
10889{
10890 struct filter *filter;
10891 struct channel *chn;
10892
10893 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10894 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10895 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10896
10897 lua_getfield(L, 1, "__filter");
10898 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10899 filter = lua_touserdata (L, -1);
10900 lua_pop(L, 1);
10901
10902 unregister_data_filter(chn_strm(chn), chn, filter);
10903 return 1;
10904}
10905
Christopher Faulet69c581a2021-05-31 08:54:04 +020010906/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010907 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020010908 * parse configuration arguments.
10909 */
10910__LJMP static int hlua_register_filter(lua_State *L)
10911{
10912 struct buffer *trash;
10913 struct flt_kw_list *fkl;
10914 struct flt_kw *fkw;
10915 const char *name;
10916 struct hlua_reg_filter *reg_flt= NULL;
10917 int flt_ref, fun_ref;
10918 int len;
10919
10920 MAY_LJMP(check_args(L, 3, "register_filter"));
10921
10922 /* First argument : filter name. */
10923 name = MAY_LJMP(luaL_checkstring(L, 1));
10924
10925 /* Second argument : The filter class */
10926 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
10927
10928 /* Third argument : lua function. */
10929 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
10930
10931 trash = get_trash_chunk();
10932 chunk_printf(trash, "lua.%s", name);
10933 fkw = flt_find_kw(trash->area);
10934 if (fkw != NULL) {
10935 reg_flt = fkw->private;
10936 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
10937 ha_warning("Trying to register filter 'lua.%s' more than once. "
10938 "This will become a hard error in version 2.5.\n", name);
10939 }
10940 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10941 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10942 return 0;
10943 }
10944
10945 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
10946 if (!fkl)
10947 goto alloc_error;
10948 fkl->scope = "HLUA";
10949
10950 reg_flt = new_hlua_reg_filter(name);
10951 if (!reg_flt)
10952 goto alloc_error;
10953
10954 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10955 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10956
10957 /* The filter keyword */
10958 len = strlen("lua.") + strlen(name) + 1;
10959 fkl->kw[0].kw = calloc(1, len);
10960 if (!fkl->kw[0].kw)
10961 goto alloc_error;
10962
10963 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
10964
10965 fkl->kw[0].parse = hlua_filter_parse_fct;
10966 fkl->kw[0].private = reg_flt;
10967 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
10968
10969 /* Register this new filter */
10970 flt_register_keywords(fkl);
10971
10972 return 0;
10973
10974 alloc_error:
10975 release_hlua_reg_filter(reg_flt);
10976 ha_free(&fkl);
10977 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10978 return 0; /* Never reached */
10979}
10980
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010981static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010982 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010983 char **err, unsigned int *timeout)
10984{
10985 const char *error;
10986
10987 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020010988 if (error == PARSE_TIME_OVER) {
10989 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
10990 args[1], args[0]);
10991 return -1;
10992 }
10993 else if (error == PARSE_TIME_UNDER) {
10994 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
10995 args[1], args[0]);
10996 return -1;
10997 }
10998 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010999 memprintf(err, "%s: invalid timeout", args[0]);
11000 return -1;
11001 }
11002 return 0;
11003}
11004
11005static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011006 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011007 char **err)
11008{
11009 return hlua_read_timeout(args, section_type, curpx, defpx,
11010 file, line, err, &hlua_timeout_session);
11011}
11012
11013static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011014 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011015 char **err)
11016{
11017 return hlua_read_timeout(args, section_type, curpx, defpx,
11018 file, line, err, &hlua_timeout_task);
11019}
11020
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011021static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011022 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011023 char **err)
11024{
11025 return hlua_read_timeout(args, section_type, curpx, defpx,
11026 file, line, err, &hlua_timeout_applet);
11027}
11028
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011029static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011030 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011031 char **err)
11032{
11033 char *error;
11034
11035 hlua_nb_instruction = strtoll(args[1], &error, 10);
11036 if (*error != '\0') {
11037 memprintf(err, "%s: invalid number", args[0]);
11038 return -1;
11039 }
11040 return 0;
11041}
11042
Willy Tarreau32f61e22015-03-18 17:54:59 +010011043static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011044 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011045 char **err)
11046{
11047 char *error;
11048
11049 if (*(args[1]) == 0) {
11050 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11051 return -1;
11052 }
11053 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11054 if (*error != '\0') {
11055 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11056 return -1;
11057 }
11058 return 0;
11059}
11060
11061
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011062/* This function is called by the main configuration key "lua-load". It loads and
11063 * execute an lua file during the parsing of the HAProxy configuration file. It is
11064 * the main lua entry point.
11065 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011066 * This function runs with the HAProxy keywords API. It returns -1 if an error
11067 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011068 *
11069 * In some error case, LUA set an error message in top of the stack. This function
11070 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011071 *
11072 * This function can fail with an abort() due to an Lua critical error.
11073 * We are in the configuration parsing process of HAProxy, this abort() is
11074 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011075 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011076static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011077{
11078 int error;
11079
11080 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011081 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011082 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011083 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11084 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011085 return -1;
11086 }
11087
11088 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011089 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011090 switch (error) {
11091 case LUA_OK:
11092 break;
11093 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011094 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11095 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011096 return -1;
11097 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011098 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011099 return -1;
11100 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011101 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11102 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011103 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011104#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011105 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011106 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11107 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011108 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011109#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011110 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011111 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11112 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011113 return -1;
11114 }
11115
11116 return 0;
11117}
11118
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011119static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011120 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011121 char **err)
11122{
11123 if (*(args[1]) == 0) {
11124 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11125 return -1;
11126 }
11127
Thierry Fournier59f11be2020-11-29 00:37:41 +010011128 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011129 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011130 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011131 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011132}
11133
Thierry Fournier59f11be2020-11-29 00:37:41 +010011134static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011135 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011136 char **err)
11137{
11138 int len;
11139
11140 if (*(args[1]) == 0) {
11141 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11142 return -1;
11143 }
11144
11145 if (per_thread_load == NULL) {
11146 /* allocate the first entry large enough to store the final NULL */
11147 per_thread_load = calloc(1, sizeof(*per_thread_load));
11148 if (per_thread_load == NULL) {
11149 memprintf(err, "out of memory error");
11150 return -1;
11151 }
11152 }
11153
11154 /* count used entries */
11155 for (len = 0; per_thread_load[len] != NULL; len++)
11156 ;
11157
11158 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11159 if (per_thread_load == NULL) {
11160 memprintf(err, "out of memory error");
11161 return -1;
11162 }
11163
11164 per_thread_load[len] = strdup(args[1]);
11165 per_thread_load[len + 1] = NULL;
11166
11167 if (per_thread_load[len] == NULL) {
11168 memprintf(err, "out of memory error");
11169 return -1;
11170 }
11171
11172 /* loading for thread 1 only */
11173 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011174 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011175 return hlua_load_state(args[1], hlua_states[1], err);
11176}
11177
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011178/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11179 * in the given <ctx>.
11180 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011181static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011182{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011183 lua_getglobal(L, "package"); /* push package variable */
11184 lua_pushstring(L, path); /* push given path */
11185 lua_pushstring(L, ";"); /* push semicolon */
11186 lua_getfield(L, -3, type); /* push old path */
11187 lua_concat(L, 3); /* concatenate to new path */
11188 lua_setfield(L, -2, type); /* store new path */
11189 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011190
11191 return 0;
11192}
11193
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011194static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011195 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011196 char **err)
11197{
11198 char *path;
11199 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011200 struct prepend_path *p = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011201
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011202 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011203 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011204 }
11205
11206 if (!(*args[1])) {
11207 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011208 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011209 }
11210 path = args[1];
11211
11212 if (*args[2]) {
11213 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11214 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011215 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011216 }
11217 type = args[2];
11218 }
11219
Thierry Fournier59f11be2020-11-29 00:37:41 +010011220 p = calloc(1, sizeof(*p));
11221 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011222 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011223 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011224 }
11225 p->path = strdup(path);
11226 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011227 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011228 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011229 }
11230 p->type = strdup(type);
11231 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011232 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011233 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011234 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011235 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011236
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011237 /* Handle the global state and the per-thread state for the first
11238 * thread. The remaining threads will be initialized based on
11239 * prepend_path_list.
11240 */
11241 for (size_t i = 0; i < 2; i++) {
11242 lua_State *L = hlua_states[i];
11243 const char *error;
11244
11245 if (setjmp(safe_ljmp_env) != 0) {
11246 lua_atpanic(L, hlua_panic_safe);
11247 if (lua_type(L, -1) == LUA_TSTRING)
11248 error = lua_tostring(L, -1);
11249 else
11250 error = "critical error";
11251 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11252 exit(1);
11253 } else {
11254 lua_atpanic(L, hlua_panic_ljmp);
11255 }
11256
11257 hlua_prepend_path(L, type, path);
11258
11259 lua_atpanic(L, hlua_panic_safe);
11260 }
11261
Thierry Fournier59f11be2020-11-29 00:37:41 +010011262 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011263
11264err2:
11265 free(p->type);
11266 free(p->path);
11267err:
11268 free(p);
11269 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011270}
11271
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011272/* configuration keywords declaration */
11273static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011274 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011275 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011276 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011277 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11278 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011279 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011280 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011281 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011282 { 0, NULL, NULL },
11283}};
11284
Willy Tarreau0108d902018-11-25 19:14:37 +010011285INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11286
Christopher Fauletafd8f102018-11-08 11:34:21 +010011287
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011288/* This function can fail with an abort() due to an Lua critical error.
11289 * We are in the initialisation process of HAProxy, this abort() is
11290 * tolerated.
11291 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011292int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011293{
11294 struct hlua_init_function *init;
11295 const char *msg;
11296 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011297 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011298 const char *kind;
11299 const char *trace;
11300 int return_status = 1;
11301#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11302 int nres;
11303#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011304
Willy Tarreaucdb53462020-12-02 12:12:00 +010011305 /* disable memory limit checks if limit is not set */
11306 if (!hlua_global_allocator.limit)
11307 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11308
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011309 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011310 if (setjmp(safe_ljmp_env) != 0) {
11311 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011312 if (lua_type(L, -1) == LUA_TSTRING)
11313 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011314 else
11315 error = "critical error";
11316 fprintf(stderr, "Lua post-init: %s.\n", error);
11317 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011318 } else {
11319 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011320 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011321
Thierry Fournierb8cef172020-11-28 15:37:17 +010011322 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011323
Thierry Fournierc7492592020-11-28 23:57:24 +010011324 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011325 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011326
11327#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011328 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011329#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011330 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011331#endif
11332 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011333 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011334
11335 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011336 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011337 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011338
11339 case LUA_ERRERR:
11340 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011341 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011342 case LUA_ERRRUN:
11343 if (!kind)
11344 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011345 msg = lua_tostring(L, -1);
11346 lua_settop(L, 0); /* Empty the stack. */
11347 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011348 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011349 if (msg)
11350 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11351 else
11352 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11353 return_status = 0;
11354 break;
11355
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011356 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011357 /* Unknown error */
11358 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011359 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011360 case LUA_YIELD:
11361 /* yield is not configured at this step, this state doesn't happen */
11362 if (!kind)
11363 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011364 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011365 case LUA_ERRMEM:
11366 if (!kind)
11367 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011368 lua_settop(L, 0);
11369 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011370 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011371 ha_alert("Lua init: %s: %s\n", kind, trace);
11372 return_status = 0;
11373 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011374 }
Thierry Fournier670db242020-11-28 10:49:59 +010011375 if (!return_status)
11376 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011377 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011378
11379 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011380 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011381}
11382
Thierry Fournierb8cef172020-11-28 15:37:17 +010011383int hlua_post_init()
11384{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011385 int ret;
11386 int i;
11387 int errors;
11388 char *err = NULL;
11389 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011390 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011391
Willy Tarreaub1310492021-08-30 09:35:18 +020011392#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011393 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011394 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011395 int saved_used_backed = global.ssl_used_backend;
11396 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011397 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011398 global.ssl_used_backend = saved_used_backed;
11399 }
11400#endif
11401
Thierry Fournierc7492592020-11-28 23:57:24 +010011402 /* Perform post init of common thread */
11403 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011404 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011405 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11406 if (ret == 0)
11407 return 0;
11408
11409 /* init remaining lua states and load files */
11410 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11411
11412 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011413 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011414
11415 /* Init lua state */
11416 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11417
11418 /* Load lua files */
11419 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11420 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11421 if (ret != 0) {
11422 ha_alert("Lua init: %s\n", err);
11423 return 0;
11424 }
11425 }
11426 }
11427
11428 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011429 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011430
11431 /* Execute post init for all states */
11432 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11433
11434 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011435 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011436
11437 /* run post init */
11438 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11439 if (ret == 0)
11440 return 0;
11441 }
11442
11443 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011444 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011445
11446 /* control functions registering. Each function must have:
11447 * - only the function_ref[0] set positive and all other to -1
11448 * - only the function_ref[0] set to -1 and all other positive
11449 * This ensure a same reference is not used both in shared
11450 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011451 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011452 * complicated to found for the end user.
11453 */
11454 errors = 0;
11455 list_for_each_entry(fcn, &referenced_functions, l) {
11456 ret = 0;
11457 for (i = 1; i < global.nbthread + 1; i++) {
11458 if (fcn->function_ref[i] == -1)
11459 ret--;
11460 else
11461 ret++;
11462 }
11463 if (abs(ret) != global.nbthread) {
11464 ha_alert("Lua function '%s' is not referenced in all thread. "
11465 "Expect function in all thread or in none thread.\n", fcn->name);
11466 errors++;
11467 continue;
11468 }
11469
11470 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011471 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11472 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011473 "exclusive.\n", fcn->name);
11474 errors++;
11475 }
11476 }
11477
Christopher Faulet69c581a2021-05-31 08:54:04 +020011478 /* Do the same with registered filters */
11479 list_for_each_entry(reg_flt, &referenced_filters, l) {
11480 ret = 0;
11481 for (i = 1; i < global.nbthread + 1; i++) {
11482 if (reg_flt->flt_ref[i] == -1)
11483 ret--;
11484 else
11485 ret++;
11486 }
11487 if (abs(ret) != global.nbthread) {
11488 ha_alert("Lua filter '%s' is not referenced in all thread. "
11489 "Expect function in all thread or in none thread.\n", reg_flt->name);
11490 errors++;
11491 continue;
11492 }
11493
11494 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11495 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11496 "and per-thread Lua context (through lua-load-per-thread). these two context "
11497 "exclusive.\n", fcn->name);
11498 errors++;
11499 }
11500 }
11501
11502
Thierry Fournier59f11be2020-11-29 00:37:41 +010011503 if (errors > 0)
11504 return 0;
11505
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011506 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011507 * -1 in order to have probably a segfault if someone use it
11508 */
11509 hlua_state_id = -1;
11510
11511 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011512}
11513
Willy Tarreau32f61e22015-03-18 17:54:59 +010011514/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11515 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11516 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011517 * allocation. <nsize> is the requested new size. A new allocation is
11518 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011519 * zero. This one verifies that the limits are respected but is optimized
11520 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011521 *
11522 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11523 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11524 * that and will simply allocate zero as if it were the result of malloc(0),
11525 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11526 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011527 */
11528static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11529{
11530 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011531 size_t limit, old, new;
11532
Tim Duesterhus22586522021-01-08 10:35:33 +010011533 if (unlikely(!ptr && !nsize))
11534 return NULL;
11535
Willy Tarreaucdb53462020-12-02 12:12:00 +010011536 /* a limit of ~0 means unlimited and boot complete, so there's no need
11537 * for accounting anymore.
11538 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011539 if (likely(~zone->limit == 0)) {
11540 if (!nsize)
11541 ha_free(&ptr);
11542 else
11543 ptr = realloc(ptr, nsize);
11544 return ptr;
11545 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011546
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011547 if (!ptr)
11548 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011549
Willy Tarreaucdb53462020-12-02 12:12:00 +010011550 /* enforce strict limits across all threads */
11551 limit = zone->limit;
11552 old = _HA_ATOMIC_LOAD(&zone->allocated);
11553 do {
11554 new = old + nsize - osize;
11555 if (unlikely(nsize && limit && new > limit))
11556 return NULL;
11557 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011558
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011559 if (!nsize)
11560 ha_free(&ptr);
11561 else
11562 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011563
11564 if (unlikely(!ptr && nsize)) // failed
11565 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11566
11567 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011568 return ptr;
11569}
11570
Thierry Fournierecb83c22020-11-28 15:49:44 +010011571/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011572 * We are in the initialisation process of HAProxy, this abort() is
11573 * tolerated.
11574 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011575lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011576{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011577 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011578 int idx;
11579 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011580 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011581 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011582 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011583 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011584 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011585 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011586
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011587 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011588 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011589
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011590 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011591 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011592 *context = NULL;
11593
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011594 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011595 * the Lua function can fail with an abort. We are in the initialisation
11596 * process of HAProxy, this abort() is tolerated.
11597 */
11598
Thierry Fournier3c539322020-11-28 16:05:05 +010011599 /* Call post initialisation function in safe environment. */
11600 if (setjmp(safe_ljmp_env) != 0) {
11601 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011602 if (lua_type(L, -1) == LUA_TSTRING)
11603 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011604 else
11605 error_msg = "critical error";
11606 fprintf(stderr, "Lua init: %s.\n", error_msg);
11607 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011608 } else {
11609 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011610 }
11611
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011612 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011613 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011614#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11615#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11616#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011617 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011618#endif
11619#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011620 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011621#endif
11622#undef HLUA_PREPEND_PATH_TOSTRING
11623#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011624
Thierry Fournier59f11be2020-11-29 00:37:41 +010011625 /* Apply configured prepend path */
11626 list_for_each_entry(pp, &prepend_path_list, l)
11627 hlua_prepend_path(L, pp->type, pp->path);
11628
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011629 /*
11630 *
11631 * Create "core" object.
11632 *
11633 */
11634
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011635 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011636 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011637
Thierry Fournierecb83c22020-11-28 15:49:44 +010011638 /* set the thread id */
11639 hlua_class_const_int(L, "thread", thread_num);
11640
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011641 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011642 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011643 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011644
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011645 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011646 hlua_class_function(L, "register_init", hlua_register_init);
11647 hlua_class_function(L, "register_task", hlua_register_task);
11648 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11649 hlua_class_function(L, "register_converters", hlua_register_converters);
11650 hlua_class_function(L, "register_action", hlua_register_action);
11651 hlua_class_function(L, "register_service", hlua_register_service);
11652 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011653 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011654 hlua_class_function(L, "yield", hlua_yield);
11655 hlua_class_function(L, "set_nice", hlua_set_nice);
11656 hlua_class_function(L, "sleep", hlua_sleep);
11657 hlua_class_function(L, "msleep", hlua_msleep);
11658 hlua_class_function(L, "add_acl", hlua_add_acl);
11659 hlua_class_function(L, "del_acl", hlua_del_acl);
11660 hlua_class_function(L, "set_map", hlua_set_map);
11661 hlua_class_function(L, "del_map", hlua_del_map);
11662 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011663 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011664 hlua_class_function(L, "log", hlua_log);
11665 hlua_class_function(L, "Debug", hlua_log_debug);
11666 hlua_class_function(L, "Info", hlua_log_info);
11667 hlua_class_function(L, "Warning", hlua_log_warning);
11668 hlua_class_function(L, "Alert", hlua_log_alert);
11669 hlua_class_function(L, "done", hlua_done);
11670 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011671
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011672 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011673
11674 /*
11675 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011676 * Create "act" object.
11677 *
11678 */
11679
11680 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011681 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011682
11683 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011684 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11685 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11686 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11687 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11688 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11689 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11690 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11691 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011692
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011693 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011694
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011695 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011696
11697 /*
11698 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011699 * Create "Filter" object.
11700 *
11701 */
11702
11703 /* This table entry is the object "filter" base. */
11704 lua_newtable(L);
11705
11706 /* push flags and constants */
11707 hlua_class_const_int(L, "CONTINUE", 1);
11708 hlua_class_const_int(L, "WAIT", 0);
11709 hlua_class_const_int(L, "ERROR", -1);
11710
11711 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
11712
Christopher Fauletc404f112020-02-26 15:03:09 +010011713 hlua_class_function(L, "wake_time", hlua_set_wake_time);
11714 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
11715 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
11716
Christopher Faulet69c581a2021-05-31 08:54:04 +020011717 lua_setglobal(L, "filter");
11718
11719 /*
11720 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011721 * Register class Map
11722 *
11723 */
11724
11725 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011726 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011727
11728 /* register pattern types. */
11729 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011730 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011731 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011732 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011733 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011734 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011735
11736 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011737 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011738
11739 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011740 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011741
Ilya Shipitsind4259502020-04-08 01:07:56 +050011742 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011743 lua_pushstring(L, "__index");
11744 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011745
11746 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011747 hlua_class_function(L, "lookup", hlua_map_lookup);
11748 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011749
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011750 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011751
Thierry Fournier45e78d72016-02-19 18:34:46 +010011752 /* Register previous table in the registry with reference and named entry.
11753 * The function hlua_register_metatable() pops the stack, so we
11754 * previously create a copy of the table.
11755 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011756 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
11757 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011758
11759 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011760 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011761
11762 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011763 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011764
11765 /*
11766 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011767 * Register class Channel
11768 *
11769 */
11770
11771 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011772 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011773
Ilya Shipitsind4259502020-04-08 01:07:56 +050011774 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011775 lua_pushstring(L, "__index");
11776 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011777
11778 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011779 hlua_class_function(L, "data", hlua_channel_get_data);
11780 hlua_class_function(L, "line", hlua_channel_get_line);
11781 hlua_class_function(L, "set", hlua_channel_set_data);
11782 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011783 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011784 hlua_class_function(L, "prepend", hlua_channel_prepend);
11785 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011786 hlua_class_function(L, "send", hlua_channel_send);
11787 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011788 hlua_class_function(L, "input", hlua_channel_get_in_len);
11789 hlua_class_function(L, "output", hlua_channel_get_out_len);
11790 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011791 hlua_class_function(L, "is_full", hlua_channel_is_full);
11792 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011793
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011794 /* Deprecated API */
11795 hlua_class_function(L, "get", hlua_channel_get);
11796 hlua_class_function(L, "dup", hlua_channel_dup);
11797 hlua_class_function(L, "getline", hlua_channel_getline);
11798 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
11799 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
11800
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011801 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011802
11803 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011804 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011805
11806 /*
11807 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011808 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011809 *
11810 */
11811
11812 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011813 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011814
Ilya Shipitsind4259502020-04-08 01:07:56 +050011815 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011816 lua_pushstring(L, "__index");
11817 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011818
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011819 /* Browse existing fetches and create the associated
11820 * object method.
11821 */
11822 sf = NULL;
11823 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011824 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11825 * by an underscore.
11826 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011827 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011828 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011829 if (*p == '.' || *p == '-' || *p == '+')
11830 *p = '_';
11831
11832 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011833 lua_pushstring(L, trash.area);
11834 lua_pushlightuserdata(L, sf);
11835 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
11836 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011837 }
11838
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011839 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011840
11841 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011842 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011843
11844 /*
11845 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011846 * Register class Converters
11847 *
11848 */
11849
11850 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011851 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011852
11853 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011854 lua_pushstring(L, "__index");
11855 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011856
11857 /* Browse existing converters and create the associated
11858 * object method.
11859 */
11860 sc = NULL;
11861 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011862 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11863 * by an underscore.
11864 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011865 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011866 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011867 if (*p == '.' || *p == '-' || *p == '+')
11868 *p = '_';
11869
11870 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011871 lua_pushstring(L, trash.area);
11872 lua_pushlightuserdata(L, sc);
11873 lua_pushcclosure(L, hlua_run_sample_conv, 1);
11874 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011875 }
11876
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011877 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011878
11879 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011880 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011881
11882 /*
11883 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011884 * Register class HTTP
11885 *
11886 */
11887
11888 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011889 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011890
Ilya Shipitsind4259502020-04-08 01:07:56 +050011891 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011892 lua_pushstring(L, "__index");
11893 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011894
11895 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011896 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
11897 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
11898 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
11899 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
11900 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
11901 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
11902 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
11903 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
11904 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
11905 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011906
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011907 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
11908 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
11909 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
11910 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
11911 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
11912 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
11913 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011914
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011915 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011916
11917 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011918 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011919
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011920 /*
11921 *
11922 * Register class HTTPMessage
11923 *
11924 */
11925
11926 /* Create and fill the metatable. */
11927 lua_newtable(L);
11928
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011929 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011930 lua_pushstring(L, "__index");
11931 lua_newtable(L);
11932
11933 /* Register Lua functions. */
11934 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
11935 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
11936 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
11937 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
11938 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
11939 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
11940 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
11941 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
11942 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
11943 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
11944 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
11945 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
11946 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
11947 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
11948 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
11949 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
11950 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
11951 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
11952
11953 hlua_class_function(L, "body", hlua_http_msg_get_body);
11954 hlua_class_function(L, "set", hlua_http_msg_set_data);
11955 hlua_class_function(L, "remove", hlua_http_msg_del_data);
11956 hlua_class_function(L, "append", hlua_http_msg_append);
11957 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
11958 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
11959 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
11960 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
11961
11962 hlua_class_function(L, "send", hlua_http_msg_send);
11963 hlua_class_function(L, "forward", hlua_http_msg_forward);
11964
11965 lua_rawset(L, -3);
11966
11967 /* Register previous table in the registry with reference and named entry. */
11968 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020011969
11970 /*
11971 *
11972 * Register class HTTPClient
11973 *
11974 */
11975
11976 /* Create and fill the metatable. */
11977 lua_newtable(L);
11978 lua_pushstring(L, "__index");
11979 lua_newtable(L);
11980 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020011981 hlua_class_function(L, "head", hlua_httpclient_head);
11982 hlua_class_function(L, "put", hlua_httpclient_put);
11983 hlua_class_function(L, "post", hlua_httpclient_post);
11984 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020011985 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020011986 /* Register the garbage collector entry. */
11987 lua_pushstring(L, "__gc");
11988 lua_pushcclosure(L, hlua_httpclient_gc, 0);
11989 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
11990
William Lallemand3956c4e2021-09-21 16:25:15 +020011991
11992
11993 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011994 /*
11995 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011996 * Register class AppletTCP
11997 *
11998 */
11999
12000 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012001 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012002
Ilya Shipitsind4259502020-04-08 01:07:56 +050012003 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012004 lua_pushstring(L, "__index");
12005 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012006
12007 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012008 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12009 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12010 hlua_class_function(L, "send", hlua_applet_tcp_send);
12011 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12012 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12013 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12014 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12015 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012016
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012017 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012018
12019 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012020 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012021
12022 /*
12023 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012024 * Register class AppletHTTP
12025 *
12026 */
12027
12028 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012029 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012030
Ilya Shipitsind4259502020-04-08 01:07:56 +050012031 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012032 lua_pushstring(L, "__index");
12033 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012034
12035 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012036 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12037 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12038 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12039 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12040 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12041 hlua_class_function(L, "getline", hlua_applet_http_getline);
12042 hlua_class_function(L, "receive", hlua_applet_http_recv);
12043 hlua_class_function(L, "send", hlua_applet_http_send);
12044 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12045 hlua_class_function(L, "set_status", hlua_applet_http_status);
12046 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012047
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012048 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012049
12050 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012051 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012052
12053 /*
12054 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012055 * Register class TXN
12056 *
12057 */
12058
12059 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012060 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012061
Ilya Shipitsind4259502020-04-08 01:07:56 +050012062 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012063 lua_pushstring(L, "__index");
12064 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012065
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012066 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012067 hlua_class_function(L, "set_priv", hlua_set_priv);
12068 hlua_class_function(L, "get_priv", hlua_get_priv);
12069 hlua_class_function(L, "set_var", hlua_set_var);
12070 hlua_class_function(L, "unset_var", hlua_unset_var);
12071 hlua_class_function(L, "get_var", hlua_get_var);
12072 hlua_class_function(L, "done", hlua_txn_done);
12073 hlua_class_function(L, "reply", hlua_txn_reply_new);
12074 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12075 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12076 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12077 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12078 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12079 hlua_class_function(L, "deflog", hlua_txn_deflog);
12080 hlua_class_function(L, "log", hlua_txn_log);
12081 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12082 hlua_class_function(L, "Info", hlua_txn_log_info);
12083 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12084 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012085
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012086 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012087
12088 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012089 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012090
12091 /*
12092 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012093 * Register class reply
12094 *
12095 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012096 lua_newtable(L);
12097 lua_pushstring(L, "__index");
12098 lua_newtable(L);
12099 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12100 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12101 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12102 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12103 lua_settable(L, -3); /* Sets the __index entry. */
12104 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012105
12106
12107 /*
12108 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012109 * Register class Socket
12110 *
12111 */
12112
12113 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012114 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012115
Ilya Shipitsind4259502020-04-08 01:07:56 +050012116 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012117 lua_pushstring(L, "__index");
12118 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012119
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012120#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012121 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012122#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012123 hlua_class_function(L, "connect", hlua_socket_connect);
12124 hlua_class_function(L, "send", hlua_socket_send);
12125 hlua_class_function(L, "receive", hlua_socket_receive);
12126 hlua_class_function(L, "close", hlua_socket_close);
12127 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12128 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12129 hlua_class_function(L, "setoption", hlua_socket_setoption);
12130 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012131
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012132 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012133
12134 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012135 lua_pushstring(L, "__gc");
12136 lua_pushcclosure(L, hlua_socket_gc, 0);
12137 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012138
12139 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012140 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012141
Thierry Fournieraafc7772020-12-04 11:47:47 +010012142 lua_atpanic(L, hlua_panic_safe);
12143
12144 return L;
12145}
12146
12147void hlua_init(void) {
12148 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012149 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012150#ifdef USE_OPENSSL
12151 struct srv_kw *kw;
12152 int tmp_error;
12153 char *error;
12154 char *args[] = { /* SSL client configuration. */
12155 "ssl",
12156 "verify",
12157 "none",
12158 NULL
12159 };
12160#endif
12161
12162 /* Init post init function list head */
12163 for (i = 0; i < MAX_THREADS + 1; i++)
12164 LIST_INIT(&hlua_init_functions[i]);
12165
12166 /* Init state for common/shared lua parts */
12167 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012168 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012169 hlua_states[0] = hlua_init_state(0);
12170
12171 /* Init state 1 for thread 0. We have at least one thread. */
12172 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012173 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012174 hlua_states[1] = hlua_init_state(1);
12175
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012176 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012177 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012178 if (!socket_proxy) {
12179 fprintf(stderr, "Lua init: %s\n", errmsg);
12180 exit(1);
12181 }
12182 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012183
12184 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012185 socket_tcp = new_server(socket_proxy);
12186 if (!socket_tcp) {
12187 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12188 exit(1);
12189 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012190
12191#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012192 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012193 socket_ssl = new_server(socket_proxy);
12194 if (!socket_ssl) {
12195 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12196 exit(1);
12197 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012198
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012199 socket_ssl->use_ssl = 1;
12200 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012201
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012202 for (i = 0; args[i] != NULL; i++) {
12203 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012204 /*
12205 *
12206 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012207 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012208 * features like client certificates and ssl_verify.
12209 *
12210 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012211 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012212 if (tmp_error != 0) {
12213 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12214 abort(); /* This must be never arrives because the command line
12215 not editable by the user. */
12216 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012217 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012218 }
12219 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012220#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012221
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012222}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012223
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012224static void hlua_deinit()
12225{
Willy Tarreau186f3762020-12-04 11:48:12 +010012226 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012227 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12228
12229 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12230 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012231
12232 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12233 if (hlua_states[thr])
12234 lua_close(hlua_states[thr]);
12235 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012236
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012237 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012238
Willy Tarreau0f143af2021-03-05 10:41:48 +010012239#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012240 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012241#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012242
12243 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012244}
12245
12246REGISTER_POST_DEINIT(hlua_deinit);
12247
Willy Tarreau80713382018-11-26 10:19:54 +010012248static void hlua_register_build_options(void)
12249{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012250 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012251
Willy Tarreaubb57d942016-12-21 19:04:56 +010012252 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12253 hap_register_build_opts(ptr, 1);
12254}
Willy Tarreau80713382018-11-26 10:19:54 +010012255
12256INITCALL0(STG_REGISTER, hlua_register_build_options);