blob: 7eec25ce9e982b5e66650c44f2491dae9cbb1ca6 [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 Tarreau7ea393d2020-06-04 18:02:10 +020035#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020036#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020037#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020038#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020039#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020040#include <haproxy/http_ana.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020041#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020042#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020043#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020044#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020045#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020046#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020047#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020048#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020049#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020050#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020051#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010052#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020053#include <haproxy/session.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020054#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020055#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020056#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020057#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020058#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020059#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020060#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020061#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020062#include <haproxy/xref.h>
63
Thierry FOURNIER380d0932015-01-23 14:27:52 +010064
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010065/* Lua uses longjmp to perform yield or throwing errors. This
66 * macro is used only for identifying the function that can
67 * not return because a longjmp is executed.
68 * __LJMP marks a prototype of hlua file that can use longjmp.
69 * WILL_LJMP() marks an lua function that will use longjmp.
70 * MAY_LJMP() marks an lua function that may use longjmp.
71 */
72#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020073#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010074#define MAY_LJMP(func) func
75
Thierry FOURNIERbabae282015-09-17 11:36:37 +020076/* This couple of function executes securely some Lua calls outside of
77 * the lua runtime environment. Each Lua call can return a longjmp
78 * if it encounter a memory error.
79 *
80 * Lua documentation extract:
81 *
82 * If an error happens outside any protected environment, Lua calls
83 * a panic function (see lua_atpanic) and then calls abort, thus
84 * exiting the host application. Your panic function can avoid this
85 * exit by never returning (e.g., doing a long jump to your own
86 * recovery point outside Lua).
87 *
88 * The panic function runs as if it were a message handler (see
89 * §2.3); in particular, the error message is at the top of the
90 * stack. However, there is no guarantee about stack space. To push
91 * anything on the stack, the panic function must first check the
92 * available space (see §4.2).
93 *
94 * We must check all the Lua entry point. This includes:
95 * - The include/proto/hlua.h exported functions
96 * - the task wrapper function
97 * - The action wrapper function
98 * - The converters wrapper function
99 * - The sample-fetch wrapper functions
100 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500101 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800102 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200103 *
104 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
105 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
106 * because they must be exists in the program stack when the longjmp
107 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200108 *
109 * Note that the Lua processing is not really thread safe. It provides
110 * heavy system which consists to add our own lock function in the Lua
111 * code and recompile the library. This system will probably not accepted
112 * by maintainers of various distribs.
113 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500114 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200115 * quick looking on the Lua sources displays a lua_lock() a the start
116 * of function and a lua_unlock() at the end of the function. So I
117 * conclude that the Lua thread safe mode just perform a mutex around
118 * all execution. So I prefer to do this in the HAProxy code, it will be
119 * easier for distro maintainers.
120 *
121 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
122 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
123 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200124 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100125__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200126THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200127static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200128static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100130/* This is the chained list of struct hlua_function referenced
131 * for haproxy action, sample-fetches, converters, cli and
132 * applet bindings. It is used for a post-initialisation control.
133 */
134static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
135
Thierry Fournierc7492592020-11-28 23:57:24 +0100136/* This variable is used only during initialization to identify the Lua state
137 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
138 * states dedicated to each thread (in this case hlua_state_id==tid+1).
139 */
140static int hlua_state_id;
141
Thierry Fournier59f11be2020-11-29 00:37:41 +0100142/* This is a NULL-terminated list of lua file which are referenced to load per thread */
143static char **per_thread_load = NULL;
144
145lua_State *hlua_init_state(int thread_id);
146
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100147#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200148 ({ \
149 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100150 if ((__HLUA)->state_id == 0) \
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100151 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200152 if (setjmp(safe_ljmp_env) != 0) { \
153 lua_atpanic(__L, hlua_panic_safe); \
154 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100155 if ((__HLUA)->state_id == 0) \
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100156 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200157 } else { \
158 lua_atpanic(__L, hlua_panic_ljmp); \
159 ret = 1; \
160 } \
161 ret; \
162 })
163
164/* If we are the last function catching Lua errors, we
165 * must reset the panic function.
166 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100167#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200168 do { \
169 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100170 if ((__HLUA)->state_id == 0) \
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100171 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200172 } while(0)
173
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100174#define SET_SAFE_LJMP(__HLUA) \
175 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
176
177#define RESET_SAFE_LJMP(__HLUA) \
178 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
179
180#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100181 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100182
183#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100184 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200186/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200187#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100188/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200189#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200190/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100191#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100192#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200193
Thierry Fournierafc63e22020-11-28 17:06:51 +0100194/* The main Lua execution context. The 0 index is the
195 * common state shared by all threads.
196 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100197static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100198
Christopher Fauletc404f112020-02-26 15:03:09 +0100199#define HLUA_FLT_CB_FINAL 0x00000001
200#define HLUA_FLT_CB_RETVAL 0x00000002
201#define HLUA_FLT_CB_ARG_CHN 0x00000004
202#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
203
Christopher Faulet9f55a502020-02-25 15:21:02 +0100204#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
205
Christopher Faulet69c581a2021-05-31 08:54:04 +0200206struct hlua_reg_filter {
207 char *name;
208 int flt_ref[MAX_THREADS + 1];
209 int fun_ref[MAX_THREADS + 1];
210 struct list l;
211};
212
213struct hlua_flt_config {
214 struct hlua_reg_filter *reg;
215 int ref[MAX_THREADS + 1];
216 char **args;
217};
218
219struct hlua_flt_ctx {
220 int ref; /* ref to the filter lua object */
221 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
222 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
223 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
224 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
225};
226
227DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
228
Christopher Faulet9f55a502020-02-25 15:21:02 +0100229static int hlua_filter_from_payload(struct filter *filter);
230
Christopher Faulet69c581a2021-05-31 08:54:04 +0200231/* This is the chained list of struct hlua_flt referenced
232 * for haproxy filters. It is used for a post-initialisation control.
233 */
234static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
235
236
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100237/* This is the memory pool containing struct lua for applets
238 * (including cli).
239 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100240DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100241
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100242/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100243static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100244static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100245#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100246static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100247#endif
248
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100249/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100250struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100251
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100252/* The following variables contains the reference of the different
253 * Lua classes. These references are useful for identify metadata
254 * associated with an object.
255 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100256static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100257static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100258static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100259static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100260static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100261static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100262static int class_http_msg_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200263static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200264static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200265static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100266static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100267
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100268/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200269 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100270 * short timeout. Lua linked with tasks doesn't have a timeout
271 * because a task may remain alive during all the haproxy execution.
272 */
273static unsigned int hlua_timeout_session = 4000; /* session timeout. */
274static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200275static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100276
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100277/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
278 * it is used for preventing infinite loops.
279 *
280 * I test the scheer with an infinite loop containing one incrementation
281 * and one test. I run this loop between 10 seconds, I raise a ceil of
282 * 710M loops from one interrupt each 9000 instructions, so I fix the value
283 * to one interrupt each 10 000 instructions.
284 *
285 * configured | Number of
286 * instructions | loops executed
287 * between two | in milions
288 * forced yields |
289 * ---------------+---------------
290 * 10 | 160
291 * 500 | 670
292 * 1000 | 680
293 * 5000 | 700
294 * 7000 | 700
295 * 8000 | 700
296 * 9000 | 710 <- ceil
297 * 10000 | 710
298 * 100000 | 710
299 * 1000000 | 710
300 *
301 */
302static unsigned int hlua_nb_instruction = 10000;
303
Willy Tarreaucdb53462020-12-02 12:12:00 +0100304/* Descriptor for the memory allocation state. The limit is pre-initialised to
305 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
306 * is replaced with ~0 during post_init after everything was loaded. This way
307 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
308 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100309 */
310struct hlua_mem_allocator {
311 size_t allocated;
312 size_t limit;
313};
314
Willy Tarreaucdb53462020-12-02 12:12:00 +0100315static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100316
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100317/* These functions converts types between HAProxy internal args or
318 * sample and LUA types. Another function permits to check if the
319 * LUA stack contains arguments according with an required ARG_T
320 * format.
321 */
322static int hlua_arg2lua(lua_State *L, const struct arg *arg);
323static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100324__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100325 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100326static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100327static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100328static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
329
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100330__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200331
Thierry Fournier59f11be2020-11-29 00:37:41 +0100332struct prepend_path {
333 struct list l;
334 char *type;
335 char *path;
336};
337
338static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
339
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200340#define SEND_ERR(__be, __fmt, __args...) \
341 do { \
342 send_log(__be, LOG_ERR, __fmt, ## __args); \
343 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100344 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200345 } while (0)
346
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100347static inline struct hlua_function *new_hlua_function()
348{
349 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100350 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100351
352 fcn = calloc(1, sizeof(*fcn));
353 if (!fcn)
354 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200355 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100356 for (i = 0; i < MAX_THREADS + 1; i++)
357 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100358 return fcn;
359}
360
Christopher Fauletdda44442021-04-12 14:05:43 +0200361static inline void release_hlua_function(struct hlua_function *fcn)
362{
363 if (!fcn)
364 return;
365 if (fcn->name)
366 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200367 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200368 ha_free(&fcn);
369}
370
Thierry Fournierc7492592020-11-28 23:57:24 +0100371/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
372static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
373{
374 if (fcn->function_ref[0] == -1)
375 return tid + 1;
376 return 0;
377}
378
Christopher Faulet69c581a2021-05-31 08:54:04 +0200379/* Create a new registered filter. Only its name is filled */
380static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
381{
382 struct hlua_reg_filter *reg_flt;
383 int i;
384
385 reg_flt = calloc(1, sizeof(*reg_flt));
386 if (!reg_flt)
387 return NULL;
388 reg_flt->name = strdup(name);
389 if (!reg_flt->name) {
390 free(reg_flt);
391 return NULL;
392 }
393 LIST_APPEND(&referenced_filters, &reg_flt->l);
394 for (i = 0; i < MAX_THREADS + 1; i++) {
395 reg_flt->flt_ref[i] = -1;
396 reg_flt->fun_ref[i] = -1;
397 }
398 return reg_flt;
399}
400
401/* Release a registered filter */
402static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
403{
404 if (!reg_flt)
405 return;
406 if (reg_flt->name)
407 ha_free(&reg_flt->name);
408 LIST_DELETE(&reg_flt->l);
409 ha_free(&reg_flt);
410}
411
412/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
413static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
414{
415 if (reg_flt->fun_ref[0] == -1)
416 return tid + 1;
417 return 0;
418}
419
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100420/* Used to check an Lua function type in the stack. It creates and
421 * returns a reference of the function. This function throws an
422 * error if the rgument is not a "function".
423 */
424__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
425{
426 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100427 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100428 WILL_LJMP(luaL_argerror(L, argno, msg));
429 }
430 lua_pushvalue(L, argno);
431 return luaL_ref(L, LUA_REGISTRYINDEX);
432}
433
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100434/* Used to check an Lua table type in the stack. It creates and
435 * returns a reference of the table. This function throws an
436 * error if the rgument is not a "table".
437 */
438__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
439{
440 if (!lua_istable(L, argno)) {
441 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
442 WILL_LJMP(luaL_argerror(L, argno, msg));
443 }
444 lua_pushvalue(L, argno);
445 return luaL_ref(L, LUA_REGISTRYINDEX);
446}
447
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200448/* Return the string that is of the top of the stack. */
449const char *hlua_get_top_error_string(lua_State *L)
450{
451 if (lua_gettop(L) < 1)
452 return "unknown error";
453 if (lua_type(L, -1) != LUA_TSTRING)
454 return "unknown error";
455 return lua_tostring(L, -1);
456}
457
Christopher Fauletd09cc512021-03-24 14:48:45 +0100458__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200459{
460 lua_Debug ar;
461 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200462 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200463
464 while (lua_getstack(L, level++, &ar)) {
465
466 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100467 if (b_data(msg))
468 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200469
470 /* Fill fields:
471 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
472 * 'l': fills in the field currentline;
473 * 'n': fills in the field name and namewhat;
474 * 't': fills in the field istailcall;
475 */
476 lua_getinfo(L, "Slnt", &ar);
477
478 /* Append code localisation */
479 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100480 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200481 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100482 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200483
484 /*
485 * Get function name
486 *
487 * if namewhat is no empty, name is defined.
488 * what contains "Lua" for Lua function, "C" for C function,
489 * or "main" for main code.
490 */
491 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100492 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200493
494 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100495 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200496
497 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100498 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200499
500 else /* nothing left... */
501 chunk_appendf(msg, "?");
502
503
504 /* Display tailed call */
505 if (ar.istailcall)
506 chunk_appendf(msg, " ...");
507 }
508
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200509 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200510}
511
512
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100513/* This function check the number of arguments available in the
514 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500515 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100516 */
517__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
518{
519 if (lua_gettop(L) == nb)
520 return;
521 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
522}
523
Mark Lakes22154b42018-01-29 14:38:40 -0800524/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100525 * and the line number where the error is encountered.
526 */
527static int hlua_pusherror(lua_State *L, const char *fmt, ...)
528{
529 va_list argp;
530 va_start(argp, fmt);
531 luaL_where(L, 1);
532 lua_pushvfstring(L, fmt, argp);
533 va_end(argp);
534 lua_concat(L, 2);
535 return 1;
536}
537
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100538/* This functions is used with sample fetch and converters. It
539 * converts the HAProxy configuration argument in a lua stack
540 * values.
541 *
542 * It takes an array of "arg", and each entry of the array is
543 * converted and pushed in the LUA stack.
544 */
545static int hlua_arg2lua(lua_State *L, const struct arg *arg)
546{
547 switch (arg->type) {
548 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100549 case ARGT_TIME:
550 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100551 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100552 break;
553
554 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200555 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100556 break;
557
558 case ARGT_IPV4:
559 case ARGT_IPV6:
560 case ARGT_MSK4:
561 case ARGT_MSK6:
562 case ARGT_FE:
563 case ARGT_BE:
564 case ARGT_TAB:
565 case ARGT_SRV:
566 case ARGT_USR:
567 case ARGT_MAP:
568 default:
569 lua_pushnil(L);
570 break;
571 }
572 return 1;
573}
574
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500575/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100576 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500577 * with sample fetch wrappers. The input arguments are given to the
578 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100579 */
580static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
581{
582 switch (lua_type(L, ud)) {
583
584 case LUA_TNUMBER:
585 case LUA_TBOOLEAN:
586 arg->type = ARGT_SINT;
587 arg->data.sint = lua_tointeger(L, ud);
588 break;
589
590 case LUA_TSTRING:
591 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200592 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200593 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200594 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200595 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100596 break;
597
598 case LUA_TUSERDATA:
599 case LUA_TNIL:
600 case LUA_TTABLE:
601 case LUA_TFUNCTION:
602 case LUA_TTHREAD:
603 case LUA_TLIGHTUSERDATA:
604 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200605 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100606 break;
607 }
608 return 1;
609}
610
611/* the following functions are used to convert a struct sample
612 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500613 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100614 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100615static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100616{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200617 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100618 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100619 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200620 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100621 break;
622
623 case SMP_T_BIN:
624 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200625 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100626 break;
627
628 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200629 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100630 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
631 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
632 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
633 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
634 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
635 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
636 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
637 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
638 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200639 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100640 break;
641 default:
642 lua_pushnil(L);
643 break;
644 }
645 break;
646
647 case SMP_T_IPV4:
648 case SMP_T_IPV6:
649 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200650 if (sample_casts[smp->data.type][SMP_T_STR] &&
651 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200652 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100653 else
654 lua_pushnil(L);
655 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100656 default:
657 lua_pushnil(L);
658 break;
659 }
660 return 1;
661}
662
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100663/* the following functions are used to convert a struct sample
664 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500665 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100666 */
667static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
668{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200669 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100670
671 case SMP_T_BIN:
672 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200673 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100674 break;
675
676 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200677 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100678 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
679 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
680 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
681 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
682 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
683 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
684 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
685 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
686 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200687 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100688 break;
689 default:
690 lua_pushstring(L, "");
691 break;
692 }
693 break;
694
695 case SMP_T_SINT:
696 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100697 case SMP_T_IPV4:
698 case SMP_T_IPV6:
699 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200700 if (sample_casts[smp->data.type][SMP_T_STR] &&
701 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200702 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100703 else
704 lua_pushstring(L, "");
705 break;
706 default:
707 lua_pushstring(L, "");
708 break;
709 }
710 return 1;
711}
712
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100713/* the following functions are used to convert an Lua type in a
714 * struct sample. This is useful to provide data from a converter
715 * to the LUA code.
716 */
717static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
718{
719 switch (lua_type(L, ud)) {
720
721 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200722 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200723 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100724 break;
725
726
727 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200728 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200729 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100730 break;
731
732 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200733 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100734 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200735 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200736 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200737 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200738 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100739 break;
740
741 case LUA_TUSERDATA:
742 case LUA_TNIL:
743 case LUA_TTABLE:
744 case LUA_TFUNCTION:
745 case LUA_TTHREAD:
746 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200747 case LUA_TNONE:
748 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200749 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200750 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100751 break;
752 }
753 return 1;
754}
755
Ilya Shipitsind4259502020-04-08 01:07:56 +0500756/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800757 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100758 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100759 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500760 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200761 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100762 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100763__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100764 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100765{
766 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200767 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100768 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200769 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200770 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200771 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200772 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100773
774 idx = 0;
775 min_arg = ARGM(mask);
776 mask >>= ARGM_BITS;
777
778 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200779 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100781 /* Check for mandatory arguments. */
782 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100783 if (idx < min_arg) {
784
785 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200786 if (idx > 0) {
787 msg = "Mandatory argument expected";
788 goto error;
789 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100790
791 /* If first argument have a certain type, some default values
792 * may be used. See the function smp_resolve_args().
793 */
794 switch (mask & ARGT_MASK) {
795
796 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200797 if (!(p->cap & PR_CAP_FE)) {
798 msg = "Mandatory argument expected";
799 goto error;
800 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100801 argp[idx].data.prx = p;
802 argp[idx].type = ARGT_FE;
803 argp[idx+1].type = ARGT_STOP;
804 break;
805
806 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200807 if (!(p->cap & PR_CAP_BE)) {
808 msg = "Mandatory argument expected";
809 goto error;
810 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100811 argp[idx].data.prx = p;
812 argp[idx].type = ARGT_BE;
813 argp[idx+1].type = ARGT_STOP;
814 break;
815
816 case ARGT_TAB:
817 argp[idx].data.prx = p;
818 argp[idx].type = ARGT_TAB;
819 argp[idx+1].type = ARGT_STOP;
820 break;
821
822 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200823 msg = "Mandatory argument expected";
824 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100825 break;
826 }
827 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200828 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100829 }
830
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500831 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100832 if ((mask & ARGT_MASK) == ARGT_STOP &&
833 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200834 msg = "Last argument expected";
835 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100836 }
837
838 if ((mask & ARGT_MASK) == ARGT_STOP &&
839 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200840 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100841 }
842
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200843 /* Convert some argument types. All string in argp[] are for not
844 * duplicated yet.
845 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100846 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100847 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200848 if (argp[idx].type != ARGT_SINT) {
849 msg = "integer expected";
850 goto error;
851 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100852 argp[idx].type = ARGT_SINT;
853 break;
854
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100855 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200856 if (argp[idx].type != ARGT_SINT) {
857 msg = "integer expected";
858 goto error;
859 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200860 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100861 break;
862
863 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200864 if (argp[idx].type != ARGT_SINT) {
865 msg = "integer expected";
866 goto error;
867 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200868 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100869 break;
870
871 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200872 if (argp[idx].type != ARGT_STR) {
873 msg = "string expected";
874 goto error;
875 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200876 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200877 if (!argp[idx].data.prx) {
878 msg = "frontend doesn't exist";
879 goto error;
880 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100881 argp[idx].type = ARGT_FE;
882 break;
883
884 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200885 if (argp[idx].type != ARGT_STR) {
886 msg = "string expected";
887 goto error;
888 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200889 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200890 if (!argp[idx].data.prx) {
891 msg = "backend doesn't exist";
892 goto error;
893 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100894 argp[idx].type = ARGT_BE;
895 break;
896
897 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200898 if (argp[idx].type != ARGT_STR) {
899 msg = "string expected";
900 goto error;
901 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200902 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200903 if (!argp[idx].data.t) {
904 msg = "table doesn't exist";
905 goto error;
906 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100907 argp[idx].type = ARGT_TAB;
908 break;
909
910 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200911 if (argp[idx].type != ARGT_STR) {
912 msg = "string expected";
913 goto error;
914 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200915 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100916 if (sname) {
917 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200918 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200919 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200920 if (!px) {
921 msg = "backend doesn't exist";
922 goto error;
923 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100924 }
925 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200926 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100927 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100928 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100929 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200930 if (!argp[idx].data.srv) {
931 msg = "server doesn't exist";
932 goto error;
933 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100934 argp[idx].type = ARGT_SRV;
935 break;
936
937 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200938 if (argp[idx].type != ARGT_STR) {
939 msg = "string expected";
940 goto error;
941 }
942 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
943 msg = "invalid IPv4 address";
944 goto error;
945 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100946 argp[idx].type = ARGT_IPV4;
947 break;
948
949 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200950 if (argp[idx].type == ARGT_SINT)
951 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
952 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200953 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
954 msg = "invalid IPv4 mask";
955 goto error;
956 }
957 }
958 else {
959 msg = "integer or string expected";
960 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200961 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100962 argp[idx].type = ARGT_MSK4;
963 break;
964
965 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200966 if (argp[idx].type != ARGT_STR) {
967 msg = "string expected";
968 goto error;
969 }
970 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
971 msg = "invalid IPv6 address";
972 goto error;
973 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100974 argp[idx].type = ARGT_IPV6;
975 break;
976
977 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200978 if (argp[idx].type == ARGT_SINT)
979 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
980 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200981 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
982 msg = "invalid IPv6 mask";
983 goto error;
984 }
985 }
986 else {
987 msg = "integer or string expected";
988 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200989 }
Tim Duesterhusb814da62018-01-25 16:24:50 +0100990 argp[idx].type = ARGT_MSK6;
991 break;
992
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200993 case ARGT_REG:
994 if (argp[idx].type != ARGT_STR) {
995 msg = "string expected";
996 goto error;
997 }
998 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
999 if (!reg) {
1000 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1001 argp[idx].data.str.area, err);
1002 free(err);
1003 goto error;
1004 }
1005 argp[idx].type = ARGT_REG;
1006 argp[idx].data.reg = reg;
1007 break;
1008
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001009 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001010 if (argp[idx].type != ARGT_STR) {
1011 msg = "string expected";
1012 goto error;
1013 }
1014 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001015 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001016 ul = p->uri_auth->userlist;
1017 else
1018 ul = auth_find_userlist(argp[idx].data.str.area);
1019
1020 if (!ul) {
1021 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1022 goto error;
1023 }
1024 argp[idx].type = ARGT_USR;
1025 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001026 break;
1027
1028 case ARGT_STR:
1029 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1030 msg = "unable to duplicate string arg";
1031 goto error;
1032 }
1033 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001034 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001035
Christopher Fauletd25d9262020-08-06 11:04:46 +02001036 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001037 msg = "type not yet supported";
1038 goto error;
1039 break;
1040
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001041 }
1042
1043 /* Check for type of argument. */
1044 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001045 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1046 arg_type_names[(mask & ARGT_MASK)],
1047 arg_type_names[argp[idx].type & ARGT_MASK]);
1048 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001049 }
1050
1051 /* Next argument. */
1052 mask >>= ARGT_BITS;
1053 idx++;
1054 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001055 return 0;
1056
1057 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001058 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001059 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1060 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001061}
1062
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001063/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001064 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001065 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001066 *
1067 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001068 * - hlua_sethlua : create the association between hlua context and lua_state.
1069 */
1070static inline struct hlua *hlua_gethlua(lua_State *L)
1071{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001072 struct hlua **hlua = lua_getextraspace(L);
1073 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001074}
1075static inline void hlua_sethlua(struct hlua *hlua)
1076{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001077 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1078 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001079}
1080
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001081/* This function is used to send logs. It try to send on screen (stderr)
1082 * and on the default syslog server.
1083 */
1084static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1085{
1086 struct tm tm;
1087 char *p;
1088
1089 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001090 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001091 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001092 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001093 /* Break the message if exceed the buffer size. */
1094 *(p-4) = ' ';
1095 *(p-3) = '.';
1096 *(p-2) = '.';
1097 *(p-1) = '.';
1098 break;
1099 }
Willy Tarreau90807112020-02-25 08:16:33 +01001100 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001101 *p = *msg;
1102 else
1103 *p = '.';
1104 }
1105 *p = '\0';
1106
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001107 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001108 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001109 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1110 return;
1111
Willy Tarreaua678b432015-08-28 10:14:59 +02001112 get_localtime(date.tv_sec, &tm);
1113 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001114 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001115 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001116 fflush(stderr);
1117 }
1118}
1119
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001120/* This function just ensure that the yield will be always
1121 * returned with a timeout and permit to set some flags
1122 */
1123__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001124 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001125{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001126 struct hlua *hlua;
1127
1128 /* Get hlua struct, or NULL if we execute from main lua state */
1129 hlua = hlua_gethlua(L);
1130 if (!hlua) {
1131 return;
1132 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001133
1134 /* Set the wake timeout. If timeout is required, we set
1135 * the expiration time.
1136 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001137 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001138
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001139 hlua->flags |= flags;
1140
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001141 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001142 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001143}
1144
Willy Tarreau87b09662015-04-03 00:22:06 +02001145/* This function initialises the Lua environment stored in the stream.
1146 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001147 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001148 *
1149 * This function is particular. it initialises a new Lua thread. If the
1150 * initialisation fails (example: out of memory error), the lua function
1151 * throws an error (longjmp).
1152 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001153 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001154 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001155 * threads appear, the safe environment set a lock to ensure only one
1156 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001157 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001158 *
1159 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001160 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001161 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001162 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001163 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001164 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001165 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001166 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001167int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001168{
1169 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001170 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001171 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001172 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001173 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001174 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001175 if (!already_safe) {
1176 if (!SET_SAFE_LJMP_PARENT(lua)) {
1177 lua->Tref = LUA_REFNIL;
1178 return 0;
1179 }
1180 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001181 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001182 if (!lua->T) {
1183 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001184 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001185 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001186 return 0;
1187 }
1188 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001189 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001190 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001191 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001192 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001193 return 1;
1194}
1195
Willy Tarreau87b09662015-04-03 00:22:06 +02001196/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001197 * is destroyed. The destroy also the memory context. The struct "lua"
1198 * is not freed.
1199 */
1200void hlua_ctx_destroy(struct hlua *lua)
1201{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001202 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001203 return;
1204
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001205 if (!lua->T)
1206 goto end;
1207
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001208 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001209 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001210
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001211 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001212 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001213 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001214 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001215
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001216 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001217 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001218 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001219 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001220 /* Forces a garbage collecting process. If the Lua program is finished
1221 * without error, we run the GC on the thread pointer. Its freed all
1222 * the unused memory.
1223 * If the thread is finnish with an error or is currently yielded,
1224 * it seems that the GC applied on the thread doesn't clean anything,
1225 * so e run the GC on the main thread.
1226 * NOTE: maybe this action locks all the Lua threads untiml the en of
1227 * the garbage collection.
1228 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001229 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001230 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001231 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001232 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001233 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001234 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001235
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001236 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001237
1238end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001239 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001240}
1241
1242/* This function is used to restore the Lua context when a coroutine
1243 * fails. This function copy the common memory between old coroutine
1244 * and the new coroutine. The old coroutine is destroyed, and its
1245 * replaced by the new coroutine.
1246 * If the flag "keep_msg" is set, the last entry of the old is assumed
1247 * as string error message and it is copied in the new stack.
1248 */
1249static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1250{
1251 lua_State *T;
1252 int new_ref;
1253
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001254 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001255 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001256 if (!T)
1257 return 0;
1258
1259 /* Copy last error message. */
1260 if (keep_msg)
1261 lua_xmove(lua->T, T, 1);
1262
1263 /* Copy data between the coroutines. */
1264 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1265 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001266 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001267
1268 /* Destroy old data. */
1269 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1270
1271 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001272 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001273
1274 /* Fill the struct with the new coroutine values. */
1275 lua->Mref = new_ref;
1276 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001277 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001278
1279 /* Set context. */
1280 hlua_sethlua(lua);
1281
1282 return 1;
1283}
1284
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001285void hlua_hook(lua_State *L, lua_Debug *ar)
1286{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001287 struct hlua *hlua;
1288
1289 /* Get hlua struct, or NULL if we execute from main lua state */
1290 hlua = hlua_gethlua(L);
1291 if (!hlua)
1292 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001293
1294 /* Lua cannot yield when its returning from a function,
1295 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001296 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001297 */
1298 if (lua_gethookmask(L) & LUA_MASKRET) {
1299 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1300 return;
1301 }
1302
1303 /* restore the interrupt condition. */
1304 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1305
1306 /* If we interrupt the Lua processing in yieldable state, we yield.
1307 * If the state is not yieldable, trying yield causes an error.
1308 */
1309 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001310 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001311
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001312 /* If we cannot yield, update the clock and check the timeout. */
1313 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001314 hlua->run_time += now_ms - hlua->start_time;
1315 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001316 lua_pushfstring(L, "execution timeout");
1317 WILL_LJMP(lua_error(L));
1318 }
1319
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001320 /* Update the start time. */
1321 hlua->start_time = now_ms;
1322
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001323 /* Try to interrupt the process at the end of the current
1324 * unyieldable function.
1325 */
1326 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001327}
1328
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001329/* This function start or resumes the Lua stack execution. If the flag
1330 * "yield_allowed" if no set and the LUA stack execution returns a yield
1331 * The function return an error.
1332 *
1333 * The function can returns 4 values:
1334 * - HLUA_E_OK : The execution is terminated without any errors.
1335 * - HLUA_E_AGAIN : The execution must continue at the next associated
1336 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001337 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001338 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001339 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001340 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001341 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001342 * LUA code.
1343 */
1344static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1345{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001346#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1347 int nres;
1348#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001349 int ret;
1350 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001351 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001352
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001353 /* Initialise run time counter. */
1354 if (!HLUA_IS_RUNNING(lua))
1355 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001356
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001357 /* Lock the whole Lua execution. This lock must be before the
1358 * label "resume_execution".
1359 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001360 if (lua->state_id == 0)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001361 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001362
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001363resume_execution:
1364
1365 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1366 * instructions. it is used for preventing infinite loops.
1367 */
1368 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1369
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001370 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001371 HLUA_SET_RUN(lua);
1372 HLUA_CLR_CTRLYIELD(lua);
1373 HLUA_CLR_WAKERESWR(lua);
1374 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001375 HLUA_CLR_NOYIELD(lua);
1376 if (!yield_allowed)
1377 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001378
Christopher Fauletbc275a92020-02-26 14:55:16 +01001379 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001380 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001381 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001382
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001383 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001384#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001385 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001386#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001387 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001388#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001389 switch (ret) {
1390
1391 case LUA_OK:
1392 ret = HLUA_E_OK;
1393 break;
1394
1395 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001396 /* Check if the execution timeout is expired. It it is the case, we
1397 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001398 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001399 tv_update_date(0, 1);
1400 lua->run_time += now_ms - lua->start_time;
1401 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001402 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001403 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001404 break;
1405 }
1406 /* Process the forced yield. if the general yield is not allowed or
1407 * if no task were associated this the current Lua execution
1408 * coroutine, we resume the execution. Else we want to return in the
1409 * scheduler and we want to be waked up again, to continue the
1410 * current Lua execution. So we schedule our own task.
1411 */
1412 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001413 if (!yield_allowed || !lua->task)
1414 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001415 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001416 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001417 if (!yield_allowed) {
1418 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001419 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001420 break;
1421 }
1422 ret = HLUA_E_AGAIN;
1423 break;
1424
1425 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001426
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001427 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001428 * because the errors ares the only one mean to return immediately
1429 * from and lua execution.
1430 */
1431 if (lua->flags & HLUA_EXIT) {
1432 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001433 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001434 break;
1435 }
1436
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001437 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001438 if (!lua_checkstack(lua->T, 1)) {
1439 ret = HLUA_E_ERR;
1440 break;
1441 }
1442 msg = lua_tostring(lua->T, -1);
1443 lua_settop(lua->T, 0); /* Empty the stack. */
1444 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001445 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001446 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001447 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001448 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001449 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001450 ret = HLUA_E_ERRMSG;
1451 break;
1452
1453 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001454 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001455 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001456 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001457 break;
1458
1459 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001460 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001461 if (!lua_checkstack(lua->T, 1)) {
1462 ret = HLUA_E_ERR;
1463 break;
1464 }
1465 msg = lua_tostring(lua->T, -1);
1466 lua_settop(lua->T, 0); /* Empty the stack. */
1467 lua_pop(lua->T, 1);
1468 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001469 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001470 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001471 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001472 ret = HLUA_E_ERRMSG;
1473 break;
1474
1475 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001476 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001477 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001478 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001479 break;
1480 }
1481
1482 switch (ret) {
1483 case HLUA_E_AGAIN:
1484 break;
1485
1486 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001487 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001488 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001489 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001490 break;
1491
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001492 case HLUA_E_ETMOUT:
1493 case HLUA_E_NOMEM:
1494 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001495 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001496 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001497 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001498 hlua_ctx_renew(lua, 0);
1499 break;
1500
1501 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001502 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001503 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001504 break;
1505 }
1506
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001507 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001508 if (lua->state_id == 0)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001509 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001510
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001511 return ret;
1512}
1513
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001514/* This function exit the current code. */
1515__LJMP static int hlua_done(lua_State *L)
1516{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001517 struct hlua *hlua;
1518
1519 /* Get hlua struct, or NULL if we execute from main lua state */
1520 hlua = hlua_gethlua(L);
1521 if (!hlua)
1522 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001523
1524 hlua->flags |= HLUA_EXIT;
1525 WILL_LJMP(lua_error(L));
1526
1527 return 0;
1528}
1529
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001530/* This function is an LUA binding. It provides a function
1531 * for deleting ACL from a referenced ACL file.
1532 */
1533__LJMP static int hlua_del_acl(lua_State *L)
1534{
1535 const char *name;
1536 const char *key;
1537 struct pat_ref *ref;
1538
1539 MAY_LJMP(check_args(L, 2, "del_acl"));
1540
1541 name = MAY_LJMP(luaL_checkstring(L, 1));
1542 key = MAY_LJMP(luaL_checkstring(L, 2));
1543
1544 ref = pat_ref_lookup(name);
1545 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001546 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001547
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001548 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001549 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001550 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001551 return 0;
1552}
1553
1554/* This function is an LUA binding. It provides a function
1555 * for deleting map entry from a referenced map file.
1556 */
1557static int hlua_del_map(lua_State *L)
1558{
1559 const char *name;
1560 const char *key;
1561 struct pat_ref *ref;
1562
1563 MAY_LJMP(check_args(L, 2, "del_map"));
1564
1565 name = MAY_LJMP(luaL_checkstring(L, 1));
1566 key = MAY_LJMP(luaL_checkstring(L, 2));
1567
1568 ref = pat_ref_lookup(name);
1569 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001570 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001571
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001572 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001573 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001574 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001575 return 0;
1576}
1577
1578/* This function is an LUA binding. It provides a function
1579 * for adding ACL pattern from a referenced ACL file.
1580 */
1581static int hlua_add_acl(lua_State *L)
1582{
1583 const char *name;
1584 const char *key;
1585 struct pat_ref *ref;
1586
1587 MAY_LJMP(check_args(L, 2, "add_acl"));
1588
1589 name = MAY_LJMP(luaL_checkstring(L, 1));
1590 key = MAY_LJMP(luaL_checkstring(L, 2));
1591
1592 ref = pat_ref_lookup(name);
1593 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001594 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001595
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001596 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001597 if (pat_ref_find_elt(ref, key) == NULL)
1598 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001599 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001600 return 0;
1601}
1602
1603/* This function is an LUA binding. It provides a function
1604 * for setting map pattern and sample from a referenced map
1605 * file.
1606 */
1607static int hlua_set_map(lua_State *L)
1608{
1609 const char *name;
1610 const char *key;
1611 const char *value;
1612 struct pat_ref *ref;
1613
1614 MAY_LJMP(check_args(L, 3, "set_map"));
1615
1616 name = MAY_LJMP(luaL_checkstring(L, 1));
1617 key = MAY_LJMP(luaL_checkstring(L, 2));
1618 value = MAY_LJMP(luaL_checkstring(L, 3));
1619
1620 ref = pat_ref_lookup(name);
1621 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001622 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001623
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001624 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001625 if (pat_ref_find_elt(ref, key) != NULL)
1626 pat_ref_set(ref, key, value, NULL);
1627 else
1628 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001629 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001630 return 0;
1631}
1632
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001633/* A class is a lot of memory that contain data. This data can be a table,
1634 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001635 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001636 * the name of the object (_G[<name>] = <metable> ).
1637 *
1638 * A metable is a table that modify the standard behavior of a standard
1639 * access to the associated data. The entries of this new metatable are
1640 * defined as is:
1641 *
1642 * http://lua-users.org/wiki/MetatableEvents
1643 *
1644 * __index
1645 *
1646 * we access an absent field in a table, the result is nil. This is
1647 * true, but it is not the whole truth. Actually, such access triggers
1648 * the interpreter to look for an __index metamethod: If there is no
1649 * such method, as usually happens, then the access results in nil;
1650 * otherwise, the metamethod will provide the result.
1651 *
1652 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1653 * the key does not appear in the table, but the metatable has an __index
1654 * property:
1655 *
1656 * - if the value is a function, the function is called, passing in the
1657 * table and the key; the return value of that function is returned as
1658 * the result.
1659 *
1660 * - if the value is another table, the value of the key in that table is
1661 * asked for and returned (and if it doesn't exist in that table, but that
1662 * table's metatable has an __index property, then it continues on up)
1663 *
1664 * - Use "rawget(myTable,key)" to skip this metamethod.
1665 *
1666 * http://www.lua.org/pil/13.4.1.html
1667 *
1668 * __newindex
1669 *
1670 * Like __index, but control property assignment.
1671 *
1672 * __mode - Control weak references. A string value with one or both
1673 * of the characters 'k' and 'v' which specifies that the the
1674 * keys and/or values in the table are weak references.
1675 *
1676 * __call - Treat a table like a function. When a table is followed by
1677 * parenthesis such as "myTable( 'foo' )" and the metatable has
1678 * a __call key pointing to a function, that function is invoked
1679 * (passing any specified arguments) and the return value is
1680 * returned.
1681 *
1682 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1683 * called, if the metatable for myTable has a __metatable
1684 * key, the value of that key is returned instead of the
1685 * actual metatable.
1686 *
1687 * __tostring - Control string representation. When the builtin
1688 * "tostring( myTable )" function is called, if the metatable
1689 * for myTable has a __tostring property set to a function,
1690 * that function is invoked (passing myTable to it) and the
1691 * return value is used as the string representation.
1692 *
1693 * __len - Control table length. When the table length is requested using
1694 * the length operator ( '#' ), if the metatable for myTable has
1695 * a __len key pointing to a function, that function is invoked
1696 * (passing myTable to it) and the return value used as the value
1697 * of "#myTable".
1698 *
1699 * __gc - Userdata finalizer code. When userdata is set to be garbage
1700 * collected, if the metatable has a __gc field pointing to a
1701 * function, that function is first invoked, passing the userdata
1702 * to it. The __gc metamethod is not called for tables.
1703 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1704 *
1705 * Special metamethods for redefining standard operators:
1706 * http://www.lua.org/pil/13.1.html
1707 *
1708 * __add "+"
1709 * __sub "-"
1710 * __mul "*"
1711 * __div "/"
1712 * __unm "!"
1713 * __pow "^"
1714 * __concat ".."
1715 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001716 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001717 * http://www.lua.org/pil/13.2.html
1718 *
1719 * __eq "=="
1720 * __lt "<"
1721 * __le "<="
1722 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001723
1724/*
1725 *
1726 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001727 * Class Map
1728 *
1729 *
1730 */
1731
1732/* Returns a struct hlua_map if the stack entry "ud" is
1733 * a class session, otherwise it throws an error.
1734 */
1735__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1736{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001737 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001738}
1739
1740/* This function is the map constructor. It don't need
1741 * the class Map object. It creates and return a new Map
1742 * object. It must be called only during "body" or "init"
1743 * context because it process some filesystem accesses.
1744 */
1745__LJMP static int hlua_map_new(struct lua_State *L)
1746{
1747 const char *fn;
1748 int match = PAT_MATCH_STR;
1749 struct sample_conv conv;
1750 const char *file = "";
1751 int line = 0;
1752 lua_Debug ar;
1753 char *err = NULL;
1754 struct arg args[2];
1755
1756 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1757 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1758
1759 fn = MAY_LJMP(luaL_checkstring(L, 1));
1760
1761 if (lua_gettop(L) >= 2) {
1762 match = MAY_LJMP(luaL_checkinteger(L, 2));
1763 if (match < 0 || match >= PAT_MATCH_NUM)
1764 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1765 }
1766
1767 /* Get Lua filename and line number. */
1768 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1769 lua_getinfo(L, "Sl", &ar); /* get info about it */
1770 if (ar.currentline > 0) { /* is there info? */
1771 file = ar.short_src;
1772 line = ar.currentline;
1773 }
1774 }
1775
1776 /* fill fake sample_conv struct. */
1777 conv.kw = ""; /* unused. */
1778 conv.process = NULL; /* unused. */
1779 conv.arg_mask = 0; /* unused. */
1780 conv.val_args = NULL; /* unused. */
1781 conv.out_type = SMP_T_STR;
1782 conv.private = (void *)(long)match;
1783 switch (match) {
1784 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1785 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1786 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1787 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1788 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1789 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1790 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001791 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001792 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1793 default:
1794 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1795 }
1796
1797 /* fill fake args. */
1798 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001799 args[0].data.str.area = strdup(fn);
1800 args[0].data.str.data = strlen(fn);
1801 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001802 args[1].type = ARGT_STOP;
1803
1804 /* load the map. */
1805 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001806 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001807 * free the err variable.
1808 */
1809 luaL_where(L, 1);
1810 lua_pushfstring(L, "'new': %s.", err);
1811 lua_concat(L, 2);
1812 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001813 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001814 WILL_LJMP(lua_error(L));
1815 }
1816
1817 /* create the lua object. */
1818 lua_newtable(L);
1819 lua_pushlightuserdata(L, args[0].data.map);
1820 lua_rawseti(L, -2, 0);
1821
1822 /* Pop a class Map metatable and affect it to the userdata. */
1823 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1824 lua_setmetatable(L, -2);
1825
1826
1827 return 1;
1828}
1829
1830__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1831{
1832 struct map_descriptor *desc;
1833 struct pattern *pat;
1834 struct sample smp;
1835
1836 MAY_LJMP(check_args(L, 2, "lookup"));
1837 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001838 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001839 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001840 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001841 }
1842 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001843 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001844 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001845 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 +01001846 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001847 }
1848
1849 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001850 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001851 if (str)
1852 lua_pushstring(L, "");
1853 else
1854 lua_pushnil(L);
1855 return 1;
1856 }
1857
1858 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001859 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001860 return 1;
1861}
1862
1863__LJMP static int hlua_map_lookup(struct lua_State *L)
1864{
1865 return _hlua_map_lookup(L, 0);
1866}
1867
1868__LJMP static int hlua_map_slookup(struct lua_State *L)
1869{
1870 return _hlua_map_lookup(L, 1);
1871}
1872
1873/*
1874 *
1875 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001876 * Class Socket
1877 *
1878 *
1879 */
1880
1881__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1882{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001883 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001884}
1885
1886/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001887 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001888 * received.
1889 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001890static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001891{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001892 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001893
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001894 if (appctx->ctx.hlua_cosocket.die) {
1895 si_shutw(si);
1896 si_shutr(si);
1897 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001898 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1899 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001900 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1901 }
1902
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001903 /* If we can't write, wakeup the pending write signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001904 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001905 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001906
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001907 /* If we can't read, wakeup the pending read signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001908 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001909 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001910
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001911 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001912 * to be notified whenever the connection completes.
1913 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001914 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001915 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001916 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001917 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001918 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001919 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001920
1921 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001922 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001923
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001924 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001925 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001926 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001927
1928 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001929 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001930 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001931
1932 /* Some data were injected in the buffer, notify the stream
1933 * interface.
1934 */
1935 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001936 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001937
1938 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001939 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001940 */
1941 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001942 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001943}
1944
Willy Tarreau87b09662015-04-03 00:22:06 +02001945/* This function is called when the "struct stream" is destroyed.
1946 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947 * Wake all the pending signals.
1948 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001949static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001950{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001951 struct xref *peer;
1952
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001953 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001954 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1955 if (peer)
1956 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957
1958 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001959 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1960 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001961}
1962
1963/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001964 * uses this object. If the stream does not exists, just quit.
1965 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001966 * pending signal can rest in the read and write lists. destroy
1967 * it.
1968 */
1969__LJMP static int hlua_socket_gc(lua_State *L)
1970{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001971 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001972 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001973 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001975 MAY_LJMP(check_args(L, 1, "__gc"));
1976
1977 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001978 peer = xref_get_peer_and_lock(&socket->xref);
1979 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001980 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001981 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001982
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001983 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001984 appctx->ctx.hlua_cosocket.die = 1;
1985 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001986
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001987 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001988 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001989 return 0;
1990}
1991
1992/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001993 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001994 */
sada05ed3302018-05-11 11:48:18 -07001995__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001996{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001997 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001999 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002000 struct hlua *hlua;
2001
2002 /* Get hlua struct, or NULL if we execute from main lua state */
2003 hlua = hlua_gethlua(L);
2004 if (!hlua)
2005 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002006
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002007 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002008
2009 /* Check if we run on the same thread than the xreator thread.
2010 * We cannot access to the socket if the thread is different.
2011 */
2012 if (socket->tid != tid)
2013 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2014
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002015 peer = xref_get_peer_and_lock(&socket->xref);
2016 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002017 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002018
2019 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002020 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002021
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002022 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002023 appctx->ctx.hlua_cosocket.die = 1;
2024 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002025
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002026 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002027 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002028 return 0;
2029}
2030
sada05ed3302018-05-11 11:48:18 -07002031/* The close function calls close_helper.
2032 */
2033__LJMP static int hlua_socket_close(lua_State *L)
2034{
2035 MAY_LJMP(check_args(L, 1, "close"));
2036 return hlua_socket_close_helper(L);
2037}
2038
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002039/* This Lua function assumes that the stack contain three parameters.
2040 * 1 - USERDATA containing a struct socket
2041 * 2 - INTEGER with values of the macro defined below
2042 * If the integer is -1, we must read at most one line.
2043 * If the integer is -2, we ust read all the data until the
2044 * end of the stream.
2045 * If the integer is positive value, we must read a number of
2046 * bytes corresponding to this value.
2047 */
2048#define HLSR_READ_LINE (-1)
2049#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002050__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051{
2052 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2053 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002054 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002055 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002056 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002057 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002058 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002059 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002060 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002061 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002062 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002063 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002064 struct stream_interface *si;
2065 struct stream *s;
2066 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002067 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002068
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002069 /* Get hlua struct, or NULL if we execute from main lua state */
2070 hlua = hlua_gethlua(L);
2071
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072 /* Check if this lua stack is schedulable. */
2073 if (!hlua || !hlua->task)
2074 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2075 "'frontend', 'backend' or 'task'"));
2076
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002077 /* Check if we run on the same thread than the xreator thread.
2078 * We cannot access to the socket if the thread is different.
2079 */
2080 if (socket->tid != tid)
2081 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2082
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002083 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002084 peer = xref_get_peer_and_lock(&socket->xref);
2085 if (!peer)
2086 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002087 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2088 si = appctx->owner;
2089 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002091 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002092 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002093 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002094 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 if (nblk < 0) /* Connection close. */
2096 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002097 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002098 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002099
2100 /* remove final \r\n. */
2101 if (nblk == 1) {
2102 if (blk1[len1-1] == '\n') {
2103 len1--;
2104 skip_at_end++;
2105 if (blk1[len1-1] == '\r') {
2106 len1--;
2107 skip_at_end++;
2108 }
2109 }
2110 }
2111 else {
2112 if (blk2[len2-1] == '\n') {
2113 len2--;
2114 skip_at_end++;
2115 if (blk2[len2-1] == '\r') {
2116 len2--;
2117 skip_at_end++;
2118 }
2119 }
2120 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002121 }
2122
2123 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002124 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002125 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126 if (nblk < 0) /* Connection close. */
2127 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002128 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002129 goto connection_empty;
2130 }
2131
2132 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002133 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002134 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002135 if (nblk < 0) /* Connection close. */
2136 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002137 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002138 goto connection_empty;
2139
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002140 missing_bytes = wanted - socket->b.n;
2141 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002143 len1 = missing_bytes;
2144 } if (nblk == 2 && len1 + len2 > missing_bytes)
2145 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146 }
2147
2148 len = len1;
2149
2150 luaL_addlstring(&socket->b, blk1, len1);
2151 if (nblk == 2) {
2152 len += len2;
2153 luaL_addlstring(&socket->b, blk2, len2);
2154 }
2155
2156 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002157 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158
2159 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002160 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161
2162 /* If the pattern reclaim to read all the data
2163 * in the connection, got out.
2164 */
2165 if (wanted == HLSR_READ_ALL)
2166 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002167 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002168 goto connection_empty;
2169
2170 /* Return result. */
2171 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002172 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173 return 1;
2174
2175connection_closed:
2176
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002177 xref_unlock(&socket->xref, peer);
2178
2179no_peer:
2180
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181 /* If the buffer containds data. */
2182 if (socket->b.n > 0) {
2183 luaL_pushresult(&socket->b);
2184 return 1;
2185 }
2186 lua_pushnil(L);
2187 lua_pushstring(L, "connection closed.");
2188 return 2;
2189
2190connection_empty:
2191
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002192 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
2193 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002195 }
2196 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002197 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002198 return 0;
2199}
2200
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002201/* This Lua function gets two parameters. The first one can be string
2202 * or a number. If the string is "*l", the user requires one line. If
2203 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204 * If the value is a number, the user require a number of bytes equal
2205 * to the value. The default value is "*l" (a line).
2206 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002207 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208 * integer takes this values:
2209 * -1 : read a line
2210 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002211 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002213 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214 * concatenated with the read data.
2215 */
2216__LJMP static int hlua_socket_receive(struct lua_State *L)
2217{
2218 int wanted = HLSR_READ_LINE;
2219 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002220 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221 char *error;
2222 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002223 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224
2225 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2226 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2227
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002228 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002230 /* Check if we run on the same thread than the xreator thread.
2231 * We cannot access to the socket if the thread is different.
2232 */
2233 if (socket->tid != tid)
2234 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2235
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236 /* check for pattern. */
2237 if (lua_gettop(L) >= 2) {
2238 type = lua_type(L, 2);
2239 if (type == LUA_TSTRING) {
2240 pattern = lua_tostring(L, 2);
2241 if (strcmp(pattern, "*a") == 0)
2242 wanted = HLSR_READ_ALL;
2243 else if (strcmp(pattern, "*l") == 0)
2244 wanted = HLSR_READ_LINE;
2245 else {
2246 wanted = strtoll(pattern, &error, 10);
2247 if (*error != '\0')
2248 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2249 }
2250 }
2251 else if (type == LUA_TNUMBER) {
2252 wanted = lua_tointeger(L, 2);
2253 if (wanted < 0)
2254 WILL_LJMP(luaL_error(L, "Unsupported size."));
2255 }
2256 }
2257
2258 /* Set pattern. */
2259 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002260
2261 /* Check if we would replace the top by itself. */
2262 if (lua_gettop(L) != 2)
2263 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002264
Christopher Fauletc31b2002021-05-03 10:11:13 +02002265 /* Save index of the top of the stack because since buffers are used, it
2266 * may change
2267 */
2268 lastarg = lua_gettop(L);
2269
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002270 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 luaL_buffinit(L, &socket->b);
2272
2273 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002274 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 if (lua_type(L, 3) != LUA_TSTRING)
2276 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2277 pattern = lua_tolstring(L, 3, &len);
2278 luaL_addlstring(&socket->b, pattern, len);
2279 }
2280
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002281 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282}
2283
2284/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002285 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002287static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288{
2289 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002290 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291 struct appctx *appctx;
2292 size_t buf_len;
2293 const char *buf;
2294 int len;
2295 int send_len;
2296 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002297 struct xref *peer;
2298 struct stream_interface *si;
2299 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002301 /* Get hlua struct, or NULL if we execute from main lua state */
2302 hlua = hlua_gethlua(L);
2303
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304 /* Check if this lua stack is schedulable. */
2305 if (!hlua || !hlua->task)
2306 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2307 "'frontend', 'backend' or 'task'"));
2308
2309 /* Get object */
2310 socket = MAY_LJMP(hlua_checksocket(L, 1));
2311 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002312 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002314 /* Check if we run on the same thread than the xreator thread.
2315 * We cannot access to the socket if the thread is different.
2316 */
2317 if (socket->tid != tid)
2318 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2319
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002320 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002321 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002322 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002323 lua_pushinteger(L, -1);
2324 return 1;
2325 }
2326 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2327 si = appctx->owner;
2328 s = si_strm(si);
2329
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002331 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002332 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333 lua_pushinteger(L, -1);
2334 return 1;
2335 }
2336
2337 /* Update the input buffer data. */
2338 buf += sent;
2339 send_len = buf_len - sent;
2340
2341 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002342 if (sent >= buf_len) {
2343 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002344 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002345 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002347 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002348 * the request buffer if its not required.
2349 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002350 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002351 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002352 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002353 }
2354
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002355 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002356 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002357 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002359 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002360
2361 /* send data */
2362 if (len < send_len)
2363 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002364 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
2366 /* "Not enough space" (-1), "Buffer too little to contain
2367 * the data" (-2) are not expected because the available length
2368 * is tested.
2369 * Other unknown error are also not expected.
2370 */
2371 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002372 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002373 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002374
sada05ed3302018-05-11 11:48:18 -07002375 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002377 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002378 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002379 return 1;
2380 }
2381
2382 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002383 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002384
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002385 s->req.rex = TICK_ETERNITY;
2386 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002387
2388 /* Update length sent. */
2389 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002390 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002391
2392 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002393 if (sent + len >= buf_len) {
2394 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002396 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002397
2398hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002399 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2400 xref_unlock(&socket->xref, peer);
2401 WILL_LJMP(luaL_error(L, "out of memory"));
2402 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002403 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002404 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002405 return 0;
2406}
2407
2408/* This function initiate the send of data. It just check the input
2409 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002410 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002411 * "hlua_socket_write_yield" that can yield.
2412 *
2413 * The Lua function gets between 3 and 4 parameters. The first one is
2414 * the associated object. The second is a string buffer. The third is
2415 * a facultative integer that represents where is the buffer position
2416 * of the start of the data that can send. The first byte is the
2417 * position "1". The default value is "1". The fourth argument is a
2418 * facultative integer that represents where is the buffer position
2419 * of the end of the data that can send. The default is the last byte.
2420 */
2421static int hlua_socket_send(struct lua_State *L)
2422{
2423 int i;
2424 int j;
2425 const char *buf;
2426 size_t buf_len;
2427
2428 /* Check number of arguments. */
2429 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2430 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2431
2432 /* Get the string. */
2433 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2434
2435 /* Get and check j. */
2436 if (lua_gettop(L) == 4) {
2437 j = MAY_LJMP(luaL_checkinteger(L, 4));
2438 if (j < 0)
2439 j = buf_len + j + 1;
2440 if (j > buf_len)
2441 j = buf_len + 1;
2442 lua_pop(L, 1);
2443 }
2444 else
2445 j = buf_len;
2446
2447 /* Get and check i. */
2448 if (lua_gettop(L) == 3) {
2449 i = MAY_LJMP(luaL_checkinteger(L, 3));
2450 if (i < 0)
2451 i = buf_len + i + 1;
2452 if (i > buf_len)
2453 i = buf_len + 1;
2454 lua_pop(L, 1);
2455 } else
2456 i = 1;
2457
2458 /* Check bth i and j. */
2459 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002460 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002461 return 1;
2462 }
2463 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002464 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465 return 1;
2466 }
2467 if (i == 0)
2468 i = 1;
2469 if (j == 0)
2470 j = 1;
2471
2472 /* Pop the string. */
2473 lua_pop(L, 1);
2474
2475 /* Update the buffer length. */
2476 buf += i - 1;
2477 buf_len = j - i + 1;
2478 lua_pushlstring(L, buf, buf_len);
2479
2480 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002481 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002482
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002483 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002484}
2485
Willy Tarreau22b0a682015-06-17 19:43:49 +02002486#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002487__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2488{
2489 static char buffer[SOCKET_INFO_MAX_LEN];
2490 int ret;
2491 int len;
2492 char *p;
2493
2494 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2495 if (ret <= 0) {
2496 lua_pushnil(L);
2497 return 1;
2498 }
2499
2500 if (ret == AF_UNIX) {
2501 lua_pushstring(L, buffer+1);
2502 return 1;
2503 }
2504 else if (ret == AF_INET6) {
2505 buffer[0] = '[';
2506 len = strlen(buffer);
2507 buffer[len] = ']';
2508 len++;
2509 buffer[len] = ':';
2510 len++;
2511 p = buffer;
2512 }
2513 else if (ret == AF_INET) {
2514 p = buffer + 1;
2515 len = strlen(p);
2516 p[len] = ':';
2517 len++;
2518 }
2519 else {
2520 lua_pushnil(L);
2521 return 1;
2522 }
2523
2524 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2525 lua_pushnil(L);
2526 return 1;
2527 }
2528
2529 lua_pushstring(L, p);
2530 return 1;
2531}
2532
2533/* Returns information about the peer of the connection. */
2534__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2535{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002536 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002537 struct xref *peer;
2538 struct appctx *appctx;
2539 struct stream_interface *si;
2540 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002541 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002542
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002543 MAY_LJMP(check_args(L, 1, "getpeername"));
2544
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002545 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002546
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002547 /* Check if we run on the same thread than the xreator thread.
2548 * We cannot access to the socket if the thread is different.
2549 */
2550 if (socket->tid != tid)
2551 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2552
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002553 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002554 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002555 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002556 lua_pushnil(L);
2557 return 1;
2558 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002559 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2560 si = appctx->owner;
2561 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002562
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002563 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002564 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002565 lua_pushnil(L);
2566 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002567 }
2568
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002569 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002570 xref_unlock(&socket->xref, peer);
2571 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002572}
2573
2574/* Returns information about my connection side. */
2575static int hlua_socket_getsockname(struct lua_State *L)
2576{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002577 struct hlua_socket *socket;
2578 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002579 struct appctx *appctx;
2580 struct xref *peer;
2581 struct stream_interface *si;
2582 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002583 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002584
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585 MAY_LJMP(check_args(L, 1, "getsockname"));
2586
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002587 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002588
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002589 /* Check if we run on the same thread than the xreator thread.
2590 * We cannot access to the socket if the thread is different.
2591 */
2592 if (socket->tid != tid)
2593 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2594
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002595 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002596 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002597 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002598 lua_pushnil(L);
2599 return 1;
2600 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002601 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2602 si = appctx->owner;
2603 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002604
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002605 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002606 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002607 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002608 lua_pushnil(L);
2609 return 1;
2610 }
2611
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002612 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002613 xref_unlock(&socket->xref, peer);
2614 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002615}
2616
2617/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002618static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002619 .obj_type = OBJ_TYPE_APPLET,
2620 .name = "<LUA_TCP>",
2621 .fct = hlua_socket_handler,
2622 .release = hlua_socket_release,
2623};
2624
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002625__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002626{
2627 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002628 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002629 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002630 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002631 struct stream_interface *si;
2632 struct stream *s;
2633
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002634 /* Get hlua struct, or NULL if we execute from main lua state */
2635 hlua = hlua_gethlua(L);
2636 if (!hlua)
2637 return 0;
2638
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002639 /* Check if we run on the same thread than the xreator thread.
2640 * We cannot access to the socket if the thread is different.
2641 */
2642 if (socket->tid != tid)
2643 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2644
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002645 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002646 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002647 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002648 lua_pushnil(L);
2649 lua_pushstring(L, "Can't connect");
2650 return 2;
2651 }
2652 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2653 si = appctx->owner;
2654 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002655
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002656 /* Check if we run on the same thread than the xreator thread.
2657 * We cannot access to the socket if the thread is different.
2658 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002659 if (socket->tid != tid) {
2660 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002661 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002662 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002663
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002664 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002665 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002666 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002667 lua_pushnil(L);
2668 lua_pushstring(L, "Can't connect");
2669 return 2;
2670 }
2671
Willy Tarreaue09101e2018-10-16 17:37:12 +02002672 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002673
2674 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002675 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002676 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677 lua_pushinteger(L, 1);
2678 return 1;
2679 }
2680
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002681 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2682 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002683 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002684 }
2685 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002686 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002687 return 0;
2688}
2689
2690/* This function fail or initite the connection. */
2691__LJMP static int hlua_socket_connect(struct lua_State *L)
2692{
2693 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002694 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002695 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002696 struct hlua *hlua;
2697 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002698 int low, high;
2699 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002700 struct xref *peer;
2701 struct stream_interface *si;
2702 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002703
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002704 if (lua_gettop(L) < 2)
2705 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002706
2707 /* Get args. */
2708 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002709
2710 /* Check if we run on the same thread than the xreator thread.
2711 * We cannot access to the socket if the thread is different.
2712 */
2713 if (socket->tid != tid)
2714 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2715
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002716 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002717 if (lua_gettop(L) >= 3) {
2718 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002719 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002720
Tim Duesterhus6edab862018-01-06 19:04:45 +01002721 /* Force the ip to end with a colon, to support IPv6 addresses
2722 * that are not enclosed within square brackets.
2723 */
2724 if (port > 0) {
2725 luaL_buffinit(L, &b);
2726 luaL_addstring(&b, ip);
2727 luaL_addchar(&b, ':');
2728 luaL_pushresult(&b);
2729 ip = lua_tolstring(L, lua_gettop(L), NULL);
2730 }
2731 }
2732
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002733 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002734 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002735 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002736 lua_pushnil(L);
2737 return 1;
2738 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002739
2740 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002741 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 +02002742 if (!addr) {
2743 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002744 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002745 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002746
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002747 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002748 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002749 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002750 if (port == -1) {
2751 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002752 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002753 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002754 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2755 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002756 if (port == -1) {
2757 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002758 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002759 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002760 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002761 }
2762 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002763
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002764 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2765 si = appctx->owner;
2766 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002767
Willy Tarreau9b7587a2020-10-15 07:32:10 +02002768 if (!sockaddr_alloc(&s->target_addr, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002769 xref_unlock(&socket->xref, peer);
2770 WILL_LJMP(luaL_error(L, "connect: internal error"));
2771 }
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002772 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002773
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002774 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002775 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002776 if (!hlua)
2777 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002778
2779 /* inform the stream that we want to be notified whenever the
2780 * connection completes.
2781 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002782 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002783 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002784 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002785
Willy Tarreauf31af932020-01-14 09:59:38 +01002786 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002787
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002788 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2789 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002790 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002791 }
2792 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002793
2794 task_wakeup(s->task, TASK_WOKEN_INIT);
2795 /* Return yield waiting for connection. */
2796
Willy Tarreau9635e032018-10-16 17:52:55 +02002797 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002798
2799 return 0;
2800}
2801
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002802#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002803__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2804{
2805 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002806 struct xref *peer;
2807 struct appctx *appctx;
2808 struct stream_interface *si;
2809 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002810
2811 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2812 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002813
2814 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002815 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002816 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002817 lua_pushnil(L);
2818 return 1;
2819 }
2820 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2821 si = appctx->owner;
2822 s = si_strm(si);
2823
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002824 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002825 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002826 return MAY_LJMP(hlua_socket_connect(L));
2827}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002828#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002829
2830__LJMP static int hlua_socket_setoption(struct lua_State *L)
2831{
2832 return 0;
2833}
2834
2835__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2836{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002837 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002838 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002839 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002840 struct xref *peer;
2841 struct appctx *appctx;
2842 struct stream_interface *si;
2843 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002844
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002845 MAY_LJMP(check_args(L, 2, "settimeout"));
2846
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002847 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002848
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002849 /* convert the timeout to millis */
2850 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002851
Thierry Fournier17a921b2018-03-08 09:59:02 +01002852 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002853 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002854 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2855
Mark Lakes56cc1252018-03-27 09:48:06 +02002856 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002857 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002858
2859 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002860 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002861 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002862
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002863 /* Check if we run on the same thread than the xreator thread.
2864 * We cannot access to the socket if the thread is different.
2865 */
2866 if (socket->tid != tid)
2867 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2868
Mark Lakes56cc1252018-03-27 09:48:06 +02002869 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002870 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002871 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002872 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2873 WILL_LJMP(lua_error(L));
2874 return 0;
2875 }
2876 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2877 si = appctx->owner;
2878 s = si_strm(si);
2879
Cyril Bonté7bb63452018-08-17 23:51:02 +02002880 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002881 s->req.rto = tmout;
2882 s->req.wto = tmout;
2883 s->res.rto = tmout;
2884 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002885 s->req.rex = tick_add_ifset(now_ms, tmout);
2886 s->req.wex = tick_add_ifset(now_ms, tmout);
2887 s->res.rex = tick_add_ifset(now_ms, tmout);
2888 s->res.wex = tick_add_ifset(now_ms, tmout);
2889
2890 s->task->expire = tick_add_ifset(now_ms, tmout);
2891 task_queue(s->task);
2892
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002893 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002894
Thierry Fourniere9636f12018-03-08 09:54:32 +01002895 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002896 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002897}
2898
2899__LJMP static int hlua_socket_new(lua_State *L)
2900{
2901 struct hlua_socket *socket;
2902 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002903 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002904 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002905
2906 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002907 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002908 hlua_pusherror(L, "socket: full stack");
2909 goto out_fail_conf;
2910 }
2911
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002912 /* Create the object: obj[0] = userdata. */
2913 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002914 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002915 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002916 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002917 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002918
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002919 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002920 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002921 hlua_pusherror(L, "socket: uninitialized pools.");
2922 goto out_fail_conf;
2923 }
2924
Willy Tarreau87b09662015-04-03 00:22:06 +02002925 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002926 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2927 lua_setmetatable(L, -2);
2928
Willy Tarreaud420a972015-04-06 00:39:18 +02002929 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002930 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002931 if (!appctx) {
2932 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002933 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002934 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002935
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002936 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002937 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002938 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2939 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002940
Willy Tarreaud420a972015-04-06 00:39:18 +02002941 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002942 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002943 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002944 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002945 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002946 }
2947
Christopher Faulet26256f82020-09-14 11:40:13 +02002948 strm = stream_new(sess, &appctx->obj_type, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002949 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002950 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002951 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002952 }
2953
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002954 /* Initialise cross reference between stream and Lua socket object. */
2955 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002956
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002957 /* Configure "right" stream interface. this "si" is used to connect
2958 * and retrieve data from the server. The connection is initialized
2959 * with the "struct server".
2960 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002961 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002962
2963 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002964 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002965 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002966
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002967 return 1;
2968
Willy Tarreaud420a972015-04-06 00:39:18 +02002969 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002970 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002971 out_fail_sess:
2972 appctx_free(appctx);
2973 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002974 WILL_LJMP(lua_error(L));
2975 return 0;
2976}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002977
2978/*
2979 *
2980 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002981 * Class Channel
2982 *
2983 *
2984 */
2985
2986/* Returns the struct hlua_channel join to the class channel in the
2987 * stack entry "ud" or throws an argument error.
2988 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002989__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002990{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002991 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002992}
2993
Willy Tarreau47860ed2015-03-10 14:07:50 +01002994/* Pushes the channel onto the top of the stack. If the stask does not have a
2995 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002996 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002997static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002998{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002999 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003000 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003001 return 0;
3002
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003003 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003004 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003005 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003006
3007 /* Pop a class sesison metatable and affect it to the userdata. */
3008 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3009 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003010 return 1;
3011}
3012
Christopher Faulet9f55a502020-02-25 15:21:02 +01003013/* Helper function returning a filter attached to a channel at the position <ud>
3014 * in the stack, filling the current offset and length of the filter. If no
3015 * filter is attached, NULL is returned and <offet> and <len> are not
3016 * initialized.
3017 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003018static 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 +01003019{
3020 struct filter *filter = NULL;
3021
3022 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3023 struct hlua_flt_ctx *flt_ctx;
3024
3025 filter = lua_touserdata (L, -1);
3026 flt_ctx = filter->ctx;
3027 if (hlua_filter_from_payload(filter)) {
3028 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3029 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3030 }
3031 }
3032
3033 lua_pop(L, 1);
3034 return filter;
3035}
3036
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003037/* Copies <len> bytes of data present in the channel's buffer, starting at the
3038* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003039* responsibility to ensure <len> and <offset> are valid. It always return the
3040* length of the built string. <len> may be 0, in this case, an empty string is
3041* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003042*/
3043static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003044{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003045 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046 luaL_Buffer b;
3047
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003048 block1 = len;
3049 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3050 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3051 block2 = len - block1;
3052
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003053 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003054 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3055 if (block2)
3056 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003058 return len;
3059}
3060
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003061/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3062 * function returns -1 if data cannot be copied. Otherwise, it returns the
3063 * number of bytes copied.
3064 */
3065static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3066{
3067 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003068
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003069 /* Nothing to do, just return */
3070 if (unlikely(istlen(str) == 0))
3071 goto end;
3072
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003073 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003074 ret = -1;
3075 goto end;
3076 }
3077 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3078
3079 end:
3080 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003081}
3082
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003083/* Removes <len> bytes of data at the absolute position <offset>.
3084 */
3085static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3086{
3087 size_t end = offset + len;
3088
3089 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3090 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3091 b_data(&chn->buf) - end, -len);
3092 b_sub(&chn->buf, len);
3093}
3094
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003095/* Copies input data in the channel's buffer. It is possible to set a specific
3096 * offset (0 by default) and a length (all remaining input data starting for the
3097 * offset by default). If there is not enough input data and more data can be
3098 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003099 *
3100 * From an action, All input data are considered. For a filter, the offset and
3101 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003102 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003103__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003104{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003105 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003106 struct filter *filter;
3107 size_t input, output;
3108 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003109
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003110 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003111
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003112 output = co_data(chn);
3113 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003114
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003115 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3116 if (filter && !hlua_filter_from_payload(filter))
3117 WILL_LJMP(lua_error(L));
3118
3119 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003120 if (lua_gettop(L) > 1) {
3121 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3122 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003123 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003124 offset += output;
3125 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003126 lua_pushfstring(L, "offset out of range.");
3127 WILL_LJMP(lua_error(L));
3128 }
3129 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003130 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003131 if (lua_gettop(L) == 3) {
3132 len = MAY_LJMP(luaL_checkinteger(L, 3));
3133 if (!len)
3134 goto dup;
3135 if (len == -1)
3136 len = global.tune.bufsize;
3137 if (len < 0) {
3138 lua_pushfstring(L, "length out of range.");
3139 WILL_LJMP(lua_error(L));
3140 }
3141 }
3142
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003143 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003144 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3145 /* Yield waiting for more data, as requested */
3146 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3147 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003148 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003149 }
3150
3151 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003152 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003153 return 1;
3154}
3155
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003156/* Copies the first line (including the trailing LF) of input data in the
3157 * channel's buffer. It is possible to set a specific offset (0 by default) and
3158 * a length (all remaining input data starting for the offset by default). If
3159 * there is not enough input data and more data can be received, the function
3160 * yields. If a length is explicitly specified, no more data are
3161 * copied. Otherwise, if no LF is found and more data can be received, this
3162 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003163 *
3164 * From an action, All input data are considered. For a filter, the offset and
3165 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003166 */
3167__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003168{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003169 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003170 struct filter *filter;
3171 size_t l, input, output;
3172 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003173
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003174 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003175 output = co_data(chn);
3176 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003177
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003178 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3179 if (filter && !hlua_filter_from_payload(filter))
3180 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003181
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003182 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003183 if (lua_gettop(L) > 1) {
3184 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3185 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003186 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003187 offset += output;
3188 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003189 lua_pushfstring(L, "offset out of range.");
3190 WILL_LJMP(lua_error(L));
3191 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003192 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003193
3194 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003195 if (lua_gettop(L) == 3) {
3196 len = MAY_LJMP(luaL_checkinteger(L, 3));
3197 if (!len)
3198 goto dup;
3199 if (len == -1)
3200 len = global.tune.bufsize;
3201 if (len < 0) {
3202 lua_pushfstring(L, "length out of range.");
3203 WILL_LJMP(lua_error(L));
3204 }
3205 }
3206
3207 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003208 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003209 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003210 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003211 len = l+1;
3212 goto dup;
3213 }
3214 }
3215
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003216 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003217 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3218 /* Yield waiting for more data */
3219 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3220 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003221 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003222 }
3223
3224 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003225 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003226 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003227}
3228
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003229/* [ DEPRECATED ]
3230 *
3231 * Duplicate all input data foud in the channel's buffer. The data are not
3232 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003233 *
3234 * From an action, All input data are considered. For a filter, the offset and
3235 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003236 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003237__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003238{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003239 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003240 struct filter *filter;
3241 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003242
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003243 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003244 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003245 if (IS_HTX_STRM(chn_strm(chn))) {
3246 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3247 WILL_LJMP(lua_error(L));
3248 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003249
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003250 offset = co_data(chn);
3251 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003252
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003253 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3254 if (filter && !hlua_filter_from_payload(filter))
3255 WILL_LJMP(lua_error(L));
3256
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003257 if (!ci_data(chn) && channel_input_closed(chn)) {
3258 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003259 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003260 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003261
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003262 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003263 return 1;
3264}
3265
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003266/* [ DEPRECATED ]
3267 *
3268 * Get all input data foud in the channel's buffer. The data are removed from
3269 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3270 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003271 *
3272 * From an action, All input data are considered. For a filter, the offset and
3273 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003274 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003275__LJMP static int hlua_channel_get(lua_State *L)
3276{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003277 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003278 struct filter *filter;
3279 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003280 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003281
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003282 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003283 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3284 if (IS_HTX_STRM(chn_strm(chn))) {
3285 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3286 WILL_LJMP(lua_error(L));
3287 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003288
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003289 offset = co_data(chn);
3290 len = ci_data(chn);
3291
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003292 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3293 if (filter && !hlua_filter_from_payload(filter))
3294 WILL_LJMP(lua_error(L));
3295
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003296 if (!ci_data(chn) && channel_input_closed(chn)) {
3297 lua_pushnil(L);
3298 return 1;
3299 }
3300
3301 ret = _hlua_channel_dup(chn, L, offset, len);
3302 _hlua_channel_delete(chn, offset, ret);
3303 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003304}
3305
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003306/* This functions consumes and returns one line. If the channel is closed,
3307 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003308 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003309 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003310 *
3311 * From an action, All input data are considered. For a filter, the offset and
3312 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003313 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003314__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003315{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003316 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003317 struct filter *filter;
3318 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003319 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003320
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003321 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003322
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003323 offset = co_data(chn);
3324 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003325
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003326 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3327 if (filter && !hlua_filter_from_payload(filter))
3328 WILL_LJMP(lua_error(L));
3329
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003330 if (!ci_data(chn) && channel_input_closed(chn)) {
3331 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003332 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003333 }
3334
3335 for (l = 0; l < len; l++) {
3336 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3337 len = l+1;
3338 goto dup;
3339 }
3340 }
3341
3342 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3343 /* Yield waiting for more data */
3344 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3345 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003346
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003347 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003348 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003349 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003350 return 1;
3351}
3352
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003353/* [ DEPRECATED ]
3354 *
3355 * Check arguments for the function "hlua_channel_getline_yield".
3356 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003357__LJMP static int hlua_channel_getline(lua_State *L)
3358{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003359 struct channel *chn;
3360
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003361 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003362 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3363 if (IS_HTX_STRM(chn_strm(chn))) {
3364 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3365 WILL_LJMP(lua_error(L));
3366 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003367 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3368}
3369
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003370/* Retrieves a given amount of input data at the given offset. By default all
3371 * available input data are returned. The offset may be negactive to start from
3372 * the end of input data. The length may be -1 to set it to the maximum buffer
3373 * size.
3374 */
3375__LJMP static int hlua_channel_get_data(lua_State *L)
3376{
3377 struct channel *chn;
3378
3379 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3380 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3381 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3382 if (IS_HTX_STRM(chn_strm(chn))) {
3383 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3384 WILL_LJMP(lua_error(L));
3385 }
3386 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3387}
3388
3389/* Retrieves a given amount of input data at the given offset. By default all
3390 * available input data are returned. The offset may be negactive to start from
3391 * the end of input data. The length may be -1 to set it to the maximum buffer
3392 * size.
3393 */
3394__LJMP static int hlua_channel_get_line(lua_State *L)
3395{
3396 struct channel *chn;
3397
3398 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3399 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3400 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3401 if (IS_HTX_STRM(chn_strm(chn))) {
3402 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3403 WILL_LJMP(lua_error(L));
3404 }
3405 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3406}
3407
3408/* Appends a string into the input side of channel. It returns the length of the
3409 * written string, or -1 if the channel is closed or if the buffer size is too
3410 * little for the data. 0 may be returned if nothing is copied. This function
3411 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003412 *
3413 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003414 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003415__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003416{
Christopher Faulet23976d92021-08-06 09:59:49 +02003417 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003418 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003419 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003420 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003421 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003422
3423 MAY_LJMP(check_args(L, 2, "append"));
3424 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003425 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003426 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003427 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003428 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003429 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003430
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003431 offset = co_data(chn);
3432 len = ci_data(chn);
3433
3434 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3435 if (filter && !hlua_filter_from_payload(filter))
3436 WILL_LJMP(lua_error(L));
3437
3438 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3439 if (ret > 0 && filter) {
3440 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3441
3442 flt_update_offsets(filter, chn, ret);
3443 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3444 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003445 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003446 return 1;
3447}
3448
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003449/* Prepends a string into the input side of channel. It returns the length of the
3450 * written string, or -1 if the channel is closed or if the buffer size is too
3451 * little for the data. 0 may be returned if nothing is copied. This function
3452 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003453 *
3454 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003455 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003456__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003457{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003458 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003459 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003460 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003461 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003462 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003463
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003464 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003465 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003466 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3467 if (IS_HTX_STRM(chn_strm(chn))) {
3468 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3469 WILL_LJMP(lua_error(L));
3470 }
3471
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003472 offset = co_data(chn);
3473 len = ci_data(chn);
3474
3475 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3476 if (filter && !hlua_filter_from_payload(filter))
3477 WILL_LJMP(lua_error(L));
3478
3479 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3480 if (ret > 0 && filter) {
3481 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3482
3483 flt_update_offsets(filter, chn, ret);
3484 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3485 }
3486
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003487 lua_pushinteger(L, ret);
3488 return 1;
3489}
3490
3491/* Inserts a given amount of input data at the given offset by a string
3492 * content. By default the string is appended at the end of input data. It
3493 * returns the length of the written string, or -1 if the channel is closed or
3494 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003495 *
3496 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003497 */
3498__LJMP static int hlua_channel_insert_data(lua_State *L)
3499{
3500 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003501 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003502 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003503 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003504 int ret, offset;
3505
3506 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3507 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3508 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3509 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003510
3511 output = co_data(chn);
3512 input = ci_data(chn);
3513
3514 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3515 if (filter && !hlua_filter_from_payload(filter))
3516 WILL_LJMP(lua_error(L));
3517
3518 offset = input + output;
3519 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003520 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003521 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003522 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003523 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003524 if (offset < output || offset > output + input) {
3525 lua_pushfstring(L, "offset out of range.");
3526 WILL_LJMP(lua_error(L));
3527 }
3528 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003529 if (IS_HTX_STRM(chn_strm(chn))) {
3530 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3531 WILL_LJMP(lua_error(L));
3532 }
3533
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003534 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3535 if (ret > 0 && filter) {
3536 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003537
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003538 flt_update_offsets(filter, chn, ret);
3539 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003540 }
3541
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003542 lua_pushinteger(L, ret);
3543 return 1;
3544}
3545/* Replaces a given amount of input data at the given offset by a string
3546 * content. By default all remaining data are removed (offset = 0 and len =
3547 * -1). It returns the length of the written string, or -1 if the channel is
3548 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003549 *
3550 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003551 */
3552__LJMP static int hlua_channel_set_data(lua_State *L)
3553{
3554 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003555 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003556 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003557 size_t sz, input, output;
3558 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003559
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003560 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3561 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3562 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3563 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003564
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003565 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003566 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003567 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003568 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003569
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003570 output = co_data(chn);
3571 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003572
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003573 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3574 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003575 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003576
3577 offset = output;
3578 if (lua_gettop(L) > 2) {
3579 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3580 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003581 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003582 offset += output;
3583 if (offset < output || offset > input + output) {
3584 lua_pushfstring(L, "offset out of range.");
3585 WILL_LJMP(lua_error(L));
3586 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003587 }
3588
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589 len = output + input - offset;
3590 if (lua_gettop(L) == 4) {
3591 len = MAY_LJMP(luaL_checkinteger(L, 4));
3592 if (!len)
3593 goto set;
3594 if (len == -1)
3595 len = output + input - offset;
3596 if (len < 0 || offset + len > output + input) {
3597 lua_pushfstring(L, "length out of range.");
3598 WILL_LJMP(lua_error(L));
3599 }
3600 }
3601
3602 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003603 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003604 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003605 lua_pushinteger(L, -1);
3606 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003607 _hlua_channel_delete(chn, offset, len);
3608 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3609 if (filter) {
3610 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3611
3612 len -= (ret > 0 ? ret : 0);
3613 flt_update_offsets(filter, chn, -len);
3614 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3615 }
3616
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003617 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003618 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003619 return 1;
3620}
3621
3622/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003623 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003624 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003625 *
3626 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003627 */
3628__LJMP static int hlua_channel_del_data(lua_State *L)
3629{
3630 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003631 struct filter *filter;
3632 size_t input, output;
3633 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003634
3635 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3636 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3637 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003638
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003639 if (IS_HTX_STRM(chn_strm(chn))) {
3640 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3641 WILL_LJMP(lua_error(L));
3642 }
3643
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003644 output = co_data(chn);
3645 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003646
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003647 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3648 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003649 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003650
3651 offset = output;
3652 if (lua_gettop(L) > 2) {
3653 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3654 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003655 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003656 offset += output;
3657 if (offset < output || offset > input + output) {
3658 lua_pushfstring(L, "offset out of range.");
3659 WILL_LJMP(lua_error(L));
3660 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003661 }
3662
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003663 len = output + input - offset;
3664 if (lua_gettop(L) == 4) {
3665 len = MAY_LJMP(luaL_checkinteger(L, 4));
3666 if (!len)
3667 goto end;
3668 if (len == -1)
3669 len = output + input - offset;
3670 if (len < 0 || offset + len > output + input) {
3671 lua_pushfstring(L, "length out of range.");
3672 WILL_LJMP(lua_error(L));
3673 }
3674 }
3675
3676 _hlua_channel_delete(chn, offset, len);
3677 if (filter) {
3678 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3679
3680 flt_update_offsets(filter, chn, -len);
3681 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3682 }
3683
3684 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003685 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003686 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003687}
3688
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003689/* Append data in the output side of the buffer. This data is immediately
3690 * sent. The function returns the amount of data written. If the buffer
3691 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003692 * if the channel is closed.
3693 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003694__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003695{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003696 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003697 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003698 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003699 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003700 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003701 struct hlua *hlua;
3702
3703 /* Get hlua struct, or NULL if we execute from main lua state */
3704 hlua = hlua_gethlua(L);
3705 if (!hlua) {
3706 lua_pushnil(L);
3707 return 1;
3708 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003709
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003710 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3711 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3712 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003713
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003714 offset = co_data(chn);
3715 len = ci_data(chn);
3716
3717 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3718 if (filter && !hlua_filter_from_payload(filter))
3719 WILL_LJMP(lua_error(L));
3720
3721
Willy Tarreau47860ed2015-03-10 14:07:50 +01003722 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003723 lua_pushinteger(L, -1);
3724 return 1;
3725 }
3726
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003727 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003728 if (len > sz -l) {
3729 if (filter) {
3730 lua_pushinteger(L, -1);
3731 return 1;
3732 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003733 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003734 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003735
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003736 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003737 if (ret == -1) {
3738 lua_pop(L, 1);
3739 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003740 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003741 }
3742 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003743 if (filter) {
3744 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3745
3746
3747 flt_update_offsets(filter, chn, ret);
3748 FLT_OFF(filter, chn) += ret;
3749 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3750 }
3751 else
3752 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003753
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003754 l += ret;
3755 lua_pop(L, 1);
3756 lua_pushinteger(L, l);
3757 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003759 if (l < sz) {
3760 /* Yield only if the channel's output is not empty.
3761 * Otherwise it means we cannot add more data. */
3762 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003763 return 1;
3764
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003765 /* If we are waiting for space in the response buffer, we
3766 * must set the flag WAKERESWR. This flag required the task
3767 * wake up if any activity is detected on the response buffer.
3768 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003769 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003770 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003771 else
3772 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003773 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003774 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003775
3776 return 1;
3777}
3778
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003779/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003780 * yield the LUA process, and resume it without checking the
3781 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003782 *
3783 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003784 */
3785__LJMP static int hlua_channel_send(lua_State *L)
3786{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003787 struct channel *chn;
3788
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003789 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003790 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3791 if (IS_HTX_STRM(chn_strm(chn))) {
3792 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3793 WILL_LJMP(lua_error(L));
3794 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003795 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003796 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003797}
3798
3799/* This function forward and amount of butes. The data pass from
3800 * the input side of the buffer to the output side, and can be
3801 * forwarded. This function never fails.
3802 *
3803 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003804 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003805 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003806__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003807{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003808 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003809 struct filter *filter;
3810 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003811 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003812 struct hlua *hlua;
3813
3814 /* Get hlua struct, or NULL if we execute from main lua state */
3815 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003816 if (!hlua) {
3817 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003818 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003819 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003820
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003821 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003822 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003823 l = MAY_LJMP(luaL_checkinteger(L, -1));
3824
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003825 offset = co_data(chn);
3826 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003827
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003828 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3829 if (filter && !hlua_filter_from_payload(filter))
3830 WILL_LJMP(lua_error(L));
3831
3832 max = fwd - l;
3833 if (max > len)
3834 max = len;
3835
3836 if (filter) {
3837 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3838
3839 FLT_OFF(filter, chn) += max;
3840 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3841 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3842 }
3843 else
3844 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003845
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003846 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003847 lua_pop(L, 1);
3848 lua_pushinteger(L, l);
3849
3850 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003851 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003852 /* The the input channel or the output channel are closed, we
3853 * must return the amount of data forwarded.
3854 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003855 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003856 return 1;
3857
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003858 /* If we are waiting for space data in the response buffer, we
3859 * must set the flag WAKERESWR. This flag required the task
3860 * wake up if any activity is detected on the response buffer.
3861 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003862 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003863 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003864 else
3865 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003866
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003867 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003868 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003869 }
3870
3871 return 1;
3872}
3873
3874/* Just check the input and prepare the stack for the previous
3875 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003876 *
3877 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003878 */
3879__LJMP static int hlua_channel_forward(lua_State *L)
3880{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003881 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003882
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003883 MAY_LJMP(check_args(L, 2, "forward"));
3884 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3885 if (IS_HTX_STRM(chn_strm(chn))) {
3886 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3887 WILL_LJMP(lua_error(L));
3888 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003889 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003890 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003891}
3892
3893/* Just returns the number of bytes available in the input
3894 * side of the buffer. This function never fails.
3895 */
3896__LJMP static int hlua_channel_get_in_len(lua_State *L)
3897{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003898 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003899 struct filter *filter;
3900 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003901
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003902 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003903 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003904
3905 output = co_data(chn);
3906 input = ci_data(chn);
3907 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3908 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3909 lua_pushinteger(L, input);
3910 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003911 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003912
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003913 lua_pushinteger(L, htx->data - co_data(chn));
3914 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003915 return 1;
3916}
3917
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003918/* Returns true if the channel is full. */
3919__LJMP static int hlua_channel_is_full(lua_State *L)
3920{
3921 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003922
3923 MAY_LJMP(check_args(L, 1, "is_full"));
3924 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003925 /* ignore the reserve, we are not on a producer side (ie in an
3926 * applet).
3927 */
3928 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003929 return 1;
3930}
3931
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003932/* Returns true if the channel may still receive data. */
3933__LJMP static int hlua_channel_may_recv(lua_State *L)
3934{
3935 struct channel *chn;
3936
3937 MAY_LJMP(check_args(L, 1, "may_recv"));
3938 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3939 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3940 return 1;
3941}
3942
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003943/* Returns true if the channel is the response channel. */
3944__LJMP static int hlua_channel_is_resp(lua_State *L)
3945{
3946 struct channel *chn;
3947
3948 MAY_LJMP(check_args(L, 1, "is_resp"));
3949 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3950
3951 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3952 return 1;
3953}
3954
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003955/* Just returns the number of bytes available in the output
3956 * side of the buffer. This function never fails.
3957 */
3958__LJMP static int hlua_channel_get_out_len(lua_State *L)
3959{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003960 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003961 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003962
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003963 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003964 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003965
3966 output = co_data(chn);
3967 input = ci_data(chn);
3968 hlua_channel_filter(L, 1, chn, &output, &input);
3969
3970 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003971 return 1;
3972}
3973
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003974/*
3975 *
3976 *
3977 * Class Fetches
3978 *
3979 *
3980 */
3981
3982/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003983 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003984 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003985__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003986{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003987 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003988}
3989
3990/* This function creates and push in the stack a fetch object according
3991 * with a current TXN.
3992 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003993static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003994{
Willy Tarreau7073c472015-04-06 11:15:40 +02003995 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003996
3997 /* Check stack size. */
3998 if (!lua_checkstack(L, 3))
3999 return 0;
4000
4001 /* Create the object: obj[0] = userdata.
4002 * Note that the base of the Fetches object is the
4003 * transaction object.
4004 */
4005 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004006 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004007 lua_rawseti(L, -2, 0);
4008
Willy Tarreau7073c472015-04-06 11:15:40 +02004009 hsmp->s = txn->s;
4010 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004011 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004012 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004013
4014 /* Pop a class sesison metatable and affect it to the userdata. */
4015 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4016 lua_setmetatable(L, -2);
4017
4018 return 1;
4019}
4020
4021/* This function is an LUA binding. It is called with each sample-fetch.
4022 * It uses closure argument to store the associated sample-fetch. It
4023 * returns only one argument or throws an error. An error is thrown
4024 * only if an error is encountered during the argument parsing. If
4025 * the "sample-fetch" function fails, nil is returned.
4026 */
4027__LJMP static int hlua_run_sample_fetch(lua_State *L)
4028{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004029 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004030 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004031 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004032 int i;
4033 struct sample smp;
4034
4035 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004036 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004037
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004038 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004039 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004040
Thierry FOURNIERca988662015-12-20 18:43:03 +01004041 /* Check execution authorization. */
4042 if (f->use & SMP_USE_HTTP_ANY &&
4043 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4044 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4045 "is not available in Lua services", f->kw);
4046 WILL_LJMP(lua_error(L));
4047 }
4048
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004049 /* Get extra arguments. */
4050 for (i = 0; i < lua_gettop(L) - 1; i++) {
4051 if (i >= ARGM_NBARGS)
4052 break;
4053 hlua_lua2arg(L, i + 2, &args[i]);
4054 }
4055 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004056 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004057
4058 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004059 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004060
4061 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004062 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004063 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004064 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004065 }
4066
4067 /* Initialise the sample. */
4068 memset(&smp, 0, sizeof(smp));
4069
4070 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004071 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004072 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004073 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004074 lua_pushstring(L, "");
4075 else
4076 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004077 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004078 }
4079
4080 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004081 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004082 hlua_smp2lua_str(L, &smp);
4083 else
4084 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004085
4086 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004087 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004088 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004089
4090 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004091 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004092 WILL_LJMP(lua_error(L));
4093 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004094}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004095
4096/*
4097 *
4098 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004099 * Class Converters
4100 *
4101 *
4102 */
4103
4104/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004105 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004106 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004107__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004108{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004109 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004110}
4111
4112/* This function creates and push in the stack a Converters object
4113 * according with a current TXN.
4114 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004115static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004116{
Willy Tarreau7073c472015-04-06 11:15:40 +02004117 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004118
4119 /* Check stack size. */
4120 if (!lua_checkstack(L, 3))
4121 return 0;
4122
4123 /* Create the object: obj[0] = userdata.
4124 * Note that the base of the Converters object is the
4125 * same than the TXN object.
4126 */
4127 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004128 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004129 lua_rawseti(L, -2, 0);
4130
Willy Tarreau7073c472015-04-06 11:15:40 +02004131 hsmp->s = txn->s;
4132 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004133 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004134 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004135
Willy Tarreau87b09662015-04-03 00:22:06 +02004136 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004137 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4138 lua_setmetatable(L, -2);
4139
4140 return 1;
4141}
4142
4143/* This function is an LUA binding. It is called with each converter.
4144 * It uses closure argument to store the associated converter. It
4145 * returns only one argument or throws an error. An error is thrown
4146 * only if an error is encountered during the argument parsing. If
4147 * the converter function function fails, nil is returned.
4148 */
4149__LJMP static int hlua_run_sample_conv(lua_State *L)
4150{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004151 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004152 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004153 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004154 int i;
4155 struct sample smp;
4156
4157 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004158 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004159
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004160 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004161 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004162
4163 /* Get extra arguments. */
4164 for (i = 0; i < lua_gettop(L) - 2; i++) {
4165 if (i >= ARGM_NBARGS)
4166 break;
4167 hlua_lua2arg(L, i + 3, &args[i]);
4168 }
4169 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004170 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004171
4172 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004173 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004174
4175 /* Run the special args checker. */
4176 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4177 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004178 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004179 }
4180
4181 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004182 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004183 if (!hlua_lua2smp(L, 2, &smp)) {
4184 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004185 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004186 }
4187
Willy Tarreau1777ea62016-03-10 16:15:46 +01004188 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4189
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004190 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004191 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004192 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004193 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004194 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004195 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004196 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4197 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004198 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004199 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004200 }
4201
4202 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004203 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004204 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004205 lua_pushstring(L, "");
4206 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004207 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004208 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004209 }
4210
4211 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004212 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004213 hlua_smp2lua_str(L, &smp);
4214 else
4215 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004216 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004217 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004218 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004219
4220 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004221 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004222 WILL_LJMP(lua_error(L));
4223 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004224}
4225
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004226/*
4227 *
4228 *
4229 * Class AppletTCP
4230 *
4231 *
4232 */
4233
4234/* Returns a struct hlua_txn if the stack entry "ud" is
4235 * a class stream, otherwise it throws an error.
4236 */
4237__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4238{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004239 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004240}
4241
4242/* This function creates and push in the stack an Applet object
4243 * according with a current TXN.
4244 */
4245static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4246{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004247 struct hlua_appctx *luactx;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004248 struct stream_interface *si = ctx->owner;
4249 struct stream *s = si_strm(si);
4250 struct proxy *p = s->be;
4251
4252 /* Check stack size. */
4253 if (!lua_checkstack(L, 3))
4254 return 0;
4255
4256 /* Create the object: obj[0] = userdata.
4257 * Note that the base of the Converters object is the
4258 * same than the TXN object.
4259 */
4260 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004261 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004262 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004263 luactx->appctx = ctx;
4264 luactx->htxn.s = s;
4265 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004266
4267 /* Create the "f" field that contains a list of fetches. */
4268 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004269 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004270 return 0;
4271 lua_settable(L, -3);
4272
4273 /* Create the "sf" field that contains a list of stringsafe fetches. */
4274 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004275 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004276 return 0;
4277 lua_settable(L, -3);
4278
4279 /* Create the "c" field that contains a list of converters. */
4280 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004281 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004282 return 0;
4283 lua_settable(L, -3);
4284
4285 /* Create the "sc" field that contains a list of stringsafe converters. */
4286 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004287 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004288 return 0;
4289 lua_settable(L, -3);
4290
4291 /* Pop a class stream metatable and affect it to the table. */
4292 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4293 lua_setmetatable(L, -2);
4294
4295 return 1;
4296}
4297
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004298__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4299{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004300 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004301 struct stream *s;
4302 const char *name;
4303 size_t len;
4304 struct sample smp;
4305
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004306 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4307 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004308
4309 /* It is useles to retrieve the stream, but this function
4310 * runs only in a stream context.
4311 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004312 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004313 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004314 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004315
4316 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004317 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004318 hlua_lua2smp(L, 3, &smp);
4319
4320 /* Store the sample in a variable. */
4321 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004322
4323 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4324 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4325 else
4326 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4327
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004328 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004329}
4330
4331__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4332{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004333 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004334 struct stream *s;
4335 const char *name;
4336 size_t len;
4337 struct sample smp;
4338
4339 MAY_LJMP(check_args(L, 2, "unset_var"));
4340
4341 /* It is useles to retrieve the stream, but this function
4342 * runs only in a stream context.
4343 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004344 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004345 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004346 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004347
4348 /* Unset the variable. */
4349 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004350 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4351 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004352}
4353
4354__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4355{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004356 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004357 struct stream *s;
4358 const char *name;
4359 size_t len;
4360 struct sample smp;
4361
4362 MAY_LJMP(check_args(L, 2, "get_var"));
4363
4364 /* It is useles to retrieve the stream, but this function
4365 * runs only in a stream context.
4366 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004367 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004368 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004369 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004370
4371 smp_set_owner(&smp, s->be, s->sess, s, 0);
4372 if (!vars_get_by_name(name, len, &smp)) {
4373 lua_pushnil(L);
4374 return 1;
4375 }
4376
4377 return hlua_smp2lua(L, &smp);
4378}
4379
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004380__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4381{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004382 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4383 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004384 struct hlua *hlua;
4385
4386 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004387 if (!s->hlua)
4388 return 0;
4389 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004390
4391 MAY_LJMP(check_args(L, 2, "set_priv"));
4392
4393 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004394 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004395
4396 /* Get and store new value. */
4397 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4398 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4399
4400 return 0;
4401}
4402
4403__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4404{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004405 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4406 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004407 struct hlua *hlua;
4408
4409 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004410 if (!s->hlua) {
4411 lua_pushnil(L);
4412 return 1;
4413 }
4414 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004415
4416 /* Push configuration index in the stack. */
4417 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4418
4419 return 1;
4420}
4421
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004422/* If expected data not yet available, it returns a yield. This function
4423 * consumes the data in the buffer. It returns a string containing the
4424 * data. This string can be empty.
4425 */
4426__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4427{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004428 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4429 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004430 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004431 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004432 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004433 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004434 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004435
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004436 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004437 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004438
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004439 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004440 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004441 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004442 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004443 }
4444
4445 /* End of data: commit the total strings and return. */
4446 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004447 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004448 return 1;
4449 }
4450
4451 /* Ensure that the block 2 length is usable. */
4452 if (ret == 1)
4453 len2 = 0;
4454
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004455 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004456 luaL_addlstring(&luactx->b, blk1, len1);
4457 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004458
4459 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004460 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004461 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004462 return 1;
4463}
4464
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004465/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004466__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4467{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004468 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004469
4470 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004471 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004472
4473 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4474}
4475
4476/* If expected data not yet available, it returns a yield. This function
4477 * consumes the data in the buffer. It returns a string containing the
4478 * data. This string can be empty.
4479 */
4480__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4481{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004482 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4483 struct stream_interface *si = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004484 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004485 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004486 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004487 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004488 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004489 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004490
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004491 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004492 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004493
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004494 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004495 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004496 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004497 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004498 }
4499
4500 /* End of data: commit the total strings and return. */
4501 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004502 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004503 return 1;
4504 }
4505
4506 /* Ensure that the block 2 length is usable. */
4507 if (ret == 1)
4508 len2 = 0;
4509
4510 if (len == -1) {
4511
4512 /* If len == -1, catenate all the data avalaile and
4513 * yield because we want to get all the data until
4514 * the end of data stream.
4515 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004516 luaL_addlstring(&luactx->b, blk1, len1);
4517 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004518 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004519 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004520 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004521
4522 } else {
4523
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004524 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004525 if (len1 > len)
4526 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004527 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004528 len -= len1;
4529
4530 /* Copy the second block. */
4531 if (len2 > len)
4532 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004533 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004534 len -= len2;
4535
4536 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004537 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004538
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004539 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004540 if (len > 0) {
4541 lua_pushinteger(L, len);
4542 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004543 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004544 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004545 }
4546
4547 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004548 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004549 return 1;
4550 }
4551
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004552 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553 hlua_pusherror(L, "Lua: internal error");
4554 WILL_LJMP(lua_error(L));
4555 return 0;
4556}
4557
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004558/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004559__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4560{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004561 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004562 int len = -1;
4563
4564 if (lua_gettop(L) > 2)
4565 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4566 if (lua_gettop(L) >= 2) {
4567 len = MAY_LJMP(luaL_checkinteger(L, 2));
4568 lua_pop(L, 1);
4569 }
4570
4571 /* Confirm or set the required length */
4572 lua_pushinteger(L, len);
4573
4574 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004575 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576
4577 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4578}
4579
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004580/* Append data in the output side of the buffer. This data is immediately
4581 * sent. The function returns the amount of data written. If the buffer
4582 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004583 * if the channel is closed.
4584 */
4585__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4586{
4587 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004588 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004589 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4590 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004591 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004592 struct channel *chn = si_ic(si);
4593 int max;
4594
4595 /* Get the max amount of data which can write as input in the channel. */
4596 max = channel_recv_max(chn);
4597 if (max > (len - l))
4598 max = len - l;
4599
4600 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004601 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602
4603 /* update counters. */
4604 l += max;
4605 lua_pop(L, 1);
4606 lua_pushinteger(L, l);
4607
4608 /* If some data is not send, declares the situation to the
4609 * applet, and returns a yield.
4610 */
4611 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004612 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004613 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004614 }
4615
4616 return 1;
4617}
4618
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004619/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004620 * yield the LUA process, and resume it without checking the
4621 * input arguments.
4622 */
4623__LJMP static int hlua_applet_tcp_send(lua_State *L)
4624{
4625 MAY_LJMP(check_args(L, 2, "send"));
4626 lua_pushinteger(L, 0);
4627
4628 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4629}
4630
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004631/*
4632 *
4633 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004634 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004635 *
4636 *
4637 */
4638
4639/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004640 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004641 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004642__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004643{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004644 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004645}
4646
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004647/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004648 * according with a current TXN.
4649 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004650static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004651{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004652 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004653 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004654 struct stream_interface *si = ctx->owner;
4655 struct stream *s = si_strm(si);
4656 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004657 struct htx *htx;
4658 struct htx_blk *blk;
4659 struct htx_sl *sl;
4660 struct ist path;
4661 unsigned long long len = 0;
4662 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004663 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004664
4665 /* Check stack size. */
4666 if (!lua_checkstack(L, 3))
4667 return 0;
4668
4669 /* Create the object: obj[0] = userdata.
4670 * Note that the base of the Converters object is the
4671 * same than the TXN object.
4672 */
4673 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004674 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004675 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004676 luactx->appctx = ctx;
4677 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4678 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4679 luactx->htxn.s = s;
4680 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004681
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004682 /* Create the "f" field that contains a list of fetches. */
4683 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004684 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004685 return 0;
4686 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004687
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004688 /* Create the "sf" field that contains a list of stringsafe fetches. */
4689 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004690 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004691 return 0;
4692 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004693
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004694 /* Create the "c" field that contains a list of converters. */
4695 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004696 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004697 return 0;
4698 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004699
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004700 /* Create the "sc" field that contains a list of stringsafe converters. */
4701 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004702 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004703 return 0;
4704 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004705
Christopher Fauleta2097962019-07-15 16:25:33 +02004706 htx = htxbuf(&s->req.buf);
4707 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004708 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004709 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004710
Christopher Fauleta2097962019-07-15 16:25:33 +02004711 /* Stores the request method. */
4712 lua_pushstring(L, "method");
4713 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4714 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004715
Christopher Fauleta2097962019-07-15 16:25:33 +02004716 /* Stores the http version. */
4717 lua_pushstring(L, "version");
4718 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4719 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004720
Christopher Fauleta2097962019-07-15 16:25:33 +02004721 /* creates an array of headers. hlua_http_get_headers() crates and push
4722 * the array on the top of the stack.
4723 */
4724 lua_pushstring(L, "headers");
4725 htxn.s = s;
4726 htxn.p = px;
4727 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004728 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004729 return 0;
4730 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004731
Amaury Denoyellec453f952021-07-06 11:40:12 +02004732 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4733 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004734 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004735 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004736
Christopher Fauleta2097962019-07-15 16:25:33 +02004737 p = path.ptr;
4738 end = path.ptr + path.len;
4739 q = p;
4740 while (q < end && *q != '?')
4741 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004742
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004743 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004744 lua_pushstring(L, "path");
4745 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004746 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004747
Christopher Fauleta2097962019-07-15 16:25:33 +02004748 /* Stores the query string. */
4749 lua_pushstring(L, "qs");
4750 if (*q == '?')
4751 q++;
4752 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004753 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004754 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004755
Christopher Fauleta2097962019-07-15 16:25:33 +02004756 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4757 struct htx_blk *blk = htx_get_blk(htx, pos);
4758 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004759
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004760 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004761 break;
4762 if (type == HTX_BLK_DATA)
4763 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004764 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004765 if (htx->extra != ULLONG_MAX)
4766 len += htx->extra;
4767
4768 /* Stores the request path. */
4769 lua_pushstring(L, "length");
4770 lua_pushinteger(L, len);
4771 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004772
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004773 /* Create an empty array of HTTP request headers. */
4774 lua_pushstring(L, "response");
4775 lua_newtable(L);
4776 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004777
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004778 /* Pop a class stream metatable and affect it to the table. */
4779 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4780 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004781
4782 return 1;
4783}
4784
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004785__LJMP static int hlua_applet_http_set_var(lua_State *L)
4786{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004787 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004788 struct stream *s;
4789 const char *name;
4790 size_t len;
4791 struct sample smp;
4792
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004793 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4794 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004795
4796 /* It is useles to retrieve the stream, but this function
4797 * runs only in a stream context.
4798 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004799 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004800 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004801 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004802
4803 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004804 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004805 hlua_lua2smp(L, 3, &smp);
4806
4807 /* Store the sample in a variable. */
4808 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004809
4810 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4811 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4812 else
4813 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4814
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004815 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004816}
4817
4818__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4819{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004820 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004821 struct stream *s;
4822 const char *name;
4823 size_t len;
4824 struct sample smp;
4825
4826 MAY_LJMP(check_args(L, 2, "unset_var"));
4827
4828 /* It is useles to retrieve the stream, but this function
4829 * runs only in a stream context.
4830 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004831 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004832 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004833 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004834
4835 /* Unset the variable. */
4836 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004837 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4838 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004839}
4840
4841__LJMP static int hlua_applet_http_get_var(lua_State *L)
4842{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004843 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004844 struct stream *s;
4845 const char *name;
4846 size_t len;
4847 struct sample smp;
4848
4849 MAY_LJMP(check_args(L, 2, "get_var"));
4850
4851 /* It is useles to retrieve the stream, but this function
4852 * runs only in a stream context.
4853 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004854 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004855 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004856 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004857
4858 smp_set_owner(&smp, s->be, s->sess, s, 0);
4859 if (!vars_get_by_name(name, len, &smp)) {
4860 lua_pushnil(L);
4861 return 1;
4862 }
4863
4864 return hlua_smp2lua(L, &smp);
4865}
4866
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004867__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4868{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004869 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4870 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004871 struct hlua *hlua;
4872
4873 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004874 if (!s->hlua)
4875 return 0;
4876 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004877
4878 MAY_LJMP(check_args(L, 2, "set_priv"));
4879
4880 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004881 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004882
4883 /* Get and store new value. */
4884 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4885 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4886
4887 return 0;
4888}
4889
4890__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4891{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004892 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4893 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004894 struct hlua *hlua;
4895
4896 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004897 if (!s->hlua) {
4898 lua_pushnil(L);
4899 return 1;
4900 }
4901 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004902
4903 /* Push configuration index in the stack. */
4904 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4905
4906 return 1;
4907}
4908
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004909/* If expected data not yet available, it returns a yield. This function
4910 * consumes the data in the buffer. It returns a string containing the
4911 * data. This string can be empty.
4912 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004913__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004914{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004915 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4916 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004917 struct channel *req = si_oc(si);
4918 struct htx *htx;
4919 struct htx_blk *blk;
4920 size_t count;
4921 int stop = 0;
4922
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004923 htx = htx_from_buf(&req->buf);
4924 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004925 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004926
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004927 while (count && !stop && blk) {
4928 enum htx_blk_type type = htx_get_blk_type(blk);
4929 uint32_t sz = htx_get_blksz(blk);
4930 struct ist v;
4931 uint32_t vlen;
4932 char *nl;
4933
4934 vlen = sz;
4935 if (vlen > count) {
4936 if (type != HTX_BLK_DATA)
4937 break;
4938 vlen = count;
4939 }
4940
4941 switch (type) {
4942 case HTX_BLK_UNUSED:
4943 break;
4944
4945 case HTX_BLK_DATA:
4946 v = htx_get_blk_value(htx, blk);
4947 v.len = vlen;
4948 nl = istchr(v, '\n');
4949 if (nl != NULL) {
4950 stop = 1;
4951 vlen = nl - v.ptr + 1;
4952 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004953 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004954 break;
4955
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004956 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004957 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004958 stop = 1;
4959 break;
4960
4961 default:
4962 break;
4963 }
4964
4965 co_set_data(req, co_data(req) - vlen);
4966 count -= vlen;
4967 if (sz == vlen)
4968 blk = htx_remove_blk(htx, blk);
4969 else {
4970 htx_cut_data_blk(htx, blk, vlen);
4971 break;
4972 }
4973 }
4974
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004975 /* The message was fully consumed and no more data are expected
4976 * (EOM flag set).
4977 */
4978 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
4979 stop = 1;
4980
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004981 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004982 if (!stop) {
4983 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004984 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004985 }
4986
4987 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004988 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004989 return 1;
4990}
4991
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004992
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004993/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004994__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004995{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004996 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004997
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004998 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004999 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005000
Christopher Fauleta2097962019-07-15 16:25:33 +02005001 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005002}
5003
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005004/* If expected data not yet available, it returns a yield. This function
5005 * consumes the data in the buffer. It returns a string containing the
5006 * data. This string can be empty.
5007 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005008__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005009{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005010 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5011 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005012 struct channel *req = si_oc(si);
5013 struct htx *htx;
5014 struct htx_blk *blk;
5015 size_t count;
5016 int len;
5017
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005018 htx = htx_from_buf(&req->buf);
5019 len = MAY_LJMP(luaL_checkinteger(L, 2));
5020 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005021 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005022 while (count && len && blk) {
5023 enum htx_blk_type type = htx_get_blk_type(blk);
5024 uint32_t sz = htx_get_blksz(blk);
5025 struct ist v;
5026 uint32_t vlen;
5027
5028 vlen = sz;
5029 if (len > 0 && vlen > len)
5030 vlen = len;
5031 if (vlen > count) {
5032 if (type != HTX_BLK_DATA)
5033 break;
5034 vlen = count;
5035 }
5036
5037 switch (type) {
5038 case HTX_BLK_UNUSED:
5039 break;
5040
5041 case HTX_BLK_DATA:
5042 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005043 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005044 break;
5045
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005046 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005047 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005048 len = 0;
5049 break;
5050
5051 default:
5052 break;
5053 }
5054
5055 co_set_data(req, co_data(req) - vlen);
5056 count -= vlen;
5057 if (len > 0)
5058 len -= vlen;
5059 if (sz == vlen)
5060 blk = htx_remove_blk(htx, blk);
5061 else {
5062 htx_cut_data_blk(htx, blk, vlen);
5063 break;
5064 }
5065 }
5066
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005067 /* The message was fully consumed and no more data are expected
5068 * (EOM flag set).
5069 */
5070 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5071 len = 0;
5072
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005073 htx_to_buf(htx, &req->buf);
5074
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005075 /* If we are no other data available, yield waiting for new data. */
5076 if (len) {
5077 if (len > 0) {
5078 lua_pushinteger(L, len);
5079 lua_replace(L, 2);
5080 }
5081 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005082 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005083 }
5084
5085 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005086 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005087 return 1;
5088}
5089
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005090/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005091__LJMP static int hlua_applet_http_recv(lua_State *L)
5092{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005093 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005094 int len = -1;
5095
5096 /* Check arguments. */
5097 if (lua_gettop(L) > 2)
5098 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5099 if (lua_gettop(L) >= 2) {
5100 len = MAY_LJMP(luaL_checkinteger(L, 2));
5101 lua_pop(L, 1);
5102 }
5103
Christopher Fauleta2097962019-07-15 16:25:33 +02005104 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005105
Christopher Fauleta2097962019-07-15 16:25:33 +02005106 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005107 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005108
Christopher Fauleta2097962019-07-15 16:25:33 +02005109 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005110}
5111
5112/* Append data in the output side of the buffer. This data is immediately
5113 * sent. The function returns the amount of data written. If the buffer
5114 * cannot contain the data, the function yields. The function returns -1
5115 * if the channel is closed.
5116 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005117__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005118{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005119 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5120 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005121 struct channel *res = si_ic(si);
5122 struct htx *htx = htx_from_buf(&res->buf);
5123 const char *data;
5124 size_t len;
5125 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5126 int max;
5127
Christopher Faulet9060fc02019-07-03 11:39:30 +02005128 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005129 if (!max)
5130 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005131
5132 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5133
5134 /* Get the max amount of data which can write as input in the channel. */
5135 if (max > (len - l))
5136 max = len - l;
5137
5138 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005139 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005140 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005141
5142 /* update counters. */
5143 l += max;
5144 lua_pop(L, 1);
5145 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005146
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005147 /* If some data is not send, declares the situation to the
5148 * applet, and returns a yield.
5149 */
5150 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005151 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005152 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005153 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005154 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005155 }
5156
Christopher Fauleta2097962019-07-15 16:25:33 +02005157 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005158 return 1;
5159}
5160
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005161/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005162 * yield the LUA process, and resume it without checking the
5163 * input arguments.
5164 */
5165__LJMP static int hlua_applet_http_send(lua_State *L)
5166{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005167 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005168
5169 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005170 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005171 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5172 WILL_LJMP(lua_error(L));
5173 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005174
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005175 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005176 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005177
Christopher Fauleta2097962019-07-15 16:25:33 +02005178 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005179}
5180
5181__LJMP static int hlua_applet_http_addheader(lua_State *L)
5182{
5183 const char *name;
5184 int ret;
5185
5186 MAY_LJMP(hlua_checkapplet_http(L, 1));
5187 name = MAY_LJMP(luaL_checkstring(L, 2));
5188 MAY_LJMP(luaL_checkstring(L, 3));
5189
5190 /* Push in the stack the "response" entry. */
5191 ret = lua_getfield(L, 1, "response");
5192 if (ret != LUA_TTABLE) {
5193 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5194 "is expected as an array. %s found", lua_typename(L, ret));
5195 WILL_LJMP(lua_error(L));
5196 }
5197
5198 /* check if the header is already registered if it is not
5199 * the case, register it.
5200 */
5201 ret = lua_getfield(L, -1, name);
5202 if (ret == LUA_TNIL) {
5203
5204 /* Entry not found. */
5205 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5206
5207 /* Insert the new header name in the array in the top of the stack.
5208 * It left the new array in the top of the stack.
5209 */
5210 lua_newtable(L);
5211 lua_pushvalue(L, 2);
5212 lua_pushvalue(L, -2);
5213 lua_settable(L, -4);
5214
5215 } else if (ret != LUA_TTABLE) {
5216
5217 /* corruption error. */
5218 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5219 "is expected as an array. %s found", name, lua_typename(L, ret));
5220 WILL_LJMP(lua_error(L));
5221 }
5222
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005223 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005224 * the header value as new entry.
5225 */
5226 lua_pushvalue(L, 3);
5227 ret = lua_rawlen(L, -2);
5228 lua_rawseti(L, -2, ret + 1);
5229 lua_pushboolean(L, 1);
5230 return 1;
5231}
5232
5233__LJMP static int hlua_applet_http_status(lua_State *L)
5234{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005235 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005236 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005237 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005238
5239 if (status < 100 || status > 599) {
5240 lua_pushboolean(L, 0);
5241 return 1;
5242 }
5243
Willy Tarreau7e702d12021-04-28 17:59:21 +02005244 luactx->appctx->ctx.hlua_apphttp.status = status;
5245 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005246 lua_pushboolean(L, 1);
5247 return 1;
5248}
5249
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005250
Christopher Fauleta2097962019-07-15 16:25:33 +02005251__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005252{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005253 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5254 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005255 struct channel *res = si_ic(si);
5256 struct htx *htx;
5257 struct htx_sl *sl;
5258 struct h1m h1m;
5259 const char *status, *reason;
5260 const char *name, *value;
5261 size_t nlen, vlen;
5262 unsigned int flags;
5263
5264 /* Send the message at once. */
5265 htx = htx_from_buf(&res->buf);
5266 h1m_init_res(&h1m);
5267
5268 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005269 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5270 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005271 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005272 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5273 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005274 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5275 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5276 }
5277 else {
5278 flags = HTX_SL_F_IS_RESP;
5279 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5280 }
5281 if (!sl) {
5282 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005283 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005284 WILL_LJMP(lua_error(L));
5285 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005286 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005287
5288 /* Get the array associated to the field "response" in the object AppletHTTP. */
5289 lua_pushvalue(L, 0);
5290 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5291 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005292 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005293 WILL_LJMP(lua_error(L));
5294 }
5295
5296 /* Browse the list of headers. */
5297 lua_pushnil(L);
5298 while(lua_next(L, -2) != 0) {
5299 /* We expect a string as -2. */
5300 if (lua_type(L, -2) != LUA_TSTRING) {
5301 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005302 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005303 lua_typename(L, lua_type(L, -2)));
5304 WILL_LJMP(lua_error(L));
5305 }
5306 name = lua_tolstring(L, -2, &nlen);
5307
5308 /* We expect an array as -1. */
5309 if (lua_type(L, -1) != LUA_TTABLE) {
5310 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 +02005311 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005312 name,
5313 lua_typename(L, lua_type(L, -1)));
5314 WILL_LJMP(lua_error(L));
5315 }
5316
5317 /* Browse the table who is on the top of the stack. */
5318 lua_pushnil(L);
5319 while(lua_next(L, -2) != 0) {
5320 int id;
5321
5322 /* We expect a number as -2. */
5323 if (lua_type(L, -2) != LUA_TNUMBER) {
5324 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 +02005325 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005326 name,
5327 lua_typename(L, lua_type(L, -2)));
5328 WILL_LJMP(lua_error(L));
5329 }
5330 id = lua_tointeger(L, -2);
5331
5332 /* We expect a string as -2. */
5333 if (lua_type(L, -1) != LUA_TSTRING) {
5334 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 +02005335 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005336 name, id,
5337 lua_typename(L, lua_type(L, -1)));
5338 WILL_LJMP(lua_error(L));
5339 }
5340 value = lua_tolstring(L, -1, &vlen);
5341
5342 /* Simple Protocol checks. */
5343 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01005344 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005345 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5346 struct ist v = ist2(value, vlen);
5347 int ret;
5348
5349 ret = h1_parse_cont_len_header(&h1m, &v);
5350 if (ret < 0) {
5351 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005352 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005353 name);
5354 WILL_LJMP(lua_error(L));
5355 }
5356 else if (ret == 0)
5357 goto next; /* Skip it */
5358 }
5359
5360 /* Add a new header */
5361 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5362 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005363 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005364 name);
5365 WILL_LJMP(lua_error(L));
5366 }
5367 next:
5368 /* Remove the array from the stack, and get next element with a remaining string. */
5369 lua_pop(L, 1);
5370 }
5371
5372 /* Remove the array from the stack, and get next element with a remaining string. */
5373 lua_pop(L, 1);
5374 }
5375
5376 if (h1m.flags & H1_MF_CHNK)
5377 h1m.flags &= ~H1_MF_CLEN;
5378 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5379 h1m.flags |= H1_MF_XFER_LEN;
5380
5381 /* Uset HTX start-line flags */
5382 if (h1m.flags & H1_MF_XFER_ENC)
5383 flags |= HTX_SL_F_XFER_ENC;
5384 if (h1m.flags & H1_MF_XFER_LEN) {
5385 flags |= HTX_SL_F_XFER_LEN;
5386 if (h1m.flags & H1_MF_CHNK)
5387 flags |= HTX_SL_F_CHNK;
5388 else if (h1m.flags & H1_MF_CLEN)
5389 flags |= HTX_SL_F_CLEN;
5390 if (h1m.body_len == 0)
5391 flags |= HTX_SL_F_BODYLESS;
5392 }
5393 sl->flags |= flags;
5394
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005395 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005396 * and the status code implies the presence of a message body, we must
5397 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005398 * for the keepalive compliance. If the applet announces a transfer-encoding
5399 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005400 */
5401 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005402 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5403 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5404 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005405 /* Add a new header */
5406 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5407 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5408 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005409 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005410 WILL_LJMP(lua_error(L));
5411 }
5412 }
5413
5414 /* Finalize headers. */
5415 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5416 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005417 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005418 WILL_LJMP(lua_error(L));
5419 }
5420
5421 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5422 b_reset(&res->buf);
5423 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5424 WILL_LJMP(lua_error(L));
5425 }
5426
5427 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005428 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005429
5430 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005431 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005432 return 0;
5433
5434}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005435/* We will build the status line and the headers of the HTTP response.
5436 * We will try send at once if its not possible, we give back the hand
5437 * waiting for more room.
5438 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005439__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005440{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005441 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5442 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005443 struct channel *res = si_ic(si);
5444
5445 if (co_data(res)) {
5446 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005447 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005448 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005449 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005450}
5451
5452
Christopher Fauleta2097962019-07-15 16:25:33 +02005453__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005454{
Christopher Fauleta2097962019-07-15 16:25:33 +02005455 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005456}
5457
Christopher Fauleta2097962019-07-15 16:25:33 +02005458/*
5459 *
5460 *
5461 * Class HTTP
5462 *
5463 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005464 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005465
5466/* Returns a struct hlua_txn if the stack entry "ud" is
5467 * a class stream, otherwise it throws an error.
5468 */
5469__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005470{
Christopher Fauleta2097962019-07-15 16:25:33 +02005471 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5472}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005473
Christopher Fauleta2097962019-07-15 16:25:33 +02005474/* This function creates and push in the stack a HTTP object
5475 * according with a current TXN.
5476 */
5477static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5478{
5479 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005480
Christopher Fauleta2097962019-07-15 16:25:33 +02005481 /* Check stack size. */
5482 if (!lua_checkstack(L, 3))
5483 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005484
Christopher Fauleta2097962019-07-15 16:25:33 +02005485 /* Create the object: obj[0] = userdata.
5486 * Note that the base of the Converters object is the
5487 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005488 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005489 lua_newtable(L);
5490 htxn = lua_newuserdata(L, sizeof(*htxn));
5491 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005492
5493 htxn->s = txn->s;
5494 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005495 htxn->dir = txn->dir;
5496 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005497
5498 /* Pop a class stream metatable and affect it to the table. */
5499 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5500 lua_setmetatable(L, -2);
5501
5502 return 1;
5503}
5504
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005505/* This function creates and returns an array containing the status-line
5506 * elements. This function does not fails.
5507 */
5508__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5509{
5510 /* Create the table. */
5511 lua_newtable(L);
5512
5513 if (sl->flags & HTX_SL_F_IS_RESP) {
5514 lua_pushstring(L, "version");
5515 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5516 lua_settable(L, -3);
5517 lua_pushstring(L, "code");
5518 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5519 lua_settable(L, -3);
5520 lua_pushstring(L, "reason");
5521 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5522 lua_settable(L, -3);
5523 }
5524 else {
5525 lua_pushstring(L, "method");
5526 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5527 lua_settable(L, -3);
5528 lua_pushstring(L, "uri");
5529 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5530 lua_settable(L, -3);
5531 lua_pushstring(L, "version");
5532 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5533 lua_settable(L, -3);
5534 }
5535 return 1;
5536}
5537
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005538/* This function creates ans returns an array of HTTP headers.
5539 * This function does not fails. It is used as wrapper with the
5540 * 2 following functions.
5541 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005542__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005543{
Christopher Fauleta2097962019-07-15 16:25:33 +02005544 struct htx *htx;
5545 int32_t pos;
5546
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005547 /* Create the table. */
5548 lua_newtable(L);
5549
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005550
Christopher Fauleta2097962019-07-15 16:25:33 +02005551 htx = htxbuf(&msg->chn->buf);
5552 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5553 struct htx_blk *blk = htx_get_blk(htx, pos);
5554 enum htx_blk_type type = htx_get_blk_type(blk);
5555 struct ist n, v;
5556 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005557
Christopher Fauleta2097962019-07-15 16:25:33 +02005558 if (type == HTX_BLK_HDR) {
5559 n = htx_get_blk_name(htx,blk);
5560 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005561 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005562 else if (type == HTX_BLK_EOH)
5563 break;
5564 else
5565 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005566
Christopher Fauleta2097962019-07-15 16:25:33 +02005567 /* Check for existing entry:
5568 * assume that the table is on the top of the stack, and
5569 * push the key in the stack, the function lua_gettable()
5570 * perform the lookup.
5571 */
5572 lua_pushlstring(L, n.ptr, n.len);
5573 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005574
Christopher Fauleta2097962019-07-15 16:25:33 +02005575 switch (lua_type(L, -1)) {
5576 case LUA_TNIL:
5577 /* Table not found, create it. */
5578 lua_pop(L, 1); /* remove the nil value. */
5579 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5580 lua_newtable(L); /* create and push empty table. */
5581 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5582 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5583 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005584 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005585
Christopher Fauleta2097962019-07-15 16:25:33 +02005586 case LUA_TTABLE:
5587 /* Entry found: push the value in the table. */
5588 len = lua_rawlen(L, -1);
5589 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5590 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5591 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5592 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005593
Christopher Fauleta2097962019-07-15 16:25:33 +02005594 default:
5595 /* Other cases are errors. */
5596 hlua_pusherror(L, "internal error during the parsing of headers.");
5597 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005598 }
5599 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005600 return 1;
5601}
5602
5603__LJMP static int hlua_http_req_get_headers(lua_State *L)
5604{
5605 struct hlua_txn *htxn;
5606
5607 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5608 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5609
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005610 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005611 WILL_LJMP(lua_error(L));
5612
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005613 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005614}
5615
5616__LJMP static int hlua_http_res_get_headers(lua_State *L)
5617{
5618 struct hlua_txn *htxn;
5619
5620 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5621 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5622
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005623 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005624 WILL_LJMP(lua_error(L));
5625
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005626 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005627}
5628
5629/* This function replace full header, or just a value in
5630 * the request or in the response. It is a wrapper fir the
5631 * 4 following functions.
5632 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005633__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005634{
5635 size_t name_len;
5636 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5637 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5638 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005639 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005640 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005641
Dragan Dosen26743032019-04-30 15:54:36 +02005642 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005643 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5644
Christopher Fauleta2097962019-07-15 16:25:33 +02005645 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005646 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005647 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005648 return 0;
5649}
5650
5651__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5652{
5653 struct hlua_txn *htxn;
5654
5655 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5656 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5657
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005658 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005659 WILL_LJMP(lua_error(L));
5660
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005661 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005662}
5663
5664__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5665{
5666 struct hlua_txn *htxn;
5667
5668 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5669 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5670
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005671 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005672 WILL_LJMP(lua_error(L));
5673
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005674 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005675}
5676
5677__LJMP static int hlua_http_req_rep_val(lua_State *L)
5678{
5679 struct hlua_txn *htxn;
5680
5681 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5682 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5683
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005684 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005685 WILL_LJMP(lua_error(L));
5686
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005687 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005688}
5689
5690__LJMP static int hlua_http_res_rep_val(lua_State *L)
5691{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005692 struct hlua_txn *htxn;
5693
5694 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5695 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5696
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005697 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005698 WILL_LJMP(lua_error(L));
5699
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005700 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005701}
5702
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005703/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005704 * It is a wrapper for the 2 following functions.
5705 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005706__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005707{
5708 size_t len;
5709 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005710 struct htx *htx = htxbuf(&msg->chn->buf);
5711 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005712
Christopher Fauleta2097962019-07-15 16:25:33 +02005713 ctx.blk = NULL;
5714 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5715 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005716 return 0;
5717}
5718
5719__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5720{
5721 struct hlua_txn *htxn;
5722
5723 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5724 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5725
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005726 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005727 WILL_LJMP(lua_error(L));
5728
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005729 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005730}
5731
5732__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5733{
5734 struct hlua_txn *htxn;
5735
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005736 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005737 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5738
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005739 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005740 WILL_LJMP(lua_error(L));
5741
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005742 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005743}
5744
5745/* This function adds an header. It is a wrapper used by
5746 * the 2 following functions.
5747 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005748__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005749{
5750 size_t name_len;
5751 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5752 size_t value_len;
5753 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005754 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005755
Christopher Fauleta2097962019-07-15 16:25:33 +02005756 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5757 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005758 return 0;
5759}
5760
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005761__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5762{
5763 struct hlua_txn *htxn;
5764
5765 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5766 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5767
5768 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5769 WILL_LJMP(lua_error(L));
5770
5771 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5772}
5773
5774__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5775{
5776 struct hlua_txn *htxn;
5777
5778 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5779 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5780
5781 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5782 WILL_LJMP(lua_error(L));
5783
5784 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5785}
5786
5787static int hlua_http_req_set_hdr(lua_State *L)
5788{
5789 struct hlua_txn *htxn;
5790
5791 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5792 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5793
5794 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5795 WILL_LJMP(lua_error(L));
5796
5797 hlua_http_del_hdr(L, &htxn->s->txn->req);
5798 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5799}
5800
5801static int hlua_http_res_set_hdr(lua_State *L)
5802{
5803 struct hlua_txn *htxn;
5804
5805 MAY_LJMP(check_args(L, 3, "res_set_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 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5812 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5813}
5814
5815/* This function set the method. */
5816static int hlua_http_req_set_meth(lua_State *L)
5817{
5818 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5819 size_t name_len;
5820 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5821
5822 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5823 WILL_LJMP(lua_error(L));
5824
5825 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5826 return 1;
5827}
5828
5829/* This function set the method. */
5830static int hlua_http_req_set_path(lua_State *L)
5831{
5832 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5833 size_t name_len;
5834 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5835
5836 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5837 WILL_LJMP(lua_error(L));
5838
5839 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5840 return 1;
5841}
5842
5843/* This function set the query-string. */
5844static int hlua_http_req_set_query(lua_State *L)
5845{
5846 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5847 size_t name_len;
5848 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5849
5850 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5851 WILL_LJMP(lua_error(L));
5852
5853 /* Check length. */
5854 if (name_len > trash.size - 1) {
5855 lua_pushboolean(L, 0);
5856 return 1;
5857 }
5858
5859 /* Add the mark question as prefix. */
5860 chunk_reset(&trash);
5861 trash.area[trash.data++] = '?';
5862 memcpy(trash.area + trash.data, name, name_len);
5863 trash.data += name_len;
5864
5865 lua_pushboolean(L,
5866 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5867 return 1;
5868}
5869
5870/* This function set the uri. */
5871static int hlua_http_req_set_uri(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 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5881 return 1;
5882}
5883
5884/* This function set the response code & optionally reason. */
5885static int hlua_http_res_set_status(lua_State *L)
5886{
5887 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5888 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5889 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5890 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5891
5892 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5893 WILL_LJMP(lua_error(L));
5894
5895 http_res_set_status(code, reason, htxn->s);
5896 return 0;
5897}
5898
5899/*
5900 *
5901 *
5902 * Class HTTPMessage
5903 *
5904 *
5905 */
5906
5907/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5908 * otherwise it throws an error.
5909 */
5910__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5911{
5912 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5913}
5914
5915/* Creates and pushes on the stack a HTTP object according with a current TXN.
5916 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005917static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005918{
5919 /* Check stack size. */
5920 if (!lua_checkstack(L, 3))
5921 return 0;
5922
5923 lua_newtable(L);
5924 lua_pushlightuserdata(L, msg);
5925 lua_rawseti(L, -2, 0);
5926
5927 /* Create the "channel" field that contains the request channel object. */
5928 lua_pushstring(L, "channel");
5929 if (!hlua_channel_new(L, msg->chn))
5930 return 0;
5931 lua_rawset(L, -3);
5932
5933 /* Pop a class stream metatable and affect it to the table. */
5934 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5935 lua_setmetatable(L, -2);
5936
5937 return 1;
5938}
5939
5940/* Helper function returning a filter attached to the HTTP message at the
5941 * position <ud> in the stack, filling the current offset and length of the
5942 * filter. If no filter is attached, NULL is returned and <offet> and <len> are
5943 * filled with output and input length respectively.
5944 */
5945static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5946{
5947 struct channel *chn = msg->chn;
5948 struct htx *htx = htxbuf(&chn->buf);
5949 struct filter *filter = NULL;
5950
5951 *offset = co_data(msg->chn);
5952 *len = htx->data - co_data(msg->chn);
5953
5954 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5955 filter = lua_touserdata (L, -1);
5956 if (msg->msg_state >= HTTP_MSG_DATA) {
5957 struct hlua_flt_ctx *flt_ctx = filter->ctx;
5958
5959 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
5960 *len = flt_ctx->cur_len[CHN_IDX(chn)];
5961 }
5962 }
5963
5964 lua_pop(L, 1);
5965 return filter;
5966}
5967
5968/* Returns true if the channel attached to the HTTP message is the response
5969 * channel.
5970 */
5971__LJMP static int hlua_http_msg_is_resp(lua_State *L)
5972{
5973 struct http_msg *msg;
5974
5975 MAY_LJMP(check_args(L, 1, "is_resp"));
5976 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
5977
5978 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
5979 return 1;
5980}
5981
5982/* Returns an array containing the elements status-line of the HTTP message. It relies
5983 * on hlua_http_get_stline().
5984 */
5985__LJMP static int hlua_http_msg_get_stline(lua_State *L)
5986{
5987 struct http_msg *msg;
5988 struct htx *htx;
5989 struct htx_sl *sl;
5990
5991 MAY_LJMP(check_args(L, 1, "get_stline"));
5992 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
5993
5994 if (msg->msg_state > HTTP_MSG_BODY)
5995 WILL_LJMP(lua_error(L));
5996
5997 htx = htxbuf(&msg->chn->buf);
5998 sl = http_get_stline(htx);
5999 if (!sl)
6000 return 0;
6001 return hlua_http_get_stline(L, sl);
6002}
6003
6004/* Returns an array containing all headers of the HTTP message. it relies on
6005 * hlua_http_get_headers().
6006 */
6007__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6008{
6009 struct http_msg *msg;
6010
6011 MAY_LJMP(check_args(L, 1, "get_headers"));
6012 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6013
6014 if (msg->msg_state > HTTP_MSG_BODY)
6015 WILL_LJMP(lua_error(L));
6016
6017 return hlua_http_get_headers(L, msg);
6018}
6019
6020/* Deletes all occurrences of an header in the HTTP message matching on its
6021 * name. It relies on hlua_http_del_hdr().
6022 */
6023__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6024{
6025 struct http_msg *msg;
6026
6027 MAY_LJMP(check_args(L, 2, "del_header"));
6028 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6029
6030 if (msg->msg_state > HTTP_MSG_BODY)
6031 WILL_LJMP(lua_error(L));
6032
6033 return hlua_http_del_hdr(L, msg);
6034}
6035
6036/* Matches the full value line of all occurences of an header in the HTTP
6037 * message given its name against a regex and replaces it if it matches. It
6038 * relies on hlua_http_rep_hdr().
6039 */
6040__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6041{
6042 struct http_msg *msg;
6043
6044 MAY_LJMP(check_args(L, 4, "rep_header"));
6045 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6046
6047 if (msg->msg_state > HTTP_MSG_BODY)
6048 WILL_LJMP(lua_error(L));
6049
6050 return hlua_http_rep_hdr(L, msg, 1);
6051}
6052
6053/* Matches all comma-separated values of all occurences of an header in the HTTP
6054 * message given its name against a regex and replaces it if it matches. It
6055 * relies on hlua_http_rep_hdr().
6056 */
6057__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6058{
6059 struct http_msg *msg;
6060
6061 MAY_LJMP(check_args(L, 4, "rep_value"));
6062 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6063
6064 if (msg->msg_state > HTTP_MSG_BODY)
6065 WILL_LJMP(lua_error(L));
6066
6067 return hlua_http_rep_hdr(L, msg, 0);
6068}
6069
6070/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6071__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6072{
6073 struct http_msg *msg;
6074
6075 MAY_LJMP(check_args(L, 3, "add_header"));
6076 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6077
6078 if (msg->msg_state > HTTP_MSG_BODY)
6079 WILL_LJMP(lua_error(L));
6080
6081 return hlua_http_add_hdr(L, msg);
6082}
6083
6084/* Add an header in the HTTP message removing existing headers with the same
6085 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6086 */
6087__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6088{
6089 struct http_msg *msg;
6090
6091 MAY_LJMP(check_args(L, 3, "set_header"));
6092 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6093
6094 if (msg->msg_state > HTTP_MSG_BODY)
6095 WILL_LJMP(lua_error(L));
6096
6097 hlua_http_del_hdr(L, msg);
6098 return hlua_http_add_hdr(L, msg);
6099}
6100
6101/* Rewrites the request method. It relies on http_req_replace_stline(). */
6102__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6103{
6104 struct stream *s;
6105 struct http_msg *msg;
6106 const char *name;
6107 size_t name_len;
6108
6109 MAY_LJMP(check_args(L, 2, "set_method"));
6110 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6111 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6112
6113 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6114 WILL_LJMP(lua_error(L));
6115
6116 s = chn_strm(msg->chn);
6117 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6118 return 1;
6119}
6120
6121/* Rewrites the request path. It relies on http_req_replace_stline(). */
6122__LJMP static int hlua_http_msg_set_path(lua_State *L)
6123{
6124 struct stream *s;
6125 struct http_msg *msg;
6126 const char *name;
6127 size_t name_len;
6128
6129 MAY_LJMP(check_args(L, 2, "set_path"));
6130 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6131 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6132
6133 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6134 WILL_LJMP(lua_error(L));
6135
6136 s = chn_strm(msg->chn);
6137 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6138 return 1;
6139}
6140
6141/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6142__LJMP static int hlua_http_msg_set_query(lua_State *L)
6143{
6144 struct stream *s;
6145 struct http_msg *msg;
6146 const char *name;
6147 size_t name_len;
6148
6149 MAY_LJMP(check_args(L, 2, "set_query"));
6150 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6151 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6152
6153 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6154 WILL_LJMP(lua_error(L));
6155
6156 /* Check length. */
6157 if (name_len > trash.size - 1) {
6158 lua_pushboolean(L, 0);
6159 return 1;
6160 }
6161
6162 /* Add the mark question as prefix. */
6163 chunk_reset(&trash);
6164 trash.area[trash.data++] = '?';
6165 memcpy(trash.area + trash.data, name, name_len);
6166 trash.data += name_len;
6167
6168 s = chn_strm(msg->chn);
6169 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6170 return 1;
6171}
6172
6173/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6174__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6175{
6176 struct stream *s;
6177 struct http_msg *msg;
6178 const char *name;
6179 size_t name_len;
6180
6181 MAY_LJMP(check_args(L, 2, "set_uri"));
6182 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6183 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6184
6185 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6186 WILL_LJMP(lua_error(L));
6187
6188 s = chn_strm(msg->chn);
6189 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6190 return 1;
6191}
6192
6193/* Rewrites the response status code. It relies on http_res_set_status(). */
6194__LJMP static int hlua_http_msg_set_status(lua_State *L)
6195{
6196 struct http_msg *msg;
6197 unsigned int code;
6198 const char *reason;
6199 size_t reason_len;
6200
6201 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6202 code = MAY_LJMP(luaL_checkinteger(L, 2));
6203 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6204
6205 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6206 WILL_LJMP(lua_error(L));
6207
6208 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6209 return 1;
6210}
6211
6212/* Returns true if the HTTP message is full. */
6213__LJMP static int hlua_http_msg_is_full(lua_State *L)
6214{
6215 struct http_msg *msg;
6216
6217 MAY_LJMP(check_args(L, 1, "is_full"));
6218 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6219 lua_pushboolean(L, channel_full(msg->chn, 0));
6220 return 1;
6221}
6222
6223/* Returns true if the HTTP message may still receive data. */
6224__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6225{
6226 struct http_msg *msg;
6227 struct htx *htx;
6228
6229 MAY_LJMP(check_args(L, 1, "may_recv"));
6230 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6231 htx = htxbuf(&msg->chn->buf);
6232 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6233 return 1;
6234}
6235
6236/* Returns true if the HTTP message EOM was received */
6237__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6238{
6239 struct http_msg *msg;
6240 struct htx *htx;
6241
6242 MAY_LJMP(check_args(L, 1, "may_recv"));
6243 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6244 htx = htxbuf(&msg->chn->buf);
6245 lua_pushboolean(L, !htx_expect_more(htx));
6246 return 1;
6247}
6248
6249/* Returns the number of bytes available in the input side of the HTTP
6250 * message. This function never fails.
6251 */
6252__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6253{
6254 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006255 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006256
6257 MAY_LJMP(check_args(L, 1, "input"));
6258 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006259 hlua_http_msg_filter(L, 1, msg, &output, &input);
6260 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006261 return 1;
6262}
6263
6264/* Returns the number of bytes available in the output side of the HTTP
6265 * message. This function never fails.
6266 */
6267__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6268{
6269 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006270 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006271
6272 MAY_LJMP(check_args(L, 1, "output"));
6273 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006274 hlua_http_msg_filter(L, 1, msg, &output, &input);
6275 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006276 return 1;
6277}
6278
6279/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6280 * starting at the offset <offset> and put it in a string LUA variables. It
6281 * returns the length of the builded string. It stops on the first non-DATA HTX
6282 * block. This function is called during the payload filtering, so the headers
6283 * are already scheduled for output (from the filter point of view).
6284 */
6285static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6286{
6287 struct htx *htx = htxbuf(&msg->chn->buf);
6288 struct htx_blk *blk;
6289 struct htx_ret htxret;
6290 luaL_Buffer b;
6291 int ret = 0;
6292
6293 luaL_buffinit(L, &b);
6294 htxret = htx_find_offset(htx, offset);
6295 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6296 enum htx_blk_type type = htx_get_blk_type(blk);
6297 struct ist v;
6298
6299 switch (type) {
6300 case HTX_BLK_UNUSED:
6301 break;
6302
6303 case HTX_BLK_DATA:
6304 v = htx_get_blk_value(htx, blk);
6305 v.ptr += offset;
6306 v.len -= offset;
6307 if (v.len > len)
6308 v.len = len;
6309
6310 luaL_addlstring(&b, v.ptr, v.len);
6311 ret += v.len;
6312 break;
6313
6314 default:
6315 if (!ret) {
6316 /* Remove the empty string and push nil on the stack */
6317 lua_pop(L, 1);
6318 lua_pushnil(L);
6319 }
6320 goto end;
6321 }
6322 offset = 0;
6323 }
6324
6325 luaL_pushresult(&b);
6326
6327end:
6328 return ret;
6329}
6330
6331/* Copies the string <str> to the HTTP message <msg> at the offset
6332 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
6333 * returns the amount of data written. This function is responsibile to update
6334 * the filter context.
6335 */
6336static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6337{
6338 struct htx *htx = htx_from_buf(&msg->chn->buf);
6339 struct htx_ret htxret;
6340 int /*max, */ret = 0;
6341
6342 /* Nothing to do, just return */
6343 if (unlikely(istlen(str) == 0))
6344 goto end;
6345
6346 if (istlen(str) > htx_free_data_space(htx)) {
6347 ret = -1;
6348 goto end;
6349 }
6350
6351 htxret = htx_find_offset(htx, offset);
6352 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6353 if (!htx_add_last_data(htx, str))
6354 goto end;
6355 }
6356 else {
6357 struct ist v = htx_get_blk_value(htx, htxret.blk);
6358 v.ptr += htxret.ret;
6359 v.len = 0;
6360 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6361 goto end;
6362 }
6363 ret = str.len;
6364 if (ret) {
6365 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6366 flt_update_offsets(filter, msg->chn, ret);
6367 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6368 }
6369
6370 end:
6371 htx_to_buf(htx, &msg->chn->buf);
6372 return ret;
6373}
6374
6375/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6376 * position <offset>. It stops on the first non-DATA HTX block. This function is
6377 * called during the payload filtering, so the headers are already scheduled for
6378 * output (from the filter point of view). This function is responsibile to
6379 * update the filter context.
6380 */
6381static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6382{
6383 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6384 struct htx *htx = htx_from_buf(&msg->chn->buf);
6385 struct htx_blk *blk;
6386 struct htx_ret htxret;
6387 size_t ret = 0;
6388
6389 /* Be sure <len> is always the amount of DATA to remove */
6390 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6391 htx_truncate(htx, offset);
6392 ret = len;
6393 goto end;
6394 }
6395
6396 htxret = htx_find_offset(htx, offset);
6397 blk = htxret.blk;
6398 if (htxret.ret) {
6399 struct ist v;
6400
6401 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6402 goto end;
6403 v = htx_get_blk_value(htx, blk);
6404 v.ptr += htxret.ret;
6405 if (v.len > len)
6406 v.len = len;
6407 blk = htx_replace_blk_value(htx, blk, v, ist2(NULL, 0));
6408 len -= v.len;
6409 ret += v.len;
6410 }
6411
6412
6413 while (blk && len) {
6414 enum htx_blk_type type = htx_get_blk_type(blk);
6415 uint32_t sz = htx_get_blksz(blk);
6416
6417 switch (type) {
6418 case HTX_BLK_UNUSED:
6419 break;
6420
6421 case HTX_BLK_DATA:
6422 if (len < sz) {
6423 htx_cut_data_blk(htx, blk, len);
6424 ret += len;
6425 goto end;
6426 }
6427 break;
6428
6429 default:
6430 goto end;
6431 }
6432
6433 /* Remove oll the data block */
6434 len -= sz;
6435 ret += sz;
6436 blk = htx_remove_blk(htx, blk);
6437 }
6438
6439end:
6440 flt_update_offsets(filter, msg->chn, -ret);
6441 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6442 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6443 * to loose the EOM flag if the message is empty.
6444 */
6445}
6446
6447/* Copies input data found in an HTTP message. Unlike the channel function used
6448 * to duplicate raw data, this one can only be called inside a filter, from
6449 * http_payload callback. So it cannot yield. An exception is returned if it is
6450 * called from another callback. If nothing was copied, a nil value is pushed on
6451 * the stack.
6452 */
6453__LJMP static int hlua_http_msg_get_body(lua_State *L)
6454{
6455 struct http_msg *msg;
6456 struct filter *filter;
6457 size_t output, input;
6458 int offset, len;
6459
6460 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6461 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6462 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6463
6464 if (msg->msg_state < HTTP_MSG_DATA)
6465 WILL_LJMP(lua_error(L));
6466
6467 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6468 if (!filter || !hlua_filter_from_payload(filter))
6469 WILL_LJMP(lua_error(L));
6470
6471 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6472 lua_pushnil(L);
6473 return 1;
6474 }
6475
6476 offset = output;
6477 if (lua_gettop(L) > 1) {
6478 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6479 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006480 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006481 offset += output;
6482 if (offset < output || offset > input + output) {
6483 lua_pushfstring(L, "offset out of range.");
6484 WILL_LJMP(lua_error(L));
6485 }
6486 }
6487 len = output + input - offset;
6488 if (lua_gettop(L) == 3) {
6489 len = MAY_LJMP(luaL_checkinteger(L, 3));
6490 if (!len)
6491 goto dup;
6492 if (len == -1)
6493 len = global.tune.bufsize;
6494 if (len < 0) {
6495 lua_pushfstring(L, "length out of range.");
6496 WILL_LJMP(lua_error(L));
6497 }
6498 }
6499
6500 dup:
6501 _hlua_http_msg_dup(msg, L, offset, len);
6502 return 1;
6503}
6504
6505/* Appends a string to the HTTP message, after all existing DATA blocks but
6506 * before the trailers, if any. It returns the amount of data written or -1 if
6507 * nothing was copied. Unlike the channel function used to append data, this one
6508 * can only be called inside a filter, from http_payload callback. So it cannot
6509 * yield. An exception is returned if it is called from another callback.
6510 */
6511__LJMP static int hlua_http_msg_append(lua_State *L)
6512{
6513 struct http_msg *msg;
6514 struct filter *filter;
6515 const char *str;
6516 size_t offset, len, sz;
6517 int ret;
6518
6519 MAY_LJMP(check_args(L, 2, "append"));
6520 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6521
6522 if (msg->msg_state < HTTP_MSG_DATA)
6523 WILL_LJMP(lua_error(L));
6524
6525 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6526 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6527 if (!filter || !hlua_filter_from_payload(filter))
6528 WILL_LJMP(lua_error(L));
6529
6530 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6531 lua_pushinteger(L, ret);
6532 return 1;
6533}
6534
6535/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6536 * returns the amount of data written or -1 if nothing was copied. Unlike the
6537 * channel function used to prepend data, this one can only be called inside a
6538 * filter, from http_payload callback. So it cannot yield. An exception is
6539 * returned if it is called from another callback.
6540 */
6541__LJMP static int hlua_http_msg_prepend(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, "prepend"));
6550 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006551
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006552 if (msg->msg_state < HTTP_MSG_DATA)
6553 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006554
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006555 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))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006558 WILL_LJMP(lua_error(L));
6559
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006560 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6561 lua_pushinteger(L, ret);
6562 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006563}
6564
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006565/* Inserts a string to the HTTP message at a given offset. By default the string
6566 * is appended at the end of DATA blocks. It returns the amount of data written
6567 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6568 * this one can only be called inside a filter, from http_payload callback. So
6569 * it cannot yield. An exception is returned if it is called from another
6570 * callback.
6571 */
6572__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006573{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006574 struct http_msg *msg;
6575 struct filter *filter;
6576 const char *str;
6577 size_t input, output, sz;
6578 int offset;
6579 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006580
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006581 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6582 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6583 MAY_LJMP(check_args(L, 2, "insert"));
6584 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006585
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006586 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006587 WILL_LJMP(lua_error(L));
6588
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006589 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6590 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6591 if (!filter || !hlua_filter_from_payload(filter))
6592 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006593
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006594 offset = input + output;
6595 if (lua_gettop(L) > 2) {
6596 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6597 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006598 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006599 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006600 if (offset < output || offset > output + input) {
6601 lua_pushfstring(L, "offset out of range.");
6602 WILL_LJMP(lua_error(L));
6603 }
6604 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006605
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006606 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6607 lua_pushinteger(L, ret);
6608 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006609}
6610
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006611/* Removes a given amount of data from the HTTP message at a given offset. By
6612 * default all DATA blocks are removed. It returns the amount of data
6613 * removed. Unlike the channel function used to remove data, this one can only
6614 * be called inside a filter, from http_payload callback. So it cannot yield. An
6615 * exception is returned if it is called from another callback.
6616 */
6617__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006618{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006619 struct http_msg *msg;
6620 struct filter *filter;
6621 size_t input, output;
6622 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006623
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006624 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6625 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6626 MAY_LJMP(check_args(L, 2, "insert"));
6627 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006628
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006629 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006630 WILL_LJMP(lua_error(L));
6631
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006632 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6633 if (!filter || !hlua_filter_from_payload(filter))
6634 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006635
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006636 offset = input + output;
6637 if (lua_gettop(L) > 2) {
6638 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6639 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006640 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006641 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006642 if (offset < output || offset > output + input) {
6643 lua_pushfstring(L, "offset out of range.");
6644 WILL_LJMP(lua_error(L));
6645 }
6646 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006647
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006648 len = output + input - offset;
6649 if (lua_gettop(L) == 4) {
6650 len = MAY_LJMP(luaL_checkinteger(L, 4));
6651 if (!len)
6652 goto end;
6653 if (len == -1)
6654 len = output + input - offset;
6655 if (len < 0 || offset + len > output + input) {
6656 lua_pushfstring(L, "length out of range.");
6657 WILL_LJMP(lua_error(L));
6658 }
6659 }
6660
6661 _hlua_http_msg_delete(msg, filter, offset, len);
6662
6663 end:
6664 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006665 return 1;
6666}
6667
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006668/* Replaces a given amount of data at the given offet by a string. By default,
6669 * all remaining data are removed, accordingly to the filter context. It returns
6670 * the amount of data written or -1 if nothing was copied. Unlike the channel
6671 * function used to replace data, this one can only be called inside a filter,
6672 * from http_payload callback. So it cannot yield. An exception is returned if
6673 * it is called from another callback.
6674 */
6675__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006676{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006677 struct http_msg *msg;
6678 struct filter *filter;
6679 struct htx *htx;
6680 const char *str;
6681 size_t input, output, sz;
6682 int offset, len;
6683 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006684
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006685 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6686 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6687 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6688
6689 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006690 WILL_LJMP(lua_error(L));
6691
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006692 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6693 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6694 if (!filter || !hlua_filter_from_payload(filter))
6695 WILL_LJMP(lua_error(L));
6696
6697 offset = output;
6698 if (lua_gettop(L) > 2) {
6699 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6700 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006701 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006702 offset += output;
6703 if (offset < output || offset > input + output) {
6704 lua_pushfstring(L, "offset out of range.");
6705 WILL_LJMP(lua_error(L));
6706 }
6707 }
6708
6709 len = output + input - offset;
6710 if (lua_gettop(L) == 4) {
6711 len = MAY_LJMP(luaL_checkinteger(L, 4));
6712 if (!len)
6713 goto set;
6714 if (len == -1)
6715 len = output + input - offset;
6716 if (len < 0 || offset + len > output + input) {
6717 lua_pushfstring(L, "length out of range.");
6718 WILL_LJMP(lua_error(L));
6719 }
6720 }
6721
6722 set:
6723 /* Be sure we can copied the string once input data will be removed. */
6724 htx = htx_from_buf(&msg->chn->buf);
6725 if (sz > htx_free_data_space(htx) + len)
6726 lua_pushinteger(L, -1);
6727 else {
6728 _hlua_http_msg_delete(msg, filter, offset, len);
6729 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6730 lua_pushinteger(L, ret);
6731 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006732 return 1;
6733}
6734
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006735/* Prepends data into an HTTP message and forward it, from the filter point of
6736 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6737 * the channel function used to send data, this one can only be called inside a
6738 * filter, from http_payload callback. So it cannot yield. An exception is
6739 * returned if it is called from another callback.
6740 */
6741__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006742{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006743 struct http_msg *msg;
6744 struct filter *filter;
6745 struct htx *htx;
6746 const char *str;
6747 size_t offset, len, sz;
6748 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006749
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006750 MAY_LJMP(check_args(L, 2, "send"));
6751 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6752
6753 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006754 WILL_LJMP(lua_error(L));
6755
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006756 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6757 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6758 if (!filter || !hlua_filter_from_payload(filter))
6759 WILL_LJMP(lua_error(L));
6760
6761 /* Return an error if the channel's output is closed */
6762 if (unlikely(channel_output_closed(msg->chn))) {
6763 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006764 return 1;
6765 }
6766
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006767 htx = htx_from_buf(&msg->chn->buf);
6768 if (sz > htx_free_data_space(htx)) {
6769 lua_pushinteger(L, -1);
6770 return 1;
6771 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006772
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006773 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6774 if (ret > 0) {
6775 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6776
6777 FLT_OFF(filter, msg->chn) += ret;
6778 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6779 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6780 }
6781
6782 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006783 return 1;
6784}
6785
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006786/* Forwards a given amount of bytes. It return -1 if the channel's output is
6787 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6788 * channel function used to forward data, this one can only be called inside a
6789 * filter, from http_payload callback. So it cannot yield. An exception is
6790 * returned if it is called from another callback. All other functions deal with
6791 * DATA block, this one not.
6792*/
6793__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006794{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006795 struct http_msg *msg;
6796 struct filter *filter;
6797 size_t offset, len;
6798 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006799
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006800 MAY_LJMP(check_args(L, 2, "forward"));
6801 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6802
6803 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006804 WILL_LJMP(lua_error(L));
6805
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006806 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6807 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6808 if (!filter || !hlua_filter_from_payload(filter))
6809 WILL_LJMP(lua_error(L));
6810
6811 /* Nothing to do, just return */
6812 if (!fwd)
6813 goto end;
6814
6815 /* Return an error if the channel's output is closed */
6816 if (unlikely(channel_output_closed(msg->chn))) {
6817 ret = -1;
6818 goto end;
6819 }
6820
6821 ret = fwd;
6822 if (ret > len)
6823 ret = len;
6824
6825 if (ret) {
6826 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6827
6828 FLT_OFF(filter, msg->chn) += ret;
6829 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6830 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6831 }
6832
6833 end:
6834 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006835 return 1;
6836}
6837
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006838/* Set EOM flag on the HTX message.
6839 *
6840 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6841 * really know how to do without this feature.
6842 */
6843__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006844{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006845 struct http_msg *msg;
6846 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006847
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006848 MAY_LJMP(check_args(L, 1, "set_eom"));
6849 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6850 htx = htxbuf(&msg->chn->buf);
6851 htx->flags |= HTX_FL_EOM;
6852 return 0;
6853}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006854
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006855/* Unset EOM flag on the HTX message.
6856 *
6857 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6858 * really know how to do without this feature.
6859 */
6860__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6861{
6862 struct http_msg *msg;
6863 struct htx *htx;
6864
6865 MAY_LJMP(check_args(L, 1, "set_eom"));
6866 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6867 htx = htxbuf(&msg->chn->buf);
6868 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006869 return 0;
6870}
6871
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006872/*
6873 *
6874 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006875 * Class TXN
6876 *
6877 *
6878 */
6879
6880/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02006881 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006882 */
6883__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
6884{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006885 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006886}
6887
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006888__LJMP static int hlua_set_var(lua_State *L)
6889{
6890 struct hlua_txn *htxn;
6891 const char *name;
6892 size_t len;
6893 struct sample smp;
6894
Tim Duesterhus4e172c92020-05-19 13:49:42 +02006895 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6896 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006897
6898 /* It is useles to retrieve the stream, but this function
6899 * runs only in a stream context.
6900 */
6901 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6902 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6903
6904 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01006905 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006906 hlua_lua2smp(L, 3, &smp);
6907
6908 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01006909 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02006910
6911 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
6912 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
6913 else
6914 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
6915
Tim Duesterhus84ebc132020-05-19 13:49:41 +02006916 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006917}
6918
Christopher Faulet85d79c92016-11-09 16:54:56 +01006919__LJMP static int hlua_unset_var(lua_State *L)
6920{
6921 struct hlua_txn *htxn;
6922 const char *name;
6923 size_t len;
6924 struct sample smp;
6925
6926 MAY_LJMP(check_args(L, 2, "unset_var"));
6927
6928 /* It is useles to retrieve the stream, but this function
6929 * runs only in a stream context.
6930 */
6931 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6932 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6933
6934 /* Unset the variable. */
6935 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02006936 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
6937 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01006938}
6939
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006940__LJMP static int hlua_get_var(lua_State *L)
6941{
6942 struct hlua_txn *htxn;
6943 const char *name;
6944 size_t len;
6945 struct sample smp;
6946
6947 MAY_LJMP(check_args(L, 2, "get_var"));
6948
6949 /* It is useles to retrieve the stream, but this function
6950 * runs only in a stream context.
6951 */
6952 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6953 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6954
Willy Tarreau7560dd42016-03-10 16:28:58 +01006955 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01006956 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006957 lua_pushnil(L);
6958 return 1;
6959 }
6960
6961 return hlua_smp2lua(L, &smp);
6962}
6963
Willy Tarreau59551662015-03-10 14:23:13 +01006964__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006965{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006966 struct hlua *hlua;
6967
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006968 MAY_LJMP(check_args(L, 2, "set_priv"));
6969
Willy Tarreau87b09662015-04-03 00:22:06 +02006970 /* It is useles to retrieve the stream, but this function
6971 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006972 */
6973 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006974
6975 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006976 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006977 if (!hlua)
6978 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006979
6980 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02006981 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006982
6983 /* Get and store new value. */
6984 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
6985 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
6986
6987 return 0;
6988}
6989
Willy Tarreau59551662015-03-10 14:23:13 +01006990__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006991{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006992 struct hlua *hlua;
6993
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006994 MAY_LJMP(check_args(L, 1, "get_priv"));
6995
Willy Tarreau87b09662015-04-03 00:22:06 +02006996 /* It is useles to retrieve the stream, but this function
6997 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006998 */
6999 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007000
7001 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007002 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007003 if (!hlua) {
7004 lua_pushnil(L);
7005 return 1;
7006 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007007
7008 /* Push configuration index in the stack. */
7009 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7010
7011 return 1;
7012}
7013
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007014/* Create stack entry containing a class TXN. This function
7015 * return 0 if the stack does not contains free slots,
7016 * otherwise it returns 1.
7017 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007018static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007019{
Willy Tarreaude491382015-04-06 11:04:28 +02007020 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007021
7022 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007023 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007024 return 0;
7025
7026 /* NOTE: The allocation never fails. The failure
7027 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007028 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007029 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007030 /* Create the object: obj[0] = userdata. */
7031 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007032 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007033 lua_rawseti(L, -2, 0);
7034
Willy Tarreaude491382015-04-06 11:04:28 +02007035 htxn->s = s;
7036 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007037 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007038 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007039
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007040 /* Create the "f" field that contains a list of fetches. */
7041 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007042 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007043 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007044 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007045
7046 /* Create the "sf" field that contains a list of stringsafe fetches. */
7047 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007048 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007049 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007050 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007051
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007052 /* Create the "c" field that contains a list of converters. */
7053 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007054 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007055 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007056 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007057
7058 /* Create the "sc" field that contains a list of stringsafe converters. */
7059 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007060 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007061 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007062 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007063
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007064 /* Create the "req" field that contains the request channel object. */
7065 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007066 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007067 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007068 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007069
7070 /* Create the "res" field that contains the response channel object. */
7071 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007072 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007073 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007074 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007075
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007076 /* Creates the HTTP object is the current proxy allows http. */
7077 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007078 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007079 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007080 return 0;
7081 }
7082 else
7083 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007084 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007085
Christopher Faulet78c35472020-02-26 17:14:08 +01007086 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7087 /* HTTPMessage object are created when a lua TXN is created from
7088 * a filter context only
7089 */
7090
7091 /* Creates the HTTP-Request object is the current proxy allows http. */
7092 lua_pushstring(L, "http_req");
7093 if (p->mode == PR_MODE_HTTP) {
7094 if (!hlua_http_msg_new(L, &s->txn->req))
7095 return 0;
7096 }
7097 else
7098 lua_pushnil(L);
7099 lua_rawset(L, -3);
7100
7101 /* Creates the HTTP-Response object is the current proxy allows http. */
7102 lua_pushstring(L, "http_res");
7103 if (p->mode == PR_MODE_HTTP) {
7104 if (!hlua_http_msg_new(L, &s->txn->rsp))
7105 return 0;
7106 }
7107 else
7108 lua_pushnil(L);
7109 lua_rawset(L, -3);
7110 }
7111
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007112 /* Pop a class sesison metatable and affect it to the userdata. */
7113 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7114 lua_setmetatable(L, -2);
7115
7116 return 1;
7117}
7118
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007119__LJMP static int hlua_txn_deflog(lua_State *L)
7120{
7121 const char *msg;
7122 struct hlua_txn *htxn;
7123
7124 MAY_LJMP(check_args(L, 2, "deflog"));
7125 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7126 msg = MAY_LJMP(luaL_checkstring(L, 2));
7127
7128 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7129 return 0;
7130}
7131
7132__LJMP static int hlua_txn_log(lua_State *L)
7133{
7134 int level;
7135 const char *msg;
7136 struct hlua_txn *htxn;
7137
7138 MAY_LJMP(check_args(L, 3, "log"));
7139 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7140 level = MAY_LJMP(luaL_checkinteger(L, 2));
7141 msg = MAY_LJMP(luaL_checkstring(L, 3));
7142
7143 if (level < 0 || level >= NB_LOG_LEVELS)
7144 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7145
7146 hlua_sendlog(htxn->s->be, level, msg);
7147 return 0;
7148}
7149
7150__LJMP static int hlua_txn_log_debug(lua_State *L)
7151{
7152 const char *msg;
7153 struct hlua_txn *htxn;
7154
7155 MAY_LJMP(check_args(L, 2, "Debug"));
7156 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7157 msg = MAY_LJMP(luaL_checkstring(L, 2));
7158 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7159 return 0;
7160}
7161
7162__LJMP static int hlua_txn_log_info(lua_State *L)
7163{
7164 const char *msg;
7165 struct hlua_txn *htxn;
7166
7167 MAY_LJMP(check_args(L, 2, "Info"));
7168 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7169 msg = MAY_LJMP(luaL_checkstring(L, 2));
7170 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7171 return 0;
7172}
7173
7174__LJMP static int hlua_txn_log_warning(lua_State *L)
7175{
7176 const char *msg;
7177 struct hlua_txn *htxn;
7178
7179 MAY_LJMP(check_args(L, 2, "Warning"));
7180 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7181 msg = MAY_LJMP(luaL_checkstring(L, 2));
7182 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7183 return 0;
7184}
7185
7186__LJMP static int hlua_txn_log_alert(lua_State *L)
7187{
7188 const char *msg;
7189 struct hlua_txn *htxn;
7190
7191 MAY_LJMP(check_args(L, 2, "Alert"));
7192 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7193 msg = MAY_LJMP(luaL_checkstring(L, 2));
7194 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7195 return 0;
7196}
7197
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007198__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7199{
7200 struct hlua_txn *htxn;
7201 int ll;
7202
7203 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7204 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7205 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7206
7207 if (ll < 0 || ll > 7)
7208 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7209
7210 htxn->s->logs.level = ll;
7211 return 0;
7212}
7213
7214__LJMP static int hlua_txn_set_tos(lua_State *L)
7215{
7216 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007217 int tos;
7218
7219 MAY_LJMP(check_args(L, 2, "set_tos"));
7220 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7221 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7222
Willy Tarreau1a18b542018-12-11 16:37:42 +01007223 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007224 return 0;
7225}
7226
7227__LJMP static int hlua_txn_set_mark(lua_State *L)
7228{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007229 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007230 int mark;
7231
7232 MAY_LJMP(check_args(L, 2, "set_mark"));
7233 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7234 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7235
Lukas Tribus579e3e32019-08-11 18:03:45 +02007236 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007237 return 0;
7238}
7239
Patrick Hemmer268a7072018-05-11 12:52:31 -04007240__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7241{
7242 struct hlua_txn *htxn;
7243
7244 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7245 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7246 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7247 return 0;
7248}
7249
7250__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7251{
7252 struct hlua_txn *htxn;
7253
7254 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7255 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7256 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7257 return 0;
7258}
7259
Christopher Faulet700d9e82020-01-31 12:21:52 +01007260/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007261 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007262 * message and terminate the transaction. It returns 1 on success and 0 on
7263 * error. The Reply must be on top of the stack.
7264 */
7265__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7266{
7267 struct htx *htx;
7268 struct htx_sl *sl;
7269 struct h1m h1m;
7270 const char *status, *reason, *body;
7271 size_t status_len, reason_len, body_len;
7272 int ret, code, flags;
7273
7274 code = 200;
7275 status = "200";
7276 status_len = 3;
7277 ret = lua_getfield(L, -1, "status");
7278 if (ret == LUA_TNUMBER) {
7279 code = lua_tointeger(L, -1);
7280 status = lua_tolstring(L, -1, &status_len);
7281 }
7282 lua_pop(L, 1);
7283
7284 reason = http_get_reason(code);
7285 reason_len = strlen(reason);
7286 ret = lua_getfield(L, -1, "reason");
7287 if (ret == LUA_TSTRING)
7288 reason = lua_tolstring(L, -1, &reason_len);
7289 lua_pop(L, 1);
7290
7291 body = NULL;
7292 body_len = 0;
7293 ret = lua_getfield(L, -1, "body");
7294 if (ret == LUA_TSTRING)
7295 body = lua_tolstring(L, -1, &body_len);
7296 lua_pop(L, 1);
7297
7298 /* Prepare the response before inserting the headers */
7299 h1m_init_res(&h1m);
7300 htx = htx_from_buf(&s->res.buf);
7301 channel_htx_truncate(&s->res, htx);
7302 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7303 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7304 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7305 ist2(status, status_len), ist2(reason, reason_len));
7306 }
7307 else {
7308 flags = HTX_SL_F_IS_RESP;
7309 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7310 ist2(status, status_len), ist2(reason, reason_len));
7311 }
7312 if (!sl)
7313 goto fail;
7314 sl->info.res.status = code;
7315
7316 /* Push in the stack the "headers" entry. */
7317 ret = lua_getfield(L, -1, "headers");
7318 if (ret != LUA_TTABLE)
7319 goto skip_headers;
7320
7321 lua_pushnil(L);
7322 while (lua_next(L, -2) != 0) {
7323 struct ist name, value;
7324 const char *n, *v;
7325 size_t nlen, vlen;
7326
7327 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7328 /* Skip element if the key is not a string or if the value is not a table */
7329 goto next_hdr;
7330 }
7331
7332 n = lua_tolstring(L, -2, &nlen);
7333 name = ist2(n, nlen);
7334 if (isteqi(name, ist("content-length"))) {
7335 /* Always skip content-length header. It will be added
7336 * later with the correct len
7337 */
7338 goto next_hdr;
7339 }
7340
7341 /* Loop on header's values */
7342 lua_pushnil(L);
7343 while (lua_next(L, -2)) {
7344 if (!lua_isstring(L, -1)) {
7345 /* Skip the value if it is not a string */
7346 goto next_value;
7347 }
7348
7349 v = lua_tolstring(L, -1, &vlen);
7350 value = ist2(v, vlen);
7351
7352 if (isteqi(name, ist("transfer-encoding")))
7353 h1_parse_xfer_enc_header(&h1m, value);
7354 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7355 goto fail;
7356
7357 next_value:
7358 lua_pop(L, 1);
7359 }
7360
7361 next_hdr:
7362 lua_pop(L, 1);
7363 }
7364 skip_headers:
7365 lua_pop(L, 1);
7366
7367 /* Update h1m flags: CLEN is set if CHNK is not present */
7368 if (!(h1m.flags & H1_MF_CHNK)) {
7369 const char *clen = ultoa(body_len);
7370
7371 h1m.flags |= H1_MF_CLEN;
7372 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7373 goto fail;
7374 }
7375 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7376 h1m.flags |= H1_MF_XFER_LEN;
7377
7378 /* Update HTX start-line flags */
7379 if (h1m.flags & H1_MF_XFER_ENC)
7380 flags |= HTX_SL_F_XFER_ENC;
7381 if (h1m.flags & H1_MF_XFER_LEN) {
7382 flags |= HTX_SL_F_XFER_LEN;
7383 if (h1m.flags & H1_MF_CHNK)
7384 flags |= HTX_SL_F_CHNK;
7385 else if (h1m.flags & H1_MF_CLEN)
7386 flags |= HTX_SL_F_CLEN;
7387 if (h1m.body_len == 0)
7388 flags |= HTX_SL_F_BODYLESS;
7389 }
7390 sl->flags |= flags;
7391
7392
7393 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007394 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007395 goto fail;
7396
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007397 htx->flags |= HTX_FL_EOM;
7398
Christopher Faulet700d9e82020-01-31 12:21:52 +01007399 /* Now, forward the response and terminate the transaction */
7400 s->txn->status = code;
7401 htx_to_buf(htx, &s->res.buf);
7402 if (!http_forward_proxy_resp(s, 1))
7403 goto fail;
7404
7405 return 1;
7406
7407 fail:
7408 channel_htx_truncate(&s->res, htx);
7409 return 0;
7410}
7411
7412/* Terminate a transaction if called from a lua action. For TCP streams,
7413 * processing is just aborted. Nothing is returned to the client and all
7414 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7415 * is forwarded to the client before terminating the transaction. On success,
7416 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7417 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7418 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007419 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007420__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007421{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007422 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007423 struct stream *s;
7424 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007425
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007426 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007427
Christopher Faulet700d9e82020-01-31 12:21:52 +01007428 /* If the flags NOTERM is set, we cannot terminate the session, so we
7429 * just end the execution of the current lua code. */
7430 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007431 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007432
Christopher Faulet700d9e82020-01-31 12:21:52 +01007433 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007434 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007435 struct channel *req = &s->req;
7436 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007437
Christopher Faulet700d9e82020-01-31 12:21:52 +01007438 channel_auto_read(req);
7439 channel_abort(req);
7440 channel_auto_close(req);
7441 channel_erase(req);
7442
7443 res->wex = tick_add_ifset(now_ms, res->wto);
7444 channel_auto_read(res);
7445 channel_auto_close(res);
7446 channel_shutr_now(res);
7447
7448 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7449 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007450 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007451
Christopher Faulet700d9e82020-01-31 12:21:52 +01007452 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7453 /* No reply or invalid reply */
7454 s->txn->status = 0;
7455 http_reply_and_close(s, 0, NULL);
7456 }
7457 else {
7458 /* Remove extra args to have the reply on top of the stack */
7459 if (lua_gettop(L) > 2)
7460 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007461
Christopher Faulet700d9e82020-01-31 12:21:52 +01007462 if (!hlua_txn_forward_reply(L, s)) {
7463 if (!(s->flags & SF_ERR_MASK))
7464 s->flags |= SF_ERR_PRXCOND;
7465 lua_pushinteger(L, ACT_RET_ERR);
7466 WILL_LJMP(hlua_done(L));
7467 return 0; /* Never reached */
7468 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007469 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007470
Christopher Faulet700d9e82020-01-31 12:21:52 +01007471 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7472 if (htxn->dir == SMP_OPT_DIR_REQ) {
7473 /* let's log the request time */
7474 s->logs.tv_request = now;
7475 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007476 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007477 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007478
Christopher Faulet700d9e82020-01-31 12:21:52 +01007479 done:
7480 if (!(s->flags & SF_ERR_MASK))
7481 s->flags |= SF_ERR_LOCAL;
7482 if (!(s->flags & SF_FINST_MASK))
7483 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007484
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007485 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7486 lua_pushinteger(L, -1);
7487 else
7488 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007489 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007490 return 0;
7491}
7492
Christopher Faulet700d9e82020-01-31 12:21:52 +01007493/*
7494 *
7495 *
7496 * Class REPLY
7497 *
7498 *
7499 */
7500
7501/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
7502 * free slots, the function fails and returns 0;
7503 */
7504static int hlua_txn_reply_new(lua_State *L)
7505{
7506 struct hlua_txn *htxn;
7507 const char *reason, *body = NULL;
7508 int ret, status;
7509
7510 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007511 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007512 hlua_pusherror(L, "txn object is not an HTTP transaction.");
7513 WILL_LJMP(lua_error(L));
7514 }
7515
7516 /* Default value */
7517 status = 200;
7518 reason = http_get_reason(status);
7519
7520 if (lua_istable(L, 2)) {
7521 /* load status and reason from the table argument at index 2 */
7522 ret = lua_getfield(L, 2, "status");
7523 if (ret == LUA_TNIL)
7524 goto reason;
7525 else if (ret != LUA_TNUMBER) {
7526 /* invalid status: ignore the reason */
7527 goto body;
7528 }
7529 status = lua_tointeger(L, -1);
7530
7531 reason:
7532 lua_pop(L, 1); /* restore the stack: remove status */
7533 ret = lua_getfield(L, 2, "reason");
7534 if (ret == LUA_TSTRING)
7535 reason = lua_tostring(L, -1);
7536
7537 body:
7538 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
7539 ret = lua_getfield(L, 2, "body");
7540 if (ret == LUA_TSTRING)
7541 body = lua_tostring(L, -1);
7542 lua_pop(L, 1); /* restore the stack: remove body */
7543 }
7544
7545 /* Create the Reply table */
7546 lua_newtable(L);
7547
7548 /* Add status element */
7549 lua_pushstring(L, "status");
7550 lua_pushinteger(L, status);
7551 lua_settable(L, -3);
7552
7553 /* Add reason element */
7554 reason = http_get_reason(status);
7555 lua_pushstring(L, "reason");
7556 lua_pushstring(L, reason);
7557 lua_settable(L, -3);
7558
7559 /* Add body element, nil if undefined */
7560 lua_pushstring(L, "body");
7561 if (body)
7562 lua_pushstring(L, body);
7563 else
7564 lua_pushnil(L);
7565 lua_settable(L, -3);
7566
7567 /* Add headers element */
7568 lua_pushstring(L, "headers");
7569 lua_newtable(L);
7570
7571 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7572 if (lua_istable(L, 2)) {
7573 /* load headers from the table argument at index 2. If it is a table, copy it. */
7574 ret = lua_getfield(L, 2, "headers");
7575 if (ret == LUA_TTABLE) {
7576 /* stack: [ ... <headers:table>, <table> ] */
7577 lua_pushnil(L);
7578 while (lua_next(L, -2) != 0) {
7579 /* stack: [ ... <headers:table>, <table>, k, v] */
7580 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
7581 /* invalid value type, skip it */
7582 lua_pop(L, 1);
7583 continue;
7584 }
7585
7586
7587 /* Duplicate the key and swap it with the value. */
7588 lua_pushvalue(L, -2);
7589 lua_insert(L, -2);
7590 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
7591
7592 lua_newtable(L);
7593 lua_insert(L, -2);
7594 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
7595
7596 if (lua_isstring(L, -1)) {
7597 /* push the value in the inner table */
7598 lua_rawseti(L, -2, 1);
7599 }
7600 else { /* table */
7601 lua_pushnil(L);
7602 while (lua_next(L, -2) != 0) {
7603 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
7604 if (!lua_isstring(L, -1)) {
7605 /* invalid value type, skip it*/
7606 lua_pop(L, 1);
7607 continue;
7608 }
7609 /* push the value in the inner table */
7610 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
7611 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
7612 }
7613 lua_pop(L, 1);
7614 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
7615 }
7616
7617 /* push (k,v) on the stack in the headers table:
7618 * stack: [ ... <headers:table>, <table>, k, k, v ]
7619 */
7620 lua_settable(L, -5);
7621 /* stack: [ ... <headers:table>, <table>, k ] */
7622 }
7623 }
7624 lua_pop(L, 1);
7625 }
7626 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7627 lua_settable(L, -3);
7628 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
7629
7630 /* Pop a class sesison metatable and affect it to the userdata. */
7631 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
7632 lua_setmetatable(L, -2);
7633 return 1;
7634}
7635
7636/* Set the reply status code, and optionally the reason. If no reason is
7637 * provided, the default one corresponding to the status code is used.
7638 */
7639__LJMP static int hlua_txn_reply_set_status(lua_State *L)
7640{
7641 int status = MAY_LJMP(luaL_checkinteger(L, 2));
7642 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
7643
7644 /* First argument (self) must be a table */
7645 luaL_checktype(L, 1, LUA_TTABLE);
7646
7647 if (status < 100 || status > 599) {
7648 lua_pushboolean(L, 0);
7649 return 1;
7650 }
7651 if (!reason)
7652 reason = http_get_reason(status);
7653
7654 lua_pushinteger(L, status);
7655 lua_setfield(L, 1, "status");
7656
7657 lua_pushstring(L, reason);
7658 lua_setfield(L, 1, "reason");
7659
7660 lua_pushboolean(L, 1);
7661 return 1;
7662}
7663
7664/* Add a header into the reply object. Each header name is associated to an
7665 * array of values in the "headers" table. If the header name is not found, a
7666 * new entry is created.
7667 */
7668__LJMP static int hlua_txn_reply_add_header(lua_State *L)
7669{
7670 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7671 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
7672 int ret;
7673
7674 /* First argument (self) must be a table */
7675 luaL_checktype(L, 1, LUA_TTABLE);
7676
7677 /* Push in the stack the "headers" entry. */
7678 ret = lua_getfield(L, 1, "headers");
7679 if (ret != LUA_TTABLE) {
7680 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
7681 WILL_LJMP(lua_error(L));
7682 }
7683
7684 /* check if the header is already registered. If not, register it. */
7685 ret = lua_getfield(L, -1, name);
7686 if (ret == LUA_TNIL) {
7687 /* Entry not found. */
7688 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
7689
7690 /* Insert the new header name in the array in the top of the stack.
7691 * It left the new array in the top of the stack.
7692 */
7693 lua_newtable(L);
7694 lua_pushstring(L, name);
7695 lua_pushvalue(L, -2);
7696 lua_settable(L, -4);
7697 }
7698 else if (ret != LUA_TTABLE) {
7699 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
7700 WILL_LJMP(lua_error(L));
7701 }
7702
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07007703 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01007704 * the header value as new entry.
7705 */
7706 lua_pushstring(L, value);
7707 ret = lua_rawlen(L, -2);
7708 lua_rawseti(L, -2, ret + 1);
7709
7710 lua_pushboolean(L, 1);
7711 return 1;
7712}
7713
7714/* Remove all occurrences of a given header name. */
7715__LJMP static int hlua_txn_reply_del_header(lua_State *L)
7716{
7717 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7718 int ret;
7719
7720 /* First argument (self) must be a table */
7721 luaL_checktype(L, 1, LUA_TTABLE);
7722
7723 /* Push in the stack the "headers" entry. */
7724 ret = lua_getfield(L, 1, "headers");
7725 if (ret != LUA_TTABLE) {
7726 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
7727 WILL_LJMP(lua_error(L));
7728 }
7729
7730 lua_pushstring(L, name);
7731 lua_pushnil(L);
7732 lua_settable(L, -3);
7733
7734 lua_pushboolean(L, 1);
7735 return 1;
7736}
7737
7738/* Set the reply's body. Overwrite any existing entry. */
7739__LJMP static int hlua_txn_reply_set_body(lua_State *L)
7740{
7741 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
7742
7743 /* First argument (self) must be a table */
7744 luaL_checktype(L, 1, LUA_TTABLE);
7745
7746 lua_pushstring(L, payload);
7747 lua_setfield(L, 1, "body");
7748
7749 lua_pushboolean(L, 1);
7750 return 1;
7751}
7752
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007753__LJMP static int hlua_log(lua_State *L)
7754{
7755 int level;
7756 const char *msg;
7757
7758 MAY_LJMP(check_args(L, 2, "log"));
7759 level = MAY_LJMP(luaL_checkinteger(L, 1));
7760 msg = MAY_LJMP(luaL_checkstring(L, 2));
7761
7762 if (level < 0 || level >= NB_LOG_LEVELS)
7763 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7764
7765 hlua_sendlog(NULL, level, msg);
7766 return 0;
7767}
7768
7769__LJMP static int hlua_log_debug(lua_State *L)
7770{
7771 const char *msg;
7772
7773 MAY_LJMP(check_args(L, 1, "debug"));
7774 msg = MAY_LJMP(luaL_checkstring(L, 1));
7775 hlua_sendlog(NULL, LOG_DEBUG, msg);
7776 return 0;
7777}
7778
7779__LJMP static int hlua_log_info(lua_State *L)
7780{
7781 const char *msg;
7782
7783 MAY_LJMP(check_args(L, 1, "info"));
7784 msg = MAY_LJMP(luaL_checkstring(L, 1));
7785 hlua_sendlog(NULL, LOG_INFO, msg);
7786 return 0;
7787}
7788
7789__LJMP static int hlua_log_warning(lua_State *L)
7790{
7791 const char *msg;
7792
7793 MAY_LJMP(check_args(L, 1, "warning"));
7794 msg = MAY_LJMP(luaL_checkstring(L, 1));
7795 hlua_sendlog(NULL, LOG_WARNING, msg);
7796 return 0;
7797}
7798
7799__LJMP static int hlua_log_alert(lua_State *L)
7800{
7801 const char *msg;
7802
7803 MAY_LJMP(check_args(L, 1, "alert"));
7804 msg = MAY_LJMP(luaL_checkstring(L, 1));
7805 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007806 return 0;
7807}
7808
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007809__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007810{
7811 int wakeup_ms = lua_tointeger(L, -1);
7812 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02007813 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007814 return 0;
7815}
7816
7817__LJMP static int hlua_sleep(lua_State *L)
7818{
7819 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007820 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007821
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007822 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007823
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007824 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007825 wakeup_ms = tick_add(now_ms, delay);
7826 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007827
Willy Tarreau9635e032018-10-16 17:52:55 +02007828 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007829 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007830}
7831
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007832__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007833{
7834 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007835 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007836
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007837 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007838
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007839 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007840 wakeup_ms = tick_add(now_ms, delay);
7841 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007842
Willy Tarreau9635e032018-10-16 17:52:55 +02007843 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007844 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007845}
7846
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007847/* This functionis an LUA binding. it permits to give back
7848 * the hand at the HAProxy scheduler. It is used when the
7849 * LUA processing consumes a lot of time.
7850 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007851__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007852{
7853 return 0;
7854}
7855
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007856__LJMP static int hlua_yield(lua_State *L)
7857{
Willy Tarreau9635e032018-10-16 17:52:55 +02007858 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007859 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007860}
7861
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007862/* This function change the nice of the currently executed
7863 * task. It is used set low or high priority at the current
7864 * task.
7865 */
Willy Tarreau59551662015-03-10 14:23:13 +01007866__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007867{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007868 struct hlua *hlua;
7869 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007870
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007871 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007872 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007873
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007874 /* Get hlua struct, or NULL if we execute from main lua state */
7875 hlua = hlua_gethlua(L);
7876
7877 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007878 if (!hlua || !hlua->task)
7879 return 0;
7880
7881 if (nice < -1024)
7882 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007883 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007884 nice = 1024;
7885
7886 hlua->task->nice = nice;
7887 return 0;
7888}
7889
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007890/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007891 * HAProxy task subsystem when the task is awaked. The LUA runtime can
7892 * return an E_AGAIN signal, the emmiter of this signal must set a
7893 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007894 *
7895 * Task wrapper are longjmp safe because the only one Lua code
7896 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007897 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01007898struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007899{
Olivier Houchard9f6af332018-05-25 14:04:04 +02007900 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007901 enum hlua_exec status;
7902
Christopher Faulet5bc99722018-04-25 10:34:45 +02007903 if (task->thread_mask == MAX_THREADS_MASK)
7904 task_set_affinity(task, tid_bit);
7905
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007906 /* If it is the first call to the task, we must initialize the
7907 * execution timeouts.
7908 */
7909 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007910 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007911
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007912 /* Execute the Lua code. */
7913 status = hlua_ctx_resume(hlua, 1);
7914
7915 switch (status) {
7916 /* finished or yield */
7917 case HLUA_E_OK:
7918 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007919 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02007920 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007921 break;
7922
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01007923 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01007924 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02007925 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007926 break;
7927
7928 /* finished with error. */
7929 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007930 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007931 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007932 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007933 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007934 break;
7935
7936 case HLUA_E_ERR:
7937 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007938 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007939 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007940 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007941 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007942 break;
7943 }
Emeric Brun253e53e2017-10-17 18:58:40 +02007944 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007945}
7946
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007947/* This function is an LUA binding that register LUA function to be
7948 * executed after the HAProxy configuration parsing and before the
7949 * HAProxy scheduler starts. This function expect only one LUA
7950 * argument that is a function. This function returns nothing, but
7951 * throws if an error is encountered.
7952 */
7953__LJMP static int hlua_register_init(lua_State *L)
7954{
7955 struct hlua_init_function *init;
7956 int ref;
7957
7958 MAY_LJMP(check_args(L, 1, "register_init"));
7959
7960 ref = MAY_LJMP(hlua_checkfunction(L, 1));
7961
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007962 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007963 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007964 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007965
7966 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02007967 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007968 return 0;
7969}
7970
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007971/* This functio is an LUA binding. It permits to register a task
7972 * executed in parallel of the main HAroxy activity. The task is
7973 * created and it is set in the HAProxy scheduler. It can be called
7974 * from the "init" section, "post init" or during the runtime.
7975 *
7976 * Lua prototype:
7977 *
7978 * <none> core.register_task(<function>)
7979 */
7980static int hlua_register_task(lua_State *L)
7981{
Christopher Faulet5294ec02021-04-12 12:24:47 +02007982 struct hlua *hlua = NULL;
7983 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007984 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01007985 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007986
7987 MAY_LJMP(check_args(L, 1, "register_task"));
7988
7989 ref = MAY_LJMP(hlua_checkfunction(L, 1));
7990
Thierry Fournier75fc0292020-11-28 13:18:56 +01007991 /* Get the reference state. If the reference is NULL, L is the master
7992 * state, otherwise hlua->T is.
7993 */
7994 hlua = hlua_gethlua(L);
7995 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01007996 /* we are in runtime processing */
7997 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01007998 else
Thierry Fournier021d9862020-11-28 23:42:03 +01007999 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008000 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008001
Willy Tarreaubafbe012017-11-24 17:34:44 +01008002 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008003 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008004 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008005 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008006
Thierry Fournier59f11be2020-11-29 00:37:41 +01008007 /* We are in the common lua state, execute the task anywhere,
8008 * otherwise, inherit the current thread identifier
8009 */
8010 if (state_id == 0)
8011 task = task_new(MAX_THREADS_MASK);
8012 else
8013 task = task_new(tid_bit);
Willy Tarreaue09101e2018-10-16 17:37:12 +02008014 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008015 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008016
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008017 task->context = hlua;
8018 task->process = hlua_process_task;
8019
Thierry Fournier021d9862020-11-28 23:42:03 +01008020 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008021 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008022
8023 /* Restore the function in the stack. */
8024 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8025 hlua->nargs = 0;
8026
8027 /* Schedule task. */
8028 task_schedule(task, now_ms);
8029
8030 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008031
8032 alloc_error:
8033 task_destroy(task);
8034 hlua_ctx_destroy(hlua);
8035 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8036 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008037}
8038
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008039/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8040 * doesn't allow "yield" functions because the HAProxy engine cannot
8041 * resume converters.
8042 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008043static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008044{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008045 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008046 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008047 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008048
Willy Tarreaube508f12016-03-10 11:47:01 +01008049 if (!stream)
8050 return 0;
8051
Willy Tarreau87b09662015-04-03 00:22:06 +02008052 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008053 * Lua context can be not initialized. This behavior
8054 * permits to save performances because a systematic
8055 * Lua initialization cause 5% performances loss.
8056 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008057 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008058 struct hlua *hlua;
8059
8060 hlua = pool_alloc(pool_head_hlua);
8061 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008062 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8063 return 0;
8064 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008065 HLUA_INIT(hlua);
8066 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008067 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008068 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8069 return 0;
8070 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008071 }
8072
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008073 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008074 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008075
8076 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008077 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008078 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8079 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008080 else
8081 error = "critical error";
8082 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008083 return 0;
8084 }
8085
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008086 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008087 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008088 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008089 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008090 return 0;
8091 }
8092
8093 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008094 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008095
8096 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008097 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008098 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008099 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008100 return 0;
8101 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008102 hlua_smp2lua(stream->hlua->T, smp);
8103 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008104
8105 /* push keywords in the stack. */
8106 if (arg_p) {
8107 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008108 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008109 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008110 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008111 return 0;
8112 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008113 hlua_arg2lua(stream->hlua->T, arg_p);
8114 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008115 }
8116 }
8117
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008118 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008119 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008120
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008121 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008122 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008123 }
8124
8125 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008126 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008127 /* finished. */
8128 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008129 /* If the stack is empty, the function fails. */
8130 if (lua_gettop(stream->hlua->T) <= 0)
8131 return 0;
8132
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008133 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008134 hlua_lua2smp(stream->hlua->T, -1, smp);
8135 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008136 return 1;
8137
8138 /* yield. */
8139 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008140 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008141 return 0;
8142
8143 /* finished with error. */
8144 case HLUA_E_ERRMSG:
8145 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008146 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008147 fcn->name, lua_tostring(stream->hlua->T, -1));
8148 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008149 return 0;
8150
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008151 case HLUA_E_ETMOUT:
8152 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8153 return 0;
8154
8155 case HLUA_E_NOMEM:
8156 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8157 return 0;
8158
8159 case HLUA_E_YIELD:
8160 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8161 return 0;
8162
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008163 case HLUA_E_ERR:
8164 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008165 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008166 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008167
8168 default:
8169 return 0;
8170 }
8171}
8172
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008173/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8174 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008175 * resume sample-fetches. This function will be called by the sample
8176 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008177 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008178static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8179 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008180{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008181 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008182 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008183 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008184 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008185
Willy Tarreaube508f12016-03-10 11:47:01 +01008186 if (!stream)
8187 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008188
Willy Tarreau87b09662015-04-03 00:22:06 +02008189 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008190 * Lua context can be not initialized. This behavior
8191 * permits to save performances because a systematic
8192 * Lua initialization cause 5% performances loss.
8193 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008194 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008195 struct hlua *hlua;
8196
8197 hlua = pool_alloc(pool_head_hlua);
8198 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008199 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8200 return 0;
8201 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008202 hlua->T = NULL;
8203 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008204 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008205 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8206 return 0;
8207 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008208 }
8209
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008210 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008211 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008212
8213 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008214 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008215 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8216 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008217 else
8218 error = "critical error";
8219 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008220 return 0;
8221 }
8222
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008223 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008224 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008225 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008226 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008227 return 0;
8228 }
8229
8230 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008231 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008232
8233 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008234 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008235 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008236 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008237 return 0;
8238 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008239 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008240
8241 /* push keywords in the stack. */
8242 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8243 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008244 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008245 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008246 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008247 return 0;
8248 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008249 hlua_arg2lua(stream->hlua->T, arg_p);
8250 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008251 }
8252
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008253 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008254 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008255
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008256 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008257 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008258 }
8259
8260 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008261 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008262 /* finished. */
8263 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008264 /* If the stack is empty, the function fails. */
8265 if (lua_gettop(stream->hlua->T) <= 0)
8266 return 0;
8267
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008268 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008269 hlua_lua2smp(stream->hlua->T, -1, smp);
8270 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008271
8272 /* Set the end of execution flag. */
8273 smp->flags &= ~SMP_F_MAY_CHANGE;
8274 return 1;
8275
8276 /* yield. */
8277 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008278 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008279 return 0;
8280
8281 /* finished with error. */
8282 case HLUA_E_ERRMSG:
8283 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008284 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008285 fcn->name, lua_tostring(stream->hlua->T, -1));
8286 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008287 return 0;
8288
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008289 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008290 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8291 return 0;
8292
8293 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008294 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8295 return 0;
8296
8297 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008298 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8299 return 0;
8300
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008301 case HLUA_E_ERR:
8302 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008303 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008304 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008305
8306 default:
8307 return 0;
8308 }
8309}
8310
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008311/* This function is an LUA binding used for registering
8312 * "sample-conv" functions. It expects a converter name used
8313 * in the haproxy configuration file, and an LUA function.
8314 */
8315__LJMP static int hlua_register_converters(lua_State *L)
8316{
8317 struct sample_conv_kw_list *sck;
8318 const char *name;
8319 int ref;
8320 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008321 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008322 struct sample_conv *sc;
8323 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008324
8325 MAY_LJMP(check_args(L, 2, "register_converters"));
8326
8327 /* First argument : converter name. */
8328 name = MAY_LJMP(luaL_checkstring(L, 1));
8329
8330 /* Second argument : lua function. */
8331 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8332
Thierry Fournierf67442e2020-11-28 20:41:07 +01008333 /* Check if the converter is already registered */
8334 trash = get_trash_chunk();
8335 chunk_printf(trash, "lua.%s", name);
8336 sc = find_sample_conv(trash->area, trash->data);
8337 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008338 fcn = sc->private;
8339 if (fcn->function_ref[hlua_state_id] != -1) {
8340 ha_warning("Trying to register converter 'lua.%s' more than once. "
8341 "This will become a hard error in version 2.5.\n", name);
8342 }
8343 fcn->function_ref[hlua_state_id] = ref;
8344 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008345 }
8346
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008347 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008348 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008349 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008350 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008351 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008352 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008353 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008354
8355 /* Fill fcn. */
8356 fcn->name = strdup(name);
8357 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008358 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008359 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008360
8361 /* List head */
8362 sck->list.n = sck->list.p = NULL;
8363
8364 /* converter keyword. */
8365 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008366 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008367 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008368 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008369
8370 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8371 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008372 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 +01008373 sck->kw[0].val_args = NULL;
8374 sck->kw[0].in_type = SMP_T_STR;
8375 sck->kw[0].out_type = SMP_T_STR;
8376 sck->kw[0].private = fcn;
8377
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008378 /* Register this new converter */
8379 sample_register_convs(sck);
8380
8381 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008382
8383 alloc_error:
8384 release_hlua_function(fcn);
8385 ha_free(&sck);
8386 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8387 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008388}
8389
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008390/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008391 * "sample-fetch" functions. It expects a converter name used
8392 * in the haproxy configuration file, and an LUA function.
8393 */
8394__LJMP static int hlua_register_fetches(lua_State *L)
8395{
8396 const char *name;
8397 int ref;
8398 int len;
8399 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008400 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008401 struct sample_fetch *sf;
8402 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008403
8404 MAY_LJMP(check_args(L, 2, "register_fetches"));
8405
8406 /* First argument : sample-fetch name. */
8407 name = MAY_LJMP(luaL_checkstring(L, 1));
8408
8409 /* Second argument : lua function. */
8410 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8411
Thierry Fournierf67442e2020-11-28 20:41:07 +01008412 /* Check if the sample-fetch is already registered */
8413 trash = get_trash_chunk();
8414 chunk_printf(trash, "lua.%s", name);
8415 sf = find_sample_fetch(trash->area, trash->data);
8416 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008417 fcn = sf->private;
8418 if (fcn->function_ref[hlua_state_id] != -1) {
8419 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8420 "This will become a hard error in version 2.5.\n", name);
8421 }
8422 fcn->function_ref[hlua_state_id] = ref;
8423 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008424 }
8425
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008426 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008427 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008428 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008429 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008430 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008431 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008432 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008433
8434 /* Fill fcn. */
8435 fcn->name = strdup(name);
8436 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008437 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008438 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008439
8440 /* List head */
8441 sfk->list.n = sfk->list.p = NULL;
8442
8443 /* sample-fetch keyword. */
8444 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008445 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008446 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008447 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008448
8449 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8450 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008451 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 +01008452 sfk->kw[0].val_args = NULL;
8453 sfk->kw[0].out_type = SMP_T_STR;
8454 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8455 sfk->kw[0].val = 0;
8456 sfk->kw[0].private = fcn;
8457
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008458 /* Register this new fetch. */
8459 sample_register_fetches(sfk);
8460
8461 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008462
8463 alloc_error:
8464 release_hlua_function(fcn);
8465 ha_free(&sfk);
8466 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8467 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008468}
8469
Christopher Faulet501465d2020-02-26 14:54:16 +01008470/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008471 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008472__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008473{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008474 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008475 unsigned int delay;
8476 unsigned int wakeup_ms;
8477
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008478 /* Get hlua struct, or NULL if we execute from main lua state */
8479 hlua = hlua_gethlua(L);
8480 if (!hlua) {
8481 return 0;
8482 }
8483
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008484 MAY_LJMP(check_args(L, 1, "wake_time"));
8485
8486 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8487 wakeup_ms = tick_add(now_ms, delay);
8488 hlua->wake_time = wakeup_ms;
8489 return 0;
8490}
8491
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008492/* This function is a wrapper to execute each LUA function declared as an action
8493 * wrapper during the initialisation period. This function may return any
8494 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8495 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8496 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008497 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008498static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02008499 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008500{
8501 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008502 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008503 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008504 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008505
8506 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008507 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
8508 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
8509 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
8510 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008511 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008512 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008513 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008514 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008515
Willy Tarreau87b09662015-04-03 00:22:06 +02008516 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008517 * Lua context can be not initialized. This behavior
8518 * permits to save performances because a systematic
8519 * Lua initialization cause 5% performances loss.
8520 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008521 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008522 struct hlua *hlua;
8523
8524 hlua = pool_alloc(pool_head_hlua);
8525 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008526 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008527 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008528 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008529 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008530 HLUA_INIT(hlua);
8531 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008532 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 +01008533 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008534 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008535 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008536 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008537 }
8538
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008539 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008540 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008541
8542 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008543 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008544 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
8545 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008546 else
8547 error = "critical error";
8548 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008549 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008550 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008551 }
8552
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008553 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008554 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008555 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008556 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008557 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008558 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008559 }
8560
8561 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008562 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 +01008563
Willy Tarreau87b09662015-04-03 00:22:06 +02008564 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008565 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008566 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008567 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008568 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008569 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008570 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008571 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008572
8573 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008574 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008575 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008576 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008577 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008578 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008579 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008580 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008581 lua_pushstring(s->hlua->T, *arg);
8582 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008583 }
8584
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008585 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008586 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008587
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008588 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008589 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008590 }
8591
8592 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01008593 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008594 /* finished. */
8595 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008596 /* Catch the return value */
8597 if (lua_gettop(s->hlua->T) > 0)
8598 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008599
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008600 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02008601 if (act_ret == ACT_RET_YIELD) {
8602 if (flags & ACT_OPT_FINAL)
8603 goto err_yield;
8604
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008605 if (dir == SMP_OPT_DIR_REQ)
8606 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8607 s->hlua->wake_time);
8608 else
8609 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8610 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008611 }
8612 goto end;
8613
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008614 /* yield. */
8615 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008616 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008617 if (dir == SMP_OPT_DIR_REQ)
8618 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8619 s->hlua->wake_time);
8620 else
8621 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8622 s->hlua->wake_time);
8623
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008624 /* Some actions can be wake up when a "write" event
8625 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008626 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008627 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02008628 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008629 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008630 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008631 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008632 act_ret = ACT_RET_YIELD;
8633 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008634
8635 /* finished with error. */
8636 case HLUA_E_ERRMSG:
8637 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008638 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008639 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008640 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008641 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008642
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008643 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008644 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008645 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008646
8647 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008648 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008649 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008650
8651 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02008652 err_yield:
8653 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008654 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008655 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008656 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008657
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008658 case HLUA_E_ERR:
8659 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008660 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008661 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008662
8663 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008664 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008665 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008666
8667 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02008668 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008669 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008670 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008671}
8672
Willy Tarreau144f84a2021-03-02 16:09:26 +01008673struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008674{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008675 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008676
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008677 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02008678 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02008679 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008680}
8681
8682static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8683{
8684 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008685 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008686 struct task *task;
8687 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008688 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008689
Willy Tarreaubafbe012017-11-24 17:34:44 +01008690 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008691 if (!hlua) {
8692 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008693 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008694 return 0;
8695 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008696 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008697 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008698 ctx->ctx.hlua_apptcp.flags = 0;
8699
8700 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008701 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008702 if (!task) {
8703 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008704 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008705 return 0;
8706 }
8707 task->nice = 0;
8708 task->context = ctx;
8709 task->process = hlua_applet_wakeup;
8710 ctx->ctx.hlua_apptcp.task = task;
8711
8712 /* In the execution wrappers linked with a stream, the
8713 * Lua context can be not initialized. This behavior
8714 * permits to save performances because a systematic
8715 * Lua initialization cause 5% performances loss.
8716 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008717 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 +02008718 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008719 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008720 return 0;
8721 }
8722
8723 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008724 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008725
8726 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008727 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008728 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8729 error = lua_tostring(hlua->T, -1);
8730 else
8731 error = "critical error";
8732 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008733 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008734 return 0;
8735 }
8736
8737 /* Check stack available size. */
8738 if (!lua_checkstack(hlua->T, 1)) {
8739 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008740 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008741 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008742 return 0;
8743 }
8744
8745 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008746 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008747
8748 /* Create and and push object stream in the stack. */
8749 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
8750 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008751 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008752 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008753 return 0;
8754 }
8755 hlua->nargs = 1;
8756
8757 /* push keywords in the stack. */
8758 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8759 if (!lua_checkstack(hlua->T, 1)) {
8760 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008761 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008762 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008763 return 0;
8764 }
8765 lua_pushstring(hlua->T, *arg);
8766 hlua->nargs++;
8767 }
8768
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008769 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008770
8771 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008772 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01008773 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008774
8775 return 1;
8776}
8777
Willy Tarreau60409db2019-08-21 14:14:50 +02008778void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008779{
8780 struct stream_interface *si = ctx->owner;
8781 struct stream *strm = si_strm(si);
8782 struct channel *res = si_ic(si);
8783 struct act_rule *rule = ctx->rule;
8784 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008785 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008786
8787 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02008788 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
8789 /* eat the whole request */
8790 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008791 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02008792 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008793
8794 /* If the stream is disconnect or closed, ldo nothing. */
8795 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8796 return;
8797
8798 /* Execute the function. */
8799 switch (hlua_ctx_resume(hlua, 1)) {
8800 /* finished. */
8801 case HLUA_E_OK:
8802 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8803
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008804 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02008805 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008806 res->flags |= CF_READ_NULL;
8807 si_shutr(si);
8808 return;
8809
8810 /* yield. */
8811 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01008812 if (hlua->wake_time != TICK_ETERNITY)
8813 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008814 return;
8815
8816 /* finished with error. */
8817 case HLUA_E_ERRMSG:
8818 /* Display log. */
8819 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008820 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008821 lua_pop(hlua->T, 1);
8822 goto error;
8823
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008824 case HLUA_E_ETMOUT:
8825 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008826 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008827 goto error;
8828
8829 case HLUA_E_NOMEM:
8830 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008831 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008832 goto error;
8833
8834 case HLUA_E_YIELD: /* unexpected */
8835 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008836 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008837 goto error;
8838
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008839 case HLUA_E_ERR:
8840 /* Display log. */
8841 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008842 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008843 goto error;
8844
8845 default:
8846 goto error;
8847 }
8848
8849error:
8850
8851 /* For all other cases, just close the stream. */
8852 si_shutw(si);
8853 si_shutr(si);
8854 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8855}
8856
8857static void hlua_applet_tcp_release(struct appctx *ctx)
8858{
Olivier Houchard3f795f72019-04-17 22:51:06 +02008859 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008860 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008861 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008862 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008863}
8864
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008865/* The function returns 1 if the initialisation is complete, 0 if
8866 * an errors occurs and -1 if more data are required for initializing
8867 * the applet.
8868 */
8869static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8870{
8871 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008872 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008873 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008874 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008875 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008876 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008877
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008878 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01008879 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008880 if (!hlua) {
8881 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008882 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008883 return 0;
8884 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008885 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008886 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008887 ctx->ctx.hlua_apphttp.left_bytes = -1;
8888 ctx->ctx.hlua_apphttp.flags = 0;
8889
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01008890 if (txn->req.flags & HTTP_MSGF_VER_11)
8891 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
8892
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008893 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008894 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008895 if (!task) {
8896 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008897 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008898 return 0;
8899 }
8900 task->nice = 0;
8901 task->context = ctx;
8902 task->process = hlua_applet_wakeup;
8903 ctx->ctx.hlua_apphttp.task = task;
8904
8905 /* In the execution wrappers linked with a stream, the
8906 * Lua context can be not initialized. This behavior
8907 * permits to save performances because a systematic
8908 * Lua initialization cause 5% performances loss.
8909 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008910 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 +02008911 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008912 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008913 return 0;
8914 }
8915
8916 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008917 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008918
8919 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008920 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008921 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8922 error = lua_tostring(hlua->T, -1);
8923 else
8924 error = "critical error";
8925 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008926 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008927 return 0;
8928 }
8929
8930 /* Check stack available size. */
8931 if (!lua_checkstack(hlua->T, 1)) {
8932 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008933 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008934 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008935 return 0;
8936 }
8937
8938 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008939 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008940
8941 /* Create and and push object stream in the stack. */
8942 if (!hlua_applet_http_new(hlua->T, ctx)) {
8943 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008944 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008945 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008946 return 0;
8947 }
8948 hlua->nargs = 1;
8949
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008950 /* push keywords in the stack. */
8951 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8952 if (!lua_checkstack(hlua->T, 1)) {
8953 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008954 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008955 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008956 return 0;
8957 }
8958 lua_pushstring(hlua->T, *arg);
8959 hlua->nargs++;
8960 }
8961
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008962 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008963
8964 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008965 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008966
8967 return 1;
8968}
8969
Willy Tarreau60409db2019-08-21 14:14:50 +02008970void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008971{
8972 struct stream_interface *si = ctx->owner;
8973 struct stream *strm = si_strm(si);
8974 struct channel *req = si_oc(si);
8975 struct channel *res = si_ic(si);
8976 struct act_rule *rule = ctx->rule;
8977 struct proxy *px = strm->be;
8978 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
8979 struct htx *req_htx, *res_htx;
8980
8981 res_htx = htx_from_buf(&res->buf);
8982
8983 /* If the stream is disconnect or closed, ldo nothing. */
8984 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8985 goto out;
8986
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008987 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008988 if (!b_size(&res->buf)) {
8989 si_rx_room_blk(si);
8990 goto out;
8991 }
8992 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01008993 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008994 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
8995
8996 /* Set the currently running flag. */
8997 if (!HLUA_IS_RUNNING(hlua) &&
8998 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02008999 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009000 si_cant_get(si);
9001 goto out;
9002 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009003 }
9004
9005 /* Executes The applet if it is not done. */
9006 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9007
9008 /* Execute the function. */
9009 switch (hlua_ctx_resume(hlua, 1)) {
9010 /* finished. */
9011 case HLUA_E_OK:
9012 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9013 break;
9014
9015 /* yield. */
9016 case HLUA_E_AGAIN:
9017 if (hlua->wake_time != TICK_ETERNITY)
9018 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009019 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009020
9021 /* finished with error. */
9022 case HLUA_E_ERRMSG:
9023 /* Display log. */
9024 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009025 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009026 lua_pop(hlua->T, 1);
9027 goto error;
9028
9029 case HLUA_E_ETMOUT:
9030 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009031 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009032 goto error;
9033
9034 case HLUA_E_NOMEM:
9035 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009036 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009037 goto error;
9038
9039 case HLUA_E_YIELD: /* unexpected */
9040 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009041 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009042 goto error;
9043
9044 case HLUA_E_ERR:
9045 /* Display log. */
9046 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009047 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009048 goto error;
9049
9050 default:
9051 goto error;
9052 }
9053 }
9054
9055 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009056 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9057 goto done;
9058
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009059 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9060 goto error;
9061
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009062 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
9063 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009064 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9065 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009066 }
9067
9068 done:
9069 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009070 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009071 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009072 si_shutr(si);
9073 }
9074
9075 /* eat the whole request */
9076 if (co_data(req)) {
9077 req_htx = htx_from_buf(&req->buf);
9078 co_htx_skip(req, req_htx, co_data(req));
9079 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009080 }
9081 }
9082
9083 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009084 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009085 return;
9086
9087 error:
9088
9089 /* If we are in HTTP mode, and we are not send any
9090 * data, return a 500 server error in best effort:
9091 * if there is no room available in the buffer,
9092 * just close the connection.
9093 */
9094 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009095 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009096
9097 channel_erase(res);
9098 res->buf.data = b_data(err);
9099 memcpy(res->buf.area, b_head(err), b_data(err));
9100 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009101 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009102 }
9103 if (!(strm->flags & SF_ERR_MASK))
9104 strm->flags |= SF_ERR_RESOURCE;
9105 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9106 goto done;
9107}
9108
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009109static void hlua_applet_http_release(struct appctx *ctx)
9110{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009111 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009112 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009113 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009114 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009115}
9116
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009117/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009118 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009119 *
9120 * This function can fail with an abort() due to an Lua critical error.
9121 * We are in the configuration parsing process of HAProxy, this abort() is
9122 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009123 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009124static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9125 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009126{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009127 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009128 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009129
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009130 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009131 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009132 if (!rule->arg.hlua_rule) {
9133 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009134 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009135 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009136
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009137 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009138 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9139 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009140 if (!rule->arg.hlua_rule->args) {
9141 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009142 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009143 }
9144
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009145 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009146 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009147
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009148 /* Expect some arguments */
9149 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009150 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009151 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009152 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009153 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009154 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009155 if (!rule->arg.hlua_rule->args[i]) {
9156 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009157 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009158 }
9159 (*cur_arg)++;
9160 }
9161 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009162
Thierry FOURNIER42148732015-09-02 17:17:33 +02009163 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009164 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009165 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009166
9167 error:
9168 if (rule->arg.hlua_rule) {
9169 if (rule->arg.hlua_rule->args) {
9170 for (i = 0; i < fcn->nargs; i++)
9171 ha_free(&rule->arg.hlua_rule->args[i]);
9172 ha_free(&rule->arg.hlua_rule->args);
9173 }
9174 ha_free(&rule->arg.hlua_rule);
9175 }
9176 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009177}
9178
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009179static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9180 struct act_rule *rule, char **err)
9181{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009182 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009183
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009184 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009185 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009186 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009187 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009188 * the call of this analyzer.
9189 */
9190 if (rule->from != ACT_F_HTTP_REQ) {
9191 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9192 return ACT_RET_PRS_ERR;
9193 }
9194
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009195 /* Memory for the rule. */
9196 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9197 if (!rule->arg.hlua_rule) {
9198 memprintf(err, "out of memory error");
9199 return ACT_RET_PRS_ERR;
9200 }
9201
9202 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009203 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009204
9205 /* TODO: later accept arguments. */
9206 rule->arg.hlua_rule->args = NULL;
9207
9208 /* Add applet pointer in the rule. */
9209 rule->applet.obj_type = OBJ_TYPE_APPLET;
9210 rule->applet.name = fcn->name;
9211 rule->applet.init = hlua_applet_http_init;
9212 rule->applet.fct = hlua_applet_http_fct;
9213 rule->applet.release = hlua_applet_http_release;
9214 rule->applet.timeout = hlua_timeout_applet;
9215
9216 return ACT_RET_PRS_OK;
9217}
9218
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009219/* This function is an LUA binding used for registering
9220 * "sample-conv" functions. It expects a converter name used
9221 * in the haproxy configuration file, and an LUA function.
9222 */
9223__LJMP static int hlua_register_action(lua_State *L)
9224{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009225 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009226 const char *name;
9227 int ref;
9228 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009229 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009230 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009231 struct buffer *trash;
9232 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009233
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009234 /* Initialise the number of expected arguments at 0. */
9235 nargs = 0;
9236
9237 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9238 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009239
9240 /* First argument : converter name. */
9241 name = MAY_LJMP(luaL_checkstring(L, 1));
9242
9243 /* Second argument : environment. */
9244 if (lua_type(L, 2) != LUA_TTABLE)
9245 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9246
9247 /* Third argument : lua function. */
9248 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9249
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009250 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009251 if (lua_gettop(L) >= 4)
9252 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9253
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009254 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009255 lua_pushnil(L);
9256 while (lua_next(L, 2) != 0) {
9257 if (lua_type(L, -1) != LUA_TSTRING)
9258 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9259
Thierry Fournierf67442e2020-11-28 20:41:07 +01009260 /* Check if action exists */
9261 trash = get_trash_chunk();
9262 chunk_printf(trash, "lua.%s", name);
9263 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9264 akw = tcp_req_cont_action(trash->area);
9265 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9266 akw = tcp_res_cont_action(trash->area);
9267 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9268 akw = action_http_req_custom(trash->area);
9269 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9270 akw = action_http_res_custom(trash->area);
9271 } else {
9272 akw = NULL;
9273 }
9274 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009275 fcn = akw->private;
9276 if (fcn->function_ref[hlua_state_id] != -1) {
9277 ha_warning("Trying to register action 'lua.%s' more than once. "
9278 "This will become a hard error in version 2.5.\n", name);
9279 }
9280 fcn->function_ref[hlua_state_id] = ref;
9281
9282 /* pop the environment string. */
9283 lua_pop(L, 1);
9284 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009285 }
9286
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009287 /* Check required environment. Only accepted "http" or "tcp". */
9288 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009289 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009290 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009291 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009292 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009293 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009294 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009295
9296 /* Fill fcn. */
9297 fcn->name = strdup(name);
9298 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009299 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009300 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009301
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009302 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009303 fcn->nargs = nargs;
9304
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009305 /* List head */
9306 akl->list.n = akl->list.p = NULL;
9307
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009308 /* action keyword. */
9309 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009310 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009311 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009312 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009313
9314 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9315
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009316 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009317 akl->kw[0].private = fcn;
9318 akl->kw[0].parse = action_register_lua;
9319
9320 /* select the action registering point. */
9321 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9322 tcp_req_cont_keywords_register(akl);
9323 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9324 tcp_res_cont_keywords_register(akl);
9325 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9326 http_req_keywords_register(akl);
9327 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9328 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009329 else {
9330 release_hlua_function(fcn);
9331 if (akl)
9332 ha_free((char **)&(akl->kw[0].kw));
9333 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009334 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009335 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9336 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009337 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009338
9339 /* pop the environment string. */
9340 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009341
9342 /* reset for next loop */
9343 akl = NULL;
9344 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009345 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009346 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009347
9348 alloc_error:
9349 release_hlua_function(fcn);
9350 ha_free(&akl);
9351 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9352 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009353}
9354
9355static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9356 struct act_rule *rule, char **err)
9357{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009358 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009359
Christopher Faulet280f85b2019-07-15 15:02:04 +02009360 if (px->mode == PR_MODE_HTTP) {
9361 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009362 return ACT_RET_PRS_ERR;
9363 }
9364
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009365 /* Memory for the rule. */
9366 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9367 if (!rule->arg.hlua_rule) {
9368 memprintf(err, "out of memory error");
9369 return ACT_RET_PRS_ERR;
9370 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009371
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009372 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009373 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009374
9375 /* TODO: later accept arguments. */
9376 rule->arg.hlua_rule->args = NULL;
9377
9378 /* Add applet pointer in the rule. */
9379 rule->applet.obj_type = OBJ_TYPE_APPLET;
9380 rule->applet.name = fcn->name;
9381 rule->applet.init = hlua_applet_tcp_init;
9382 rule->applet.fct = hlua_applet_tcp_fct;
9383 rule->applet.release = hlua_applet_tcp_release;
9384 rule->applet.timeout = hlua_timeout_applet;
9385
9386 return 0;
9387}
9388
9389/* This function is an LUA binding used for registering
9390 * "sample-conv" functions. It expects a converter name used
9391 * in the haproxy configuration file, and an LUA function.
9392 */
9393__LJMP static int hlua_register_service(lua_State *L)
9394{
9395 struct action_kw_list *akl;
9396 const char *name;
9397 const char *env;
9398 int ref;
9399 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009400 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009401 struct buffer *trash;
9402 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009403
9404 MAY_LJMP(check_args(L, 3, "register_service"));
9405
9406 /* First argument : converter name. */
9407 name = MAY_LJMP(luaL_checkstring(L, 1));
9408
9409 /* Second argument : environment. */
9410 env = MAY_LJMP(luaL_checkstring(L, 2));
9411
9412 /* Third argument : lua function. */
9413 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9414
Thierry Fournierf67442e2020-11-28 20:41:07 +01009415 /* Check for service already registered */
9416 trash = get_trash_chunk();
9417 chunk_printf(trash, "lua.%s", name);
9418 akw = service_find(trash->area);
9419 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009420 fcn = akw->private;
9421 if (fcn->function_ref[hlua_state_id] != -1) {
9422 ha_warning("Trying to register service 'lua.%s' more than once. "
9423 "This will become a hard error in version 2.5.\n", name);
9424 }
9425 fcn->function_ref[hlua_state_id] = ref;
9426 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009427 }
9428
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009429 /* Allocate and fill the sample fetch keyword struct. */
9430 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9431 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009432 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009433 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009434 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009435 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009436
9437 /* Fill fcn. */
9438 len = strlen("<lua.>") + strlen(name) + 1;
9439 fcn->name = calloc(1, len);
9440 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009441 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009442 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009443 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009444
9445 /* List head */
9446 akl->list.n = akl->list.p = NULL;
9447
9448 /* converter keyword. */
9449 len = strlen("lua.") + strlen(name) + 1;
9450 akl->kw[0].kw = calloc(1, len);
9451 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009452 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009453
9454 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9455
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009456 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009457 if (strcmp(env, "tcp") == 0)
9458 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009459 else if (strcmp(env, "http") == 0)
9460 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009461 else {
9462 release_hlua_function(fcn);
9463 if (akl)
9464 ha_free((char **)&(akl->kw[0].kw));
9465 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009466 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009467 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009468 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009469
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009470 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009471 akl->kw[0].private = fcn;
9472
9473 /* End of array. */
9474 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9475
9476 /* Register this new converter */
9477 service_keywords_register(akl);
9478
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009479 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009480
9481 alloc_error:
9482 release_hlua_function(fcn);
9483 ha_free(&akl);
9484 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9485 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009486}
9487
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009488/* This function initialises Lua cli handler. It copies the
9489 * arguments in the Lua stack and create channel IO objects.
9490 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02009491static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009492{
9493 struct hlua *hlua;
9494 struct hlua_function *fcn;
9495 int i;
9496 const char *error;
9497
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009498 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009499 appctx->ctx.hlua_cli.fcn = private;
9500
Willy Tarreaubafbe012017-11-24 17:34:44 +01009501 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009502 if (!hlua) {
9503 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009504 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009505 }
9506 HLUA_INIT(hlua);
9507 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009508
9509 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05009510 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009511 * applet_http. It is absolutely compatible.
9512 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01009513 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009514 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01009515 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009516 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009517 }
9518 appctx->ctx.hlua_cli.task->nice = 0;
9519 appctx->ctx.hlua_cli.task->context = appctx;
9520 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
9521
9522 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +01009523 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 +01009524 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009525 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009526 }
9527
9528 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009529 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009530 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9531 error = lua_tostring(hlua->T, -1);
9532 else
9533 error = "critical error";
9534 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
9535 goto error;
9536 }
9537
9538 /* Check stack available size. */
9539 if (!lua_checkstack(hlua->T, 2)) {
9540 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9541 goto error;
9542 }
9543
9544 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009545 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009546
9547 /* Once the arguments parsed, the CLI is like an AppletTCP,
9548 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009549 */
9550 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
9551 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9552 goto error;
9553 }
9554 hlua->nargs = 1;
9555
9556 /* push keywords in the stack. */
9557 for (i = 0; *args[i]; i++) {
9558 /* Check stack available size. */
9559 if (!lua_checkstack(hlua->T, 1)) {
9560 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9561 goto error;
9562 }
9563 lua_pushstring(hlua->T, args[i]);
9564 hlua->nargs++;
9565 }
9566
9567 /* We must initialize the execution timeouts. */
9568 hlua->max_time = hlua_timeout_session;
9569
9570 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009571 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009572
9573 /* It's ok */
9574 return 0;
9575
9576 /* It's not ok. */
9577error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009578 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009579 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009580 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009581 return 1;
9582}
9583
9584static int hlua_cli_io_handler_fct(struct appctx *appctx)
9585{
9586 struct hlua *hlua;
9587 struct stream_interface *si;
9588 struct hlua_function *fcn;
9589
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009590 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009591 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01009592 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009593
9594 /* If the stream is disconnect or closed, ldo nothing. */
9595 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9596 return 1;
9597
9598 /* Execute the function. */
9599 switch (hlua_ctx_resume(hlua, 1)) {
9600
9601 /* finished. */
9602 case HLUA_E_OK:
9603 return 1;
9604
9605 /* yield. */
9606 case HLUA_E_AGAIN:
9607 /* We want write. */
9608 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01009609 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009610 /* Set the timeout. */
9611 if (hlua->wake_time != TICK_ETERNITY)
9612 task_schedule(hlua->task, hlua->wake_time);
9613 return 0;
9614
9615 /* finished with error. */
9616 case HLUA_E_ERRMSG:
9617 /* Display log. */
9618 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
9619 fcn->name, lua_tostring(hlua->T, -1));
9620 lua_pop(hlua->T, 1);
9621 return 1;
9622
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009623 case HLUA_E_ETMOUT:
9624 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
9625 fcn->name);
9626 return 1;
9627
9628 case HLUA_E_NOMEM:
9629 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
9630 fcn->name);
9631 return 1;
9632
9633 case HLUA_E_YIELD: /* unexpected */
9634 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
9635 fcn->name);
9636 return 1;
9637
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009638 case HLUA_E_ERR:
9639 /* Display log. */
9640 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
9641 fcn->name);
9642 return 1;
9643
9644 default:
9645 return 1;
9646 }
9647
9648 return 1;
9649}
9650
9651static void hlua_cli_io_release_fct(struct appctx *appctx)
9652{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009653 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009654 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009655}
9656
9657/* This function is an LUA binding used for registering
9658 * new keywords in the cli. It expects a list of keywords
9659 * which are the "path". It is limited to 5 keywords. A
9660 * description of the command, a function to be executed
9661 * for the parsing and a function for io handlers.
9662 */
9663__LJMP static int hlua_register_cli(lua_State *L)
9664{
9665 struct cli_kw_list *cli_kws;
9666 const char *message;
9667 int ref_io;
9668 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009669 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009670 int index;
9671 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009672 struct buffer *trash;
9673 const char *kw[5];
9674 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009675 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009676
9677 MAY_LJMP(check_args(L, 3, "register_cli"));
9678
9679 /* First argument : an array of maximum 5 keywords. */
9680 if (!lua_istable(L, 1))
9681 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
9682
9683 /* Second argument : string with contextual message. */
9684 message = MAY_LJMP(luaL_checkstring(L, 2));
9685
9686 /* Third and fourth argument : lua function. */
9687 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
9688
Thierry Fournierf67442e2020-11-28 20:41:07 +01009689 /* Check for CLI service already registered */
9690 trash = get_trash_chunk();
9691 index = 0;
9692 lua_pushnil(L);
9693 memset(kw, 0, sizeof(kw));
9694 while (lua_next(L, 1) != 0) {
9695 if (index >= CLI_PREFIX_KW_NB)
9696 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
9697 if (lua_type(L, -1) != LUA_TSTRING)
9698 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
9699 kw[index] = lua_tostring(L, -1);
9700 if (index == 0)
9701 chunk_printf(trash, "%s", kw[index]);
9702 else
9703 chunk_appendf(trash, " %s", kw[index]);
9704 index++;
9705 lua_pop(L, 1);
9706 }
9707 cli_kw = cli_find_kw_exact((char **)kw);
9708 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009709 fcn = cli_kw->private;
9710 if (fcn->function_ref[hlua_state_id] != -1) {
9711 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
9712 "This will become a hard error in version 2.5.\n", trash->area);
9713 }
9714 fcn->function_ref[hlua_state_id] = ref_io;
9715 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009716 }
9717
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009718 /* Allocate and fill the sample fetch keyword struct. */
9719 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009720 if (!cli_kws) {
9721 errmsg = "Lua out of memory error.";
9722 goto error;
9723 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009724 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009725 if (!fcn) {
9726 errmsg = "Lua out of memory error.";
9727 goto error;
9728 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009729
9730 /* Fill path. */
9731 index = 0;
9732 lua_pushnil(L);
9733 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009734 if (index >= 5) {
9735 errmsg = "1st argument must be a table with a maximum of 5 entries";
9736 goto error;
9737 }
9738 if (lua_type(L, -1) != LUA_TSTRING) {
9739 errmsg = "1st argument must be a table filled with strings";
9740 goto error;
9741 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009742 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009743 if (!cli_kws->kw[0].str_kw[index]) {
9744 errmsg = "Lua out of memory error.";
9745 goto error;
9746 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009747 index++;
9748 lua_pop(L, 1);
9749 }
9750
9751 /* Copy help message. */
9752 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009753 if (!cli_kws->kw[0].usage) {
9754 errmsg = "Lua out of memory error.";
9755 goto error;
9756 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009757
9758 /* Fill fcn io handler. */
9759 len = strlen("<lua.cli>") + 1;
9760 for (i = 0; i < index; i++)
9761 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
9762 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009763 if (!fcn->name) {
9764 errmsg = "Lua out of memory error.";
9765 goto error;
9766 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009767 strncat((char *)fcn->name, "<lua.cli", len);
9768 for (i = 0; i < index; i++) {
9769 strncat((char *)fcn->name, ".", len);
9770 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
9771 }
9772 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +01009773 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009774
9775 /* Fill last entries. */
9776 cli_kws->kw[0].private = fcn;
9777 cli_kws->kw[0].parse = hlua_cli_parse_fct;
9778 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
9779 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
9780
9781 /* Register this new converter */
9782 cli_register_kw(cli_kws);
9783
9784 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009785
9786 error:
9787 release_hlua_function(fcn);
9788 if (cli_kws) {
9789 for (i = 0; i < index; i++)
9790 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
9791 ha_free((char **)&(cli_kws->kw[0].usage));
9792 }
9793 ha_free(&cli_kws);
9794 WILL_LJMP(luaL_error(L, errmsg));
9795 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009796}
9797
Christopher Faulet69c581a2021-05-31 08:54:04 +02009798static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
9799{
9800 struct hlua_flt_config *conf = fconf->conf;
9801 lua_State *L;
9802 int error, pos, state_id, flt_ref;
9803
9804 state_id = reg_flt_to_stack_id(conf->reg);
9805 L = hlua_states[state_id];
9806 pos = lua_gettop(L);
9807
9808 /* The filter parsing function */
9809 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
9810
9811 /* Push the filter class on the stack and resolve all callbacks */
9812 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
9813
9814 /* Duplicate the filter class so each filter will have its own copy */
9815 lua_newtable(L);
9816 lua_pushnil(L);
9817
9818 while (lua_next(L, pos+2)) {
9819 lua_pushvalue(L, -2);
9820 lua_insert(L, -2);
9821 lua_settable(L, -4);
9822 }
9823 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
9824
9825 /* Remove the original lua filter class from the stack */
9826 lua_pop(L, 1);
9827
9828 /* Push the copy on the stack */
9829 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
9830
9831 /* extra args are pushed in a table */
9832 lua_newtable(L);
9833 for (pos = 0; conf->args[pos]; pos++) {
9834 /* Check stack available size. */
9835 if (!lua_checkstack(L, 1)) {
9836 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
9837 goto error;
9838 }
9839 lua_pushstring(L, conf->args[pos]);
9840 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
9841 }
9842
9843 error = lua_pcall(L, 2, LUA_MULTRET, 0);
9844 switch (error) {
9845 case LUA_OK:
9846 /* replace the filter ref */
9847 conf->ref[state_id] = flt_ref;
9848 break;
9849 case LUA_ERRRUN:
9850 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
9851 goto error;
9852 case LUA_ERRMEM:
9853 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
9854 goto error;
9855 case LUA_ERRERR:
9856 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
9857 goto error;
9858#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
9859 case LUA_ERRGCMM:
9860 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
9861 goto error;
9862#endif
9863 default:
9864 ha_alert("Lua filter '%s' : unknonwn error : %s", conf->reg->name, lua_tostring(L, -1));
9865 goto error;
9866 }
9867
9868 lua_settop(L, 0);
9869 return 0;
9870
9871 error:
9872 lua_settop(L, 0);
9873 return -1;
9874}
9875
9876static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
9877{
9878 struct hlua_flt_config *conf = fconf->conf;
9879 lua_State *L;
9880 int state_id;
9881
9882 if (!conf)
9883 return;
9884
9885 state_id = reg_flt_to_stack_id(conf->reg);
9886 L = hlua_states[state_id];
9887 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
9888}
9889
9890static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
9891{
9892 struct hlua_flt_config *conf = fconf->conf;
9893 int state_id = reg_flt_to_stack_id(conf->reg);
9894
9895 /* Rely on per-thread init for global scripts */
9896 if (!state_id)
9897 return hlua_filter_init_per_thread(px, fconf);
9898 return 0;
9899}
9900
9901static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
9902{
9903
9904 if (fconf->conf) {
9905 struct hlua_flt_config *conf = fconf->conf;
9906 int state_id = reg_flt_to_stack_id(conf->reg);
9907 int pos;
9908
9909 /* Rely on per-thread deinit for global scripts */
9910 if (!state_id)
9911 hlua_filter_deinit_per_thread(px, fconf);
9912
9913 for (pos = 0; conf->args[pos]; pos++)
9914 free(conf->args[pos]);
9915 free(conf->args);
9916 }
9917 ha_free(&fconf->conf);
9918 ha_free((char **)&fconf->id);
9919 ha_free(&fconf->ops);
9920}
9921
9922static int hlua_filter_new(struct stream *s, struct filter *filter)
9923{
9924 struct hlua_flt_config *conf = FLT_CONF(filter);
9925 struct hlua_flt_ctx *flt_ctx = NULL;
9926 int ret = 1;
9927
9928 /* In the execution wrappers linked with a stream, the
9929 * Lua context can be not initialized. This behavior
9930 * permits to save performances because a systematic
9931 * Lua initialization cause 5% performances loss.
9932 */
9933 if (!s->hlua) {
9934 struct hlua *hlua;
9935
9936 hlua = pool_alloc(pool_head_hlua);
9937 if (!hlua) {
9938 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9939 conf->reg->name);
9940 ret = 0;
9941 goto end;
9942 }
9943 HLUA_INIT(hlua);
9944 s->hlua = hlua;
9945 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9946 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9947 conf->reg->name);
9948 ret = 0;
9949 goto end;
9950 }
9951 }
9952
9953 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
9954 if (!flt_ctx) {
9955 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9956 conf->reg->name);
9957 ret = 0;
9958 goto end;
9959 }
9960 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
9961 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
9962 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
9963 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9964 conf->reg->name);
9965 ret = 0;
9966 goto end;
9967 }
9968 HLUA_INIT(flt_ctx->hlua[0]);
9969 HLUA_INIT(flt_ctx->hlua[1]);
9970 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
9971 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9972 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9973 conf->reg->name);
9974 ret = 0;
9975 goto end;
9976 }
9977
9978 if (!HLUA_IS_RUNNING(s->hlua)) {
9979 /* The following Lua calls can fail. */
9980 if (!SET_SAFE_LJMP(s->hlua)) {
9981 const char *error;
9982
9983 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9984 error = lua_tostring(s->hlua->T, -1);
9985 else
9986 error = "critical error";
9987 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
9988 ret = 0;
9989 goto end;
9990 }
9991
9992 /* Check stack size. */
9993 if (!lua_checkstack(s->hlua->T, 1)) {
9994 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
9995 ret = 0;
9996 goto end;
9997 }
9998
9999 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10000 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10001 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10002 conf->reg->name);
10003 RESET_SAFE_LJMP(s->hlua);
10004 ret = 0;
10005 goto end;
10006 }
10007 lua_insert(s->hlua->T, -2);
10008
10009 /* Push the copy on the stack */
10010 s->hlua->nargs = 1;
10011
10012 /* We must initialize the execution timeouts. */
10013 s->hlua->max_time = hlua_timeout_session;
10014
10015 /* At this point the execution is safe. */
10016 RESET_SAFE_LJMP(s->hlua);
10017 }
10018
10019 switch (hlua_ctx_resume(s->hlua, 0)) {
10020 case HLUA_E_OK:
10021 /* Nothing returned or not a table, ignore the filter for current stream */
10022 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10023 ret = 0;
10024 goto end;
10025 }
10026
10027 /* Attached the filter pointer to the ctx */
10028 lua_pushstring(s->hlua->T, "__filter");
10029 lua_pushlightuserdata(s->hlua->T, filter);
10030 lua_settable(s->hlua->T, -3);
10031
10032 /* Save a ref on the filter ctx */
10033 lua_pushvalue(s->hlua->T, 1);
10034 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10035 filter->ctx = flt_ctx;
10036 break;
10037 case HLUA_E_ERRMSG:
10038 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10039 ret = -1;
10040 goto end;
10041 case HLUA_E_ETMOUT:
10042 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10043 ret = 0;
10044 goto end;
10045 case HLUA_E_NOMEM:
10046 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10047 ret = 0;
10048 goto end;
10049 case HLUA_E_AGAIN:
10050 case HLUA_E_YIELD:
10051 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10052 " are not allowed from 'new' function.\n", conf->reg->name);
10053 ret = 0;
10054 goto end;
10055 case HLUA_E_ERR:
10056 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10057 ret = 0;
10058 goto end;
10059 default:
10060 ret = 0;
10061 goto end;
10062 }
10063
10064 end:
10065 if (s->hlua)
10066 lua_settop(s->hlua->T, 0);
10067 if (ret <= 0) {
10068 if (flt_ctx) {
10069 hlua_ctx_destroy(flt_ctx->hlua[0]);
10070 hlua_ctx_destroy(flt_ctx->hlua[1]);
10071 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10072 }
10073 }
10074 return ret;
10075}
10076
10077static void hlua_filter_delete(struct stream *s, struct filter *filter)
10078{
10079 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10080
10081 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10082 hlua_ctx_destroy(flt_ctx->hlua[0]);
10083 hlua_ctx_destroy(flt_ctx->hlua[1]);
10084 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10085 filter->ctx = NULL;
10086}
10087
Christopher Faulet9f55a502020-02-25 15:21:02 +010010088static int hlua_filter_from_payload(struct filter *filter)
10089{
10090 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10091
10092 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10093}
10094
Christopher Fauletc404f112020-02-26 15:03:09 +010010095static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10096 int dir, unsigned int flags)
10097{
10098 struct hlua *flt_hlua;
10099 struct hlua_flt_config *conf = FLT_CONF(filter);
10100 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10101 unsigned int hflags = HLUA_TXN_FLT_CTX;
10102 int ret = 1;
10103
10104 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10105 if (!flt_hlua)
10106 goto end;
10107
10108 if (!HLUA_IS_RUNNING(flt_hlua)) {
10109 int extra_idx = lua_gettop(flt_hlua->T);
10110
10111 /* The following Lua calls can fail. */
10112 if (!SET_SAFE_LJMP(flt_hlua)) {
10113 const char *error;
10114
10115 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10116 error = lua_tostring(flt_hlua->T, -1);
10117 else
10118 error = "critical error";
10119 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10120 goto end;
10121 }
10122
10123 /* Check stack size. */
10124 if (!lua_checkstack(flt_hlua->T, 3)) {
10125 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10126 RESET_SAFE_LJMP(flt_hlua);
10127 goto end;
10128 }
10129
10130 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10131 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10132 RESET_SAFE_LJMP(flt_hlua);
10133 goto end;
10134 }
10135 lua_insert(flt_hlua->T, -2);
10136
10137 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10138 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10139 RESET_SAFE_LJMP(flt_hlua);
10140 goto end;
10141 }
10142 flt_hlua->nargs = 2;
10143
10144 if (flags & HLUA_FLT_CB_ARG_CHN) {
10145 if (dir == SMP_OPT_DIR_REQ)
10146 lua_getfield(flt_hlua->T, -1, "req");
10147 else
10148 lua_getfield(flt_hlua->T, -1, "res");
10149 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10150 lua_pushstring(flt_hlua->T, "__filter");
10151 lua_pushlightuserdata(flt_hlua->T, filter);
10152 lua_settable(flt_hlua->T, -3);
10153 }
10154 flt_hlua->nargs++;
10155 }
10156 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010157 if (dir == SMP_OPT_DIR_REQ)
10158 lua_getfield(flt_hlua->T, -1, "http_req");
10159 else
10160 lua_getfield(flt_hlua->T, -1, "http_res");
10161 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10162 lua_pushstring(flt_hlua->T, "__filter");
10163 lua_pushlightuserdata(flt_hlua->T, filter);
10164 lua_settable(flt_hlua->T, -3);
10165 }
10166 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010167 }
10168
10169 /* Check stack size. */
10170 if (!lua_checkstack(flt_hlua->T, 1)) {
10171 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10172 RESET_SAFE_LJMP(flt_hlua);
10173 goto end;
10174 }
10175
10176 while (extra_idx--) {
10177 lua_pushvalue(flt_hlua->T, 1);
10178 lua_remove(flt_hlua->T, 1);
10179 flt_hlua->nargs++;
10180 }
10181
10182 /* We must initialize the execution timeouts. */
10183 flt_hlua->max_time = hlua_timeout_session;
10184
10185 /* At this point the execution is safe. */
10186 RESET_SAFE_LJMP(flt_hlua);
10187 }
10188
10189 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10190 case HLUA_E_OK:
10191 /* Catch the return value if it required */
10192 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10193 ret = lua_tointeger(flt_hlua->T, -1);
10194 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10195 }
10196
10197 /* Set timeout in the required channel. */
10198 if (flt_hlua->wake_time != TICK_ETERNITY) {
10199 if (dir == SMP_OPT_DIR_REQ)
10200 s->req.analyse_exp = flt_hlua->wake_time;
10201 else
10202 s->res.analyse_exp = flt_hlua->wake_time;
10203 }
10204 break;
10205 case HLUA_E_AGAIN:
10206 /* Set timeout in the required channel. */
10207 if (flt_hlua->wake_time != TICK_ETERNITY) {
10208 if (dir == SMP_OPT_DIR_REQ)
10209 s->req.analyse_exp = flt_hlua->wake_time;
10210 else
10211 s->res.analyse_exp = flt_hlua->wake_time;
10212 }
10213 /* Some actions can be wake up when a "write" event
10214 * is detected on a response channel. This is useful
10215 * only for actions targeted on the requests.
10216 */
10217 if (HLUA_IS_WAKERESWR(flt_hlua))
10218 s->res.flags |= CF_WAKE_WRITE;
10219 if (HLUA_IS_WAKEREQWR(flt_hlua))
10220 s->req.flags |= CF_WAKE_WRITE;
10221 ret = 0;
10222 goto end;
10223 case HLUA_E_ERRMSG:
10224 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10225 ret = -1;
10226 goto end;
10227 case HLUA_E_ETMOUT:
10228 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10229 goto end;
10230 case HLUA_E_NOMEM:
10231 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10232 goto end;
10233 case HLUA_E_YIELD:
10234 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10235 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10236 goto end;
10237 case HLUA_E_ERR:
10238 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10239 goto end;
10240 default:
10241 goto end;
10242 }
10243
10244
10245 end:
10246 return ret;
10247}
10248
10249static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10250{
10251 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10252
10253 flt_ctx->flags = 0;
10254 return hlua_filter_callback(s, filter, "start_analyze",
10255 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10256 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10257}
10258
10259static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10260{
10261 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10262
10263 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10264 return hlua_filter_callback(s, filter, "end_analyze",
10265 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10266 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10267}
10268
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010269static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10270{
10271 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10272
10273 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10274 return hlua_filter_callback(s, filter, "http_headers",
10275 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10276 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10277}
10278
10279static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10280 unsigned int offset, unsigned int len)
10281{
10282 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10283 struct hlua *flt_hlua;
10284 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10285 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10286 int ret;
10287
10288 flt_hlua = flt_ctx->hlua[idx];
10289 flt_ctx->cur_off[idx] = offset;
10290 flt_ctx->cur_len[idx] = len;
10291 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10292 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10293 if (ret != -1) {
10294 ret = flt_ctx->cur_len[idx];
10295 if (lua_gettop(flt_hlua->T) > 0) {
10296 ret = lua_tointeger(flt_hlua->T, -1);
10297 if (ret > flt_ctx->cur_len[idx])
10298 ret = flt_ctx->cur_len[idx];
10299 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10300 }
10301 }
10302 return ret;
10303}
10304
10305static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10306{
10307 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10308
10309 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10310 return hlua_filter_callback(s, filter, "http_end",
10311 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10312 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10313}
10314
Christopher Fauletc404f112020-02-26 15:03:09 +010010315static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10316 unsigned int offset, unsigned int len)
10317{
10318 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10319 struct hlua *flt_hlua;
10320 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10321 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10322 int ret;
10323
10324 flt_hlua = flt_ctx->hlua[idx];
10325 flt_ctx->cur_off[idx] = offset;
10326 flt_ctx->cur_len[idx] = len;
10327 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10328 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10329 if (ret != -1) {
10330 ret = flt_ctx->cur_len[idx];
10331 if (lua_gettop(flt_hlua->T) > 0) {
10332 ret = lua_tointeger(flt_hlua->T, -1);
10333 if (ret > flt_ctx->cur_len[idx])
10334 ret = flt_ctx->cur_len[idx];
10335 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10336 }
10337 }
10338 return ret;
10339}
10340
Christopher Faulet69c581a2021-05-31 08:54:04 +020010341static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10342 struct flt_conf *fconf, char **err, void *private)
10343{
10344 struct hlua_reg_filter *reg_flt = private;
10345 lua_State *L;
10346 struct hlua_flt_config *conf = NULL;
10347 const char *flt_id = NULL;
10348 int state_id, pos, flt_flags = 0;
10349 struct flt_ops *hlua_flt_ops = NULL;
10350
10351 state_id = reg_flt_to_stack_id(reg_flt);
10352 L = hlua_states[state_id];
10353
10354 /* Initialize the filter ops with default callbacks */
10355 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010356 if (!hlua_flt_ops)
10357 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010358 hlua_flt_ops->init = hlua_filter_init;
10359 hlua_flt_ops->deinit = hlua_filter_deinit;
10360 if (state_id) {
10361 /* Set per-thread callback if script is loaded per-thread */
10362 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10363 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10364 }
10365 hlua_flt_ops->attach = hlua_filter_new;
10366 hlua_flt_ops->detach = hlua_filter_delete;
10367
10368 /* Push the filter class on the stack and resolve all callbacks */
10369 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10370
Christopher Fauletc404f112020-02-26 15:03:09 +010010371 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10372 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10373 lua_pop(L, 1);
10374 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10375 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10376 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010377 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10378 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10379 lua_pop(L, 1);
10380 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10381 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10382 lua_pop(L, 1);
10383 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10384 hlua_flt_ops->http_end = hlua_filter_http_end;
10385 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010386 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10387 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10388 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010389
10390 /* Get id and flags of the filter class */
10391 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10392 flt_id = lua_tostring(L, -1);
10393 lua_pop(L, 1);
10394 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10395 flt_flags = lua_tointeger(L, -1);
10396 lua_pop(L, 1);
10397
10398 /* Create the filter config */
10399 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010400 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010401 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010402 conf->reg = reg_flt;
10403
10404 /* duplicate args */
10405 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10406 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010407 if (!conf->args)
10408 goto error;
10409 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010410 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010411 if (!conf->args[pos])
10412 goto error;
10413 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010414 conf->args[pos] = NULL;
10415 *cur_arg += pos + 1;
10416
Christopher Fauletc86bb872021-08-13 08:33:57 +020010417 if (flt_id) {
10418 fconf->id = strdup(flt_id);
10419 if (!fconf->id)
10420 goto error;
10421 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010422 fconf->flags = flt_flags;
10423 fconf->conf = conf;
10424 fconf->ops = hlua_flt_ops;
10425
10426 lua_settop(L, 0);
10427 return 0;
10428
10429 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010430 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010431 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010432 if (conf && conf->args) {
10433 for (pos = 0; conf->args[pos]; pos++)
10434 free(conf->args[pos]);
10435 free(conf->args);
10436 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010437 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010438 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010439 lua_settop(L, 0);
10440 return -1;
10441}
10442
Christopher Fauletc404f112020-02-26 15:03:09 +010010443__LJMP static int hlua_register_data_filter(lua_State *L)
10444{
10445 struct filter *filter;
10446 struct channel *chn;
10447
10448 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10449 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10450 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10451
10452 lua_getfield(L, 1, "__filter");
10453 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10454 filter = lua_touserdata (L, -1);
10455 lua_pop(L, 1);
10456
10457 register_data_filter(chn_strm(chn), chn, filter);
10458 return 1;
10459}
10460
10461__LJMP static int hlua_unregister_data_filter(lua_State *L)
10462{
10463 struct filter *filter;
10464 struct channel *chn;
10465
10466 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10467 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10468 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10469
10470 lua_getfield(L, 1, "__filter");
10471 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10472 filter = lua_touserdata (L, -1);
10473 lua_pop(L, 1);
10474
10475 unregister_data_filter(chn_strm(chn), chn, filter);
10476 return 1;
10477}
10478
Christopher Faulet69c581a2021-05-31 08:54:04 +020010479/* This function is an LUA binding used for registering a filter. It expects a
10480 * fileter name used in the haproxy configuration file and a LUA function to
10481 * parse configuration arguments.
10482 */
10483__LJMP static int hlua_register_filter(lua_State *L)
10484{
10485 struct buffer *trash;
10486 struct flt_kw_list *fkl;
10487 struct flt_kw *fkw;
10488 const char *name;
10489 struct hlua_reg_filter *reg_flt= NULL;
10490 int flt_ref, fun_ref;
10491 int len;
10492
10493 MAY_LJMP(check_args(L, 3, "register_filter"));
10494
10495 /* First argument : filter name. */
10496 name = MAY_LJMP(luaL_checkstring(L, 1));
10497
10498 /* Second argument : The filter class */
10499 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
10500
10501 /* Third argument : lua function. */
10502 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
10503
10504 trash = get_trash_chunk();
10505 chunk_printf(trash, "lua.%s", name);
10506 fkw = flt_find_kw(trash->area);
10507 if (fkw != NULL) {
10508 reg_flt = fkw->private;
10509 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
10510 ha_warning("Trying to register filter 'lua.%s' more than once. "
10511 "This will become a hard error in version 2.5.\n", name);
10512 }
10513 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10514 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10515 return 0;
10516 }
10517
10518 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
10519 if (!fkl)
10520 goto alloc_error;
10521 fkl->scope = "HLUA";
10522
10523 reg_flt = new_hlua_reg_filter(name);
10524 if (!reg_flt)
10525 goto alloc_error;
10526
10527 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10528 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10529
10530 /* The filter keyword */
10531 len = strlen("lua.") + strlen(name) + 1;
10532 fkl->kw[0].kw = calloc(1, len);
10533 if (!fkl->kw[0].kw)
10534 goto alloc_error;
10535
10536 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
10537
10538 fkl->kw[0].parse = hlua_filter_parse_fct;
10539 fkl->kw[0].private = reg_flt;
10540 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
10541
10542 /* Register this new filter */
10543 flt_register_keywords(fkl);
10544
10545 return 0;
10546
10547 alloc_error:
10548 release_hlua_reg_filter(reg_flt);
10549 ha_free(&fkl);
10550 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10551 return 0; /* Never reached */
10552}
10553
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010554static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010555 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010556 char **err, unsigned int *timeout)
10557{
10558 const char *error;
10559
10560 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020010561 if (error == PARSE_TIME_OVER) {
10562 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
10563 args[1], args[0]);
10564 return -1;
10565 }
10566 else if (error == PARSE_TIME_UNDER) {
10567 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
10568 args[1], args[0]);
10569 return -1;
10570 }
10571 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010572 memprintf(err, "%s: invalid timeout", args[0]);
10573 return -1;
10574 }
10575 return 0;
10576}
10577
10578static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010579 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010580 char **err)
10581{
10582 return hlua_read_timeout(args, section_type, curpx, defpx,
10583 file, line, err, &hlua_timeout_session);
10584}
10585
10586static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010587 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010588 char **err)
10589{
10590 return hlua_read_timeout(args, section_type, curpx, defpx,
10591 file, line, err, &hlua_timeout_task);
10592}
10593
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010594static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010595 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010596 char **err)
10597{
10598 return hlua_read_timeout(args, section_type, curpx, defpx,
10599 file, line, err, &hlua_timeout_applet);
10600}
10601
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010602static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010603 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010604 char **err)
10605{
10606 char *error;
10607
10608 hlua_nb_instruction = strtoll(args[1], &error, 10);
10609 if (*error != '\0') {
10610 memprintf(err, "%s: invalid number", args[0]);
10611 return -1;
10612 }
10613 return 0;
10614}
10615
Willy Tarreau32f61e22015-03-18 17:54:59 +010010616static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010617 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010010618 char **err)
10619{
10620 char *error;
10621
10622 if (*(args[1]) == 0) {
10623 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
10624 return -1;
10625 }
10626 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
10627 if (*error != '\0') {
10628 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
10629 return -1;
10630 }
10631 return 0;
10632}
10633
10634
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010635/* This function is called by the main configuration key "lua-load". It loads and
10636 * execute an lua file during the parsing of the HAProxy configuration file. It is
10637 * the main lua entry point.
10638 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010639 * This function runs with the HAProxy keywords API. It returns -1 if an error
10640 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010641 *
10642 * In some error case, LUA set an error message in top of the stack. This function
10643 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010644 *
10645 * This function can fail with an abort() due to an Lua critical error.
10646 * We are in the configuration parsing process of HAProxy, this abort() is
10647 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010648 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010649static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010650{
10651 int error;
10652
10653 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010654 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010655 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010656 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
10657 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010658 return -1;
10659 }
10660
10661 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010662 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010663 switch (error) {
10664 case LUA_OK:
10665 break;
10666 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010667 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
10668 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010669 return -1;
10670 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010010671 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010672 return -1;
10673 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010674 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
10675 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010676 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010677#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010678 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010679 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
10680 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010681 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010682#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010683 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010684 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
10685 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010686 return -1;
10687 }
10688
10689 return 0;
10690}
10691
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010692static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010693 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010694 char **err)
10695{
10696 if (*(args[1]) == 0) {
10697 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
10698 return -1;
10699 }
10700
Thierry Fournier59f11be2020-11-29 00:37:41 +010010701 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010010702 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010703 ha_set_tid(0);
Thierry Fournierafc63e22020-11-28 17:06:51 +010010704 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010705}
10706
Thierry Fournier59f11be2020-11-29 00:37:41 +010010707static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010708 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010010709 char **err)
10710{
10711 int len;
10712
10713 if (*(args[1]) == 0) {
10714 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
10715 return -1;
10716 }
10717
10718 if (per_thread_load == NULL) {
10719 /* allocate the first entry large enough to store the final NULL */
10720 per_thread_load = calloc(1, sizeof(*per_thread_load));
10721 if (per_thread_load == NULL) {
10722 memprintf(err, "out of memory error");
10723 return -1;
10724 }
10725 }
10726
10727 /* count used entries */
10728 for (len = 0; per_thread_load[len] != NULL; len++)
10729 ;
10730
10731 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
10732 if (per_thread_load == NULL) {
10733 memprintf(err, "out of memory error");
10734 return -1;
10735 }
10736
10737 per_thread_load[len] = strdup(args[1]);
10738 per_thread_load[len + 1] = NULL;
10739
10740 if (per_thread_load[len] == NULL) {
10741 memprintf(err, "out of memory error");
10742 return -1;
10743 }
10744
10745 /* loading for thread 1 only */
10746 hlua_state_id = 1;
10747 ha_set_tid(0);
10748 return hlua_load_state(args[1], hlua_states[1], err);
10749}
10750
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010751/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
10752 * in the given <ctx>.
10753 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010754static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010755{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010756 lua_getglobal(L, "package"); /* push package variable */
10757 lua_pushstring(L, path); /* push given path */
10758 lua_pushstring(L, ";"); /* push semicolon */
10759 lua_getfield(L, -3, type); /* push old path */
10760 lua_concat(L, 3); /* concatenate to new path */
10761 lua_setfield(L, -2, type); /* store new path */
10762 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010763
10764 return 0;
10765}
10766
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010767static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010768 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010769 char **err)
10770{
10771 char *path;
10772 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010773 struct prepend_path *p = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010774
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010775 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010776 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010777 }
10778
10779 if (!(*args[1])) {
10780 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010781 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010782 }
10783 path = args[1];
10784
10785 if (*args[2]) {
10786 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
10787 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010788 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010789 }
10790 type = args[2];
10791 }
10792
Thierry Fournier59f11be2020-11-29 00:37:41 +010010793 p = calloc(1, sizeof(*p));
10794 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010795 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010796 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010797 }
10798 p->path = strdup(path);
10799 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010800 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010801 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010802 }
10803 p->type = strdup(type);
10804 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010805 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010806 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010807 }
Willy Tarreau2b718102021-04-21 07:32:39 +020010808 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010809
10810 hlua_prepend_path(hlua_states[0], type, path);
10811 hlua_prepend_path(hlua_states[1], type, path);
10812 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010813
10814err2:
10815 free(p->type);
10816 free(p->path);
10817err:
10818 free(p);
10819 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010820}
10821
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010822/* configuration keywords declaration */
10823static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010824 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010825 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010010826 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010827 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
10828 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020010829 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010830 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010010831 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010832 { 0, NULL, NULL },
10833}};
10834
Willy Tarreau0108d902018-11-25 19:14:37 +010010835INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
10836
Christopher Fauletafd8f102018-11-08 11:34:21 +010010837
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010838/* This function can fail with an abort() due to an Lua critical error.
10839 * We are in the initialisation process of HAProxy, this abort() is
10840 * tolerated.
10841 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010010842int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010843{
10844 struct hlua_init_function *init;
10845 const char *msg;
10846 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010847 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010010848 const char *kind;
10849 const char *trace;
10850 int return_status = 1;
10851#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
10852 int nres;
10853#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010854
Willy Tarreaucdb53462020-12-02 12:12:00 +010010855 /* disable memory limit checks if limit is not set */
10856 if (!hlua_global_allocator.limit)
10857 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
10858
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010859 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010010860 if (setjmp(safe_ljmp_env) != 0) {
10861 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010010862 if (lua_type(L, -1) == LUA_TSTRING)
10863 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010864 else
10865 error = "critical error";
10866 fprintf(stderr, "Lua post-init: %s.\n", error);
10867 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010010868 } else {
10869 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010870 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020010871
Thierry Fournierb8cef172020-11-28 15:37:17 +010010872 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010873
Thierry Fournierc7492592020-11-28 23:57:24 +010010874 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010010875 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010010876
10877#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010010878 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010010879#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010010880 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010010881#endif
10882 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010883 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010010884
10885 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010010886 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010010887 break;
Thierry Fournier670db242020-11-28 10:49:59 +010010888
10889 case LUA_ERRERR:
10890 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010891 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010892 case LUA_ERRRUN:
10893 if (!kind)
10894 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010010895 msg = lua_tostring(L, -1);
10896 lua_settop(L, 0); /* Empty the stack. */
10897 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010010898 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010010899 if (msg)
10900 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
10901 else
10902 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
10903 return_status = 0;
10904 break;
10905
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010906 default:
Thierry Fournier670db242020-11-28 10:49:59 +010010907 /* Unknown error */
10908 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010909 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010910 case LUA_YIELD:
10911 /* yield is not configured at this step, this state doesn't happen */
10912 if (!kind)
10913 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010914 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010915 case LUA_ERRMEM:
10916 if (!kind)
10917 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010010918 lua_settop(L, 0);
10919 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010010920 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010010921 ha_alert("Lua init: %s: %s\n", kind, trace);
10922 return_status = 0;
10923 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010924 }
Thierry Fournier670db242020-11-28 10:49:59 +010010925 if (!return_status)
10926 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010927 }
Thierry Fournier3c539322020-11-28 16:05:05 +010010928
10929 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010010930 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010931}
10932
Thierry Fournierb8cef172020-11-28 15:37:17 +010010933int hlua_post_init()
10934{
Thierry Fournier59f11be2020-11-29 00:37:41 +010010935 int ret;
10936 int i;
10937 int errors;
10938 char *err = NULL;
10939 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010940 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010941
Thierry Fournierb8cef172020-11-28 15:37:17 +010010942#if USE_OPENSSL
10943 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010010944 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010010945 int saved_used_backed = global.ssl_used_backend;
10946 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010010947 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010010948 global.ssl_used_backend = saved_used_backed;
10949 }
10950#endif
10951
Thierry Fournierc7492592020-11-28 23:57:24 +010010952 /* Perform post init of common thread */
10953 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010954 ha_set_tid(0);
10955 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
10956 if (ret == 0)
10957 return 0;
10958
10959 /* init remaining lua states and load files */
10960 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
10961
10962 /* set thread context */
10963 ha_set_tid(hlua_state_id - 1);
10964
10965 /* Init lua state */
10966 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
10967
10968 /* Load lua files */
10969 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
10970 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
10971 if (ret != 0) {
10972 ha_alert("Lua init: %s\n", err);
10973 return 0;
10974 }
10975 }
10976 }
10977
10978 /* Reset thread context */
10979 ha_set_tid(0);
10980
10981 /* Execute post init for all states */
10982 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
10983
10984 /* set thread context */
10985 ha_set_tid(hlua_state_id - 1);
10986
10987 /* run post init */
10988 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
10989 if (ret == 0)
10990 return 0;
10991 }
10992
10993 /* Reset thread context */
10994 ha_set_tid(0);
10995
10996 /* control functions registering. Each function must have:
10997 * - only the function_ref[0] set positive and all other to -1
10998 * - only the function_ref[0] set to -1 and all other positive
10999 * This ensure a same reference is not used both in shared
11000 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011001 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011002 * complicated to found for the end user.
11003 */
11004 errors = 0;
11005 list_for_each_entry(fcn, &referenced_functions, l) {
11006 ret = 0;
11007 for (i = 1; i < global.nbthread + 1; i++) {
11008 if (fcn->function_ref[i] == -1)
11009 ret--;
11010 else
11011 ret++;
11012 }
11013 if (abs(ret) != global.nbthread) {
11014 ha_alert("Lua function '%s' is not referenced in all thread. "
11015 "Expect function in all thread or in none thread.\n", fcn->name);
11016 errors++;
11017 continue;
11018 }
11019
11020 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011021 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11022 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011023 "exclusive.\n", fcn->name);
11024 errors++;
11025 }
11026 }
11027
Christopher Faulet69c581a2021-05-31 08:54:04 +020011028 /* Do the same with registered filters */
11029 list_for_each_entry(reg_flt, &referenced_filters, l) {
11030 ret = 0;
11031 for (i = 1; i < global.nbthread + 1; i++) {
11032 if (reg_flt->flt_ref[i] == -1)
11033 ret--;
11034 else
11035 ret++;
11036 }
11037 if (abs(ret) != global.nbthread) {
11038 ha_alert("Lua filter '%s' is not referenced in all thread. "
11039 "Expect function in all thread or in none thread.\n", reg_flt->name);
11040 errors++;
11041 continue;
11042 }
11043
11044 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11045 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11046 "and per-thread Lua context (through lua-load-per-thread). these two context "
11047 "exclusive.\n", fcn->name);
11048 errors++;
11049 }
11050 }
11051
11052
Thierry Fournier59f11be2020-11-29 00:37:41 +010011053 if (errors > 0)
11054 return 0;
11055
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011056 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011057 * -1 in order to have probably a segfault if someone use it
11058 */
11059 hlua_state_id = -1;
11060
11061 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011062}
11063
Willy Tarreau32f61e22015-03-18 17:54:59 +010011064/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11065 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11066 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011067 * allocation. <nsize> is the requested new size. A new allocation is
11068 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011069 * zero. This one verifies that the limits are respected but is optimized
11070 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011071 */
11072static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11073{
11074 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011075 size_t limit, old, new;
11076
Tim Duesterhus22586522021-01-08 10:35:33 +010011077 if (unlikely(!ptr && !nsize))
11078 return NULL;
11079
Willy Tarreaucdb53462020-12-02 12:12:00 +010011080 /* a limit of ~0 means unlimited and boot complete, so there's no need
11081 * for accounting anymore.
11082 */
Christopher Fauletcc2c4f82021-03-24 14:52:24 +010011083 if (likely(~zone->limit == 0))
11084 return realloc(ptr, nsize);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011085
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011086 if (!ptr)
11087 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011088
Willy Tarreaucdb53462020-12-02 12:12:00 +010011089 /* enforce strict limits across all threads */
11090 limit = zone->limit;
11091 old = _HA_ATOMIC_LOAD(&zone->allocated);
11092 do {
11093 new = old + nsize - osize;
11094 if (unlikely(nsize && limit && new > limit))
11095 return NULL;
11096 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011097
11098 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011099
11100 if (unlikely(!ptr && nsize)) // failed
11101 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11102
11103 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011104 return ptr;
11105}
11106
Thierry Fournierecb83c22020-11-28 15:49:44 +010011107/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011108 * We are in the initialisation process of HAProxy, this abort() is
11109 * tolerated.
11110 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011111lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011112{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011113 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011114 int idx;
11115 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011116 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011117 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011118 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011119 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011120 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011121 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011122
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011123 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011124 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011125
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011126 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011127 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011128 *context = NULL;
11129
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011130 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011131 * the Lua function can fail with an abort. We are in the initialisation
11132 * process of HAProxy, this abort() is tolerated.
11133 */
11134
Thierry Fournier3c539322020-11-28 16:05:05 +010011135 /* Call post initialisation function in safe environment. */
11136 if (setjmp(safe_ljmp_env) != 0) {
11137 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011138 if (lua_type(L, -1) == LUA_TSTRING)
11139 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011140 else
11141 error_msg = "critical error";
11142 fprintf(stderr, "Lua init: %s.\n", error_msg);
11143 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011144 } else {
11145 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011146 }
11147
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011148 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011149 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011150#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11151#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11152#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011153 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011154#endif
11155#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011156 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011157#endif
11158#undef HLUA_PREPEND_PATH_TOSTRING
11159#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011160
Thierry Fournier59f11be2020-11-29 00:37:41 +010011161 /* Apply configured prepend path */
11162 list_for_each_entry(pp, &prepend_path_list, l)
11163 hlua_prepend_path(L, pp->type, pp->path);
11164
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011165 /*
11166 *
11167 * Create "core" object.
11168 *
11169 */
11170
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011171 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011172 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011173
Thierry Fournierecb83c22020-11-28 15:49:44 +010011174 /* set the thread id */
11175 hlua_class_const_int(L, "thread", thread_num);
11176
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011177 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011178 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011179 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011180
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011181 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011182 hlua_class_function(L, "register_init", hlua_register_init);
11183 hlua_class_function(L, "register_task", hlua_register_task);
11184 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11185 hlua_class_function(L, "register_converters", hlua_register_converters);
11186 hlua_class_function(L, "register_action", hlua_register_action);
11187 hlua_class_function(L, "register_service", hlua_register_service);
11188 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011189 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011190 hlua_class_function(L, "yield", hlua_yield);
11191 hlua_class_function(L, "set_nice", hlua_set_nice);
11192 hlua_class_function(L, "sleep", hlua_sleep);
11193 hlua_class_function(L, "msleep", hlua_msleep);
11194 hlua_class_function(L, "add_acl", hlua_add_acl);
11195 hlua_class_function(L, "del_acl", hlua_del_acl);
11196 hlua_class_function(L, "set_map", hlua_set_map);
11197 hlua_class_function(L, "del_map", hlua_del_map);
11198 hlua_class_function(L, "tcp", hlua_socket_new);
11199 hlua_class_function(L, "log", hlua_log);
11200 hlua_class_function(L, "Debug", hlua_log_debug);
11201 hlua_class_function(L, "Info", hlua_log_info);
11202 hlua_class_function(L, "Warning", hlua_log_warning);
11203 hlua_class_function(L, "Alert", hlua_log_alert);
11204 hlua_class_function(L, "done", hlua_done);
11205 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011206
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011207 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011208
11209 /*
11210 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011211 * Create "act" object.
11212 *
11213 */
11214
11215 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011216 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011217
11218 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011219 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11220 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11221 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11222 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11223 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11224 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11225 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11226 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011227
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011228 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011229
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011230 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011231
11232 /*
11233 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011234 * Create "Filter" object.
11235 *
11236 */
11237
11238 /* This table entry is the object "filter" base. */
11239 lua_newtable(L);
11240
11241 /* push flags and constants */
11242 hlua_class_const_int(L, "CONTINUE", 1);
11243 hlua_class_const_int(L, "WAIT", 0);
11244 hlua_class_const_int(L, "ERROR", -1);
11245
11246 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
11247
Christopher Fauletc404f112020-02-26 15:03:09 +010011248 hlua_class_function(L, "wake_time", hlua_set_wake_time);
11249 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
11250 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
11251
Christopher Faulet69c581a2021-05-31 08:54:04 +020011252 lua_setglobal(L, "filter");
11253
11254 /*
11255 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011256 * Register class Map
11257 *
11258 */
11259
11260 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011261 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011262
11263 /* register pattern types. */
11264 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011265 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011266 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011267 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011268 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011269 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011270
11271 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011272 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011273
11274 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011275 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011276
Ilya Shipitsind4259502020-04-08 01:07:56 +050011277 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011278 lua_pushstring(L, "__index");
11279 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011280
11281 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011282 hlua_class_function(L, "lookup", hlua_map_lookup);
11283 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011284
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011285 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011286
Thierry Fournier45e78d72016-02-19 18:34:46 +010011287 /* Register previous table in the registry with reference and named entry.
11288 * The function hlua_register_metatable() pops the stack, so we
11289 * previously create a copy of the table.
11290 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011291 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
11292 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011293
11294 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011295 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011296
11297 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011298 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011299
11300 /*
11301 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011302 * Register class Channel
11303 *
11304 */
11305
11306 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011307 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011308
Ilya Shipitsind4259502020-04-08 01:07:56 +050011309 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011310 lua_pushstring(L, "__index");
11311 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011312
11313 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011314 hlua_class_function(L, "data", hlua_channel_get_data);
11315 hlua_class_function(L, "line", hlua_channel_get_line);
11316 hlua_class_function(L, "set", hlua_channel_set_data);
11317 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011318 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011319 hlua_class_function(L, "prepend", hlua_channel_prepend);
11320 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011321 hlua_class_function(L, "send", hlua_channel_send);
11322 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011323 hlua_class_function(L, "input", hlua_channel_get_in_len);
11324 hlua_class_function(L, "output", hlua_channel_get_out_len);
11325 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011326 hlua_class_function(L, "is_full", hlua_channel_is_full);
11327 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011328
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011329 /* Deprecated API */
11330 hlua_class_function(L, "get", hlua_channel_get);
11331 hlua_class_function(L, "dup", hlua_channel_dup);
11332 hlua_class_function(L, "getline", hlua_channel_getline);
11333 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
11334 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
11335
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011336 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011337
11338 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011339 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011340
11341 /*
11342 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011343 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011344 *
11345 */
11346
11347 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011348 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011349
Ilya Shipitsind4259502020-04-08 01:07:56 +050011350 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011351 lua_pushstring(L, "__index");
11352 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011353
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011354 /* Browse existing fetches and create the associated
11355 * object method.
11356 */
11357 sf = NULL;
11358 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011359 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11360 * by an underscore.
11361 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011362 strncpy(trash.area, sf->kw, trash.size);
11363 trash.area[trash.size - 1] = '\0';
11364 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011365 if (*p == '.' || *p == '-' || *p == '+')
11366 *p = '_';
11367
11368 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011369 lua_pushstring(L, trash.area);
11370 lua_pushlightuserdata(L, sf);
11371 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
11372 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011373 }
11374
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011375 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011376
11377 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011378 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011379
11380 /*
11381 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011382 * Register class Converters
11383 *
11384 */
11385
11386 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011387 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011388
11389 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011390 lua_pushstring(L, "__index");
11391 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011392
11393 /* Browse existing converters and create the associated
11394 * object method.
11395 */
11396 sc = NULL;
11397 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011398 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11399 * by an underscore.
11400 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011401 strncpy(trash.area, sc->kw, trash.size);
11402 trash.area[trash.size - 1] = '\0';
11403 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011404 if (*p == '.' || *p == '-' || *p == '+')
11405 *p = '_';
11406
11407 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011408 lua_pushstring(L, trash.area);
11409 lua_pushlightuserdata(L, sc);
11410 lua_pushcclosure(L, hlua_run_sample_conv, 1);
11411 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011412 }
11413
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011414 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011415
11416 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011417 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011418
11419 /*
11420 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011421 * Register class HTTP
11422 *
11423 */
11424
11425 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011426 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011427
Ilya Shipitsind4259502020-04-08 01:07:56 +050011428 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011429 lua_pushstring(L, "__index");
11430 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011431
11432 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011433 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
11434 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
11435 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
11436 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
11437 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
11438 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
11439 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
11440 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
11441 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
11442 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011443
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011444 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
11445 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
11446 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
11447 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
11448 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
11449 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
11450 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011451
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011452 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011453
11454 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011455 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011456
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011457 /*
11458 *
11459 * Register class HTTPMessage
11460 *
11461 */
11462
11463 /* Create and fill the metatable. */
11464 lua_newtable(L);
11465
11466 /* Create and fille the __index entry. */
11467 lua_pushstring(L, "__index");
11468 lua_newtable(L);
11469
11470 /* Register Lua functions. */
11471 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
11472 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
11473 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
11474 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
11475 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
11476 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
11477 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
11478 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
11479 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
11480 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
11481 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
11482 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
11483 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
11484 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
11485 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
11486 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
11487 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
11488 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
11489
11490 hlua_class_function(L, "body", hlua_http_msg_get_body);
11491 hlua_class_function(L, "set", hlua_http_msg_set_data);
11492 hlua_class_function(L, "remove", hlua_http_msg_del_data);
11493 hlua_class_function(L, "append", hlua_http_msg_append);
11494 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
11495 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
11496 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
11497 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
11498
11499 hlua_class_function(L, "send", hlua_http_msg_send);
11500 hlua_class_function(L, "forward", hlua_http_msg_forward);
11501
11502 lua_rawset(L, -3);
11503
11504 /* Register previous table in the registry with reference and named entry. */
11505 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011506 /*
11507 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011508 * Register class AppletTCP
11509 *
11510 */
11511
11512 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011513 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011514
Ilya Shipitsind4259502020-04-08 01:07:56 +050011515 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011516 lua_pushstring(L, "__index");
11517 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011518
11519 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011520 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
11521 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
11522 hlua_class_function(L, "send", hlua_applet_tcp_send);
11523 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
11524 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
11525 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
11526 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
11527 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011528
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011529 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011530
11531 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011532 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011533
11534 /*
11535 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011536 * Register class AppletHTTP
11537 *
11538 */
11539
11540 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011541 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011542
Ilya Shipitsind4259502020-04-08 01:07:56 +050011543 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011544 lua_pushstring(L, "__index");
11545 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011546
11547 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011548 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
11549 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
11550 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
11551 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
11552 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
11553 hlua_class_function(L, "getline", hlua_applet_http_getline);
11554 hlua_class_function(L, "receive", hlua_applet_http_recv);
11555 hlua_class_function(L, "send", hlua_applet_http_send);
11556 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
11557 hlua_class_function(L, "set_status", hlua_applet_http_status);
11558 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011559
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011560 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011561
11562 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011563 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011564
11565 /*
11566 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011567 * Register class TXN
11568 *
11569 */
11570
11571 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011572 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011573
Ilya Shipitsind4259502020-04-08 01:07:56 +050011574 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011575 lua_pushstring(L, "__index");
11576 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011577
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011578 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011579 hlua_class_function(L, "set_priv", hlua_set_priv);
11580 hlua_class_function(L, "get_priv", hlua_get_priv);
11581 hlua_class_function(L, "set_var", hlua_set_var);
11582 hlua_class_function(L, "unset_var", hlua_unset_var);
11583 hlua_class_function(L, "get_var", hlua_get_var);
11584 hlua_class_function(L, "done", hlua_txn_done);
11585 hlua_class_function(L, "reply", hlua_txn_reply_new);
11586 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
11587 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
11588 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
11589 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
11590 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
11591 hlua_class_function(L, "deflog", hlua_txn_deflog);
11592 hlua_class_function(L, "log", hlua_txn_log);
11593 hlua_class_function(L, "Debug", hlua_txn_log_debug);
11594 hlua_class_function(L, "Info", hlua_txn_log_info);
11595 hlua_class_function(L, "Warning", hlua_txn_log_warning);
11596 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011597
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011598 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011599
11600 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011601 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011602
11603 /*
11604 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010011605 * Register class reply
11606 *
11607 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011608 lua_newtable(L);
11609 lua_pushstring(L, "__index");
11610 lua_newtable(L);
11611 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
11612 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
11613 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
11614 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
11615 lua_settable(L, -3); /* Sets the __index entry. */
11616 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010011617
11618
11619 /*
11620 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011621 * Register class Socket
11622 *
11623 */
11624
11625 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011626 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011627
Ilya Shipitsind4259502020-04-08 01:07:56 +050011628 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011629 lua_pushstring(L, "__index");
11630 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011631
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011632#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011633 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011634#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011635 hlua_class_function(L, "connect", hlua_socket_connect);
11636 hlua_class_function(L, "send", hlua_socket_send);
11637 hlua_class_function(L, "receive", hlua_socket_receive);
11638 hlua_class_function(L, "close", hlua_socket_close);
11639 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
11640 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
11641 hlua_class_function(L, "setoption", hlua_socket_setoption);
11642 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011643
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011644 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011645
11646 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011647 lua_pushstring(L, "__gc");
11648 lua_pushcclosure(L, hlua_socket_gc, 0);
11649 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011650
11651 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011652 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011653
Thierry Fournieraafc7772020-12-04 11:47:47 +010011654 lua_atpanic(L, hlua_panic_safe);
11655
11656 return L;
11657}
11658
11659void hlua_init(void) {
11660 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011661 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010011662#ifdef USE_OPENSSL
11663 struct srv_kw *kw;
11664 int tmp_error;
11665 char *error;
11666 char *args[] = { /* SSL client configuration. */
11667 "ssl",
11668 "verify",
11669 "none",
11670 NULL
11671 };
11672#endif
11673
11674 /* Init post init function list head */
11675 for (i = 0; i < MAX_THREADS + 1; i++)
11676 LIST_INIT(&hlua_init_functions[i]);
11677
11678 /* Init state for common/shared lua parts */
11679 hlua_state_id = 0;
11680 ha_set_tid(0);
11681 hlua_states[0] = hlua_init_state(0);
11682
11683 /* Init state 1 for thread 0. We have at least one thread. */
11684 hlua_state_id = 1;
11685 ha_set_tid(0);
11686 hlua_states[1] = hlua_init_state(1);
11687
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011688 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020011689 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011690 if (!socket_proxy) {
11691 fprintf(stderr, "Lua init: %s\n", errmsg);
11692 exit(1);
11693 }
11694 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011695
11696 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011697 socket_tcp = new_server(socket_proxy);
11698 if (!socket_tcp) {
11699 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
11700 exit(1);
11701 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011702
11703#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011704 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011705 socket_ssl = new_server(socket_proxy);
11706 if (!socket_ssl) {
11707 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
11708 exit(1);
11709 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011710
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011711 socket_ssl->use_ssl = 1;
11712 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011713
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011714 for (i = 0; args[i] != NULL; i++) {
11715 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011716 /*
11717 *
11718 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011719 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011720 * features like client certificates and ssl_verify.
11721 *
11722 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011723 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011724 if (tmp_error != 0) {
11725 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
11726 abort(); /* This must be never arrives because the command line
11727 not editable by the user. */
11728 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011729 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011730 }
11731 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011732#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010011733
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011734}
Willy Tarreaubb57d942016-12-21 19:04:56 +010011735
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011736static void hlua_deinit()
11737{
Willy Tarreau186f3762020-12-04 11:48:12 +010011738 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011739 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
11740
11741 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
11742 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010011743
11744 for (thr = 0; thr < MAX_THREADS+1; thr++) {
11745 if (hlua_states[thr])
11746 lua_close(hlua_states[thr]);
11747 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011748
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011749 free_server(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011750
Willy Tarreau0f143af2021-03-05 10:41:48 +010011751#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011752 free_server(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010011753#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011754
11755 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011756}
11757
11758REGISTER_POST_DEINIT(hlua_deinit);
11759
Willy Tarreau80713382018-11-26 10:19:54 +010011760static void hlua_register_build_options(void)
11761{
Willy Tarreaubb57d942016-12-21 19:04:56 +010011762 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010011763
Willy Tarreaubb57d942016-12-21 19:04:56 +010011764 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
11765 hap_register_build_opts(ptr, 1);
11766}
Willy Tarreau80713382018-11-26 10:19:54 +010011767
11768INITCALL0(STG_REGISTER, hlua_register_build_options);