blob: 7e68d0b33bc6b0f6f922d6dbc62289ec15ddc3e2 [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 Faulet4ad73102020-03-05 11:07:31 +01007485 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007486 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007487 return 0;
7488}
7489
Christopher Faulet700d9e82020-01-31 12:21:52 +01007490/*
7491 *
7492 *
7493 * Class REPLY
7494 *
7495 *
7496 */
7497
7498/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
7499 * free slots, the function fails and returns 0;
7500 */
7501static int hlua_txn_reply_new(lua_State *L)
7502{
7503 struct hlua_txn *htxn;
7504 const char *reason, *body = NULL;
7505 int ret, status;
7506
7507 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007508 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007509 hlua_pusherror(L, "txn object is not an HTTP transaction.");
7510 WILL_LJMP(lua_error(L));
7511 }
7512
7513 /* Default value */
7514 status = 200;
7515 reason = http_get_reason(status);
7516
7517 if (lua_istable(L, 2)) {
7518 /* load status and reason from the table argument at index 2 */
7519 ret = lua_getfield(L, 2, "status");
7520 if (ret == LUA_TNIL)
7521 goto reason;
7522 else if (ret != LUA_TNUMBER) {
7523 /* invalid status: ignore the reason */
7524 goto body;
7525 }
7526 status = lua_tointeger(L, -1);
7527
7528 reason:
7529 lua_pop(L, 1); /* restore the stack: remove status */
7530 ret = lua_getfield(L, 2, "reason");
7531 if (ret == LUA_TSTRING)
7532 reason = lua_tostring(L, -1);
7533
7534 body:
7535 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
7536 ret = lua_getfield(L, 2, "body");
7537 if (ret == LUA_TSTRING)
7538 body = lua_tostring(L, -1);
7539 lua_pop(L, 1); /* restore the stack: remove body */
7540 }
7541
7542 /* Create the Reply table */
7543 lua_newtable(L);
7544
7545 /* Add status element */
7546 lua_pushstring(L, "status");
7547 lua_pushinteger(L, status);
7548 lua_settable(L, -3);
7549
7550 /* Add reason element */
7551 reason = http_get_reason(status);
7552 lua_pushstring(L, "reason");
7553 lua_pushstring(L, reason);
7554 lua_settable(L, -3);
7555
7556 /* Add body element, nil if undefined */
7557 lua_pushstring(L, "body");
7558 if (body)
7559 lua_pushstring(L, body);
7560 else
7561 lua_pushnil(L);
7562 lua_settable(L, -3);
7563
7564 /* Add headers element */
7565 lua_pushstring(L, "headers");
7566 lua_newtable(L);
7567
7568 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7569 if (lua_istable(L, 2)) {
7570 /* load headers from the table argument at index 2. If it is a table, copy it. */
7571 ret = lua_getfield(L, 2, "headers");
7572 if (ret == LUA_TTABLE) {
7573 /* stack: [ ... <headers:table>, <table> ] */
7574 lua_pushnil(L);
7575 while (lua_next(L, -2) != 0) {
7576 /* stack: [ ... <headers:table>, <table>, k, v] */
7577 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
7578 /* invalid value type, skip it */
7579 lua_pop(L, 1);
7580 continue;
7581 }
7582
7583
7584 /* Duplicate the key and swap it with the value. */
7585 lua_pushvalue(L, -2);
7586 lua_insert(L, -2);
7587 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
7588
7589 lua_newtable(L);
7590 lua_insert(L, -2);
7591 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
7592
7593 if (lua_isstring(L, -1)) {
7594 /* push the value in the inner table */
7595 lua_rawseti(L, -2, 1);
7596 }
7597 else { /* table */
7598 lua_pushnil(L);
7599 while (lua_next(L, -2) != 0) {
7600 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
7601 if (!lua_isstring(L, -1)) {
7602 /* invalid value type, skip it*/
7603 lua_pop(L, 1);
7604 continue;
7605 }
7606 /* push the value in the inner table */
7607 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
7608 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
7609 }
7610 lua_pop(L, 1);
7611 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
7612 }
7613
7614 /* push (k,v) on the stack in the headers table:
7615 * stack: [ ... <headers:table>, <table>, k, k, v ]
7616 */
7617 lua_settable(L, -5);
7618 /* stack: [ ... <headers:table>, <table>, k ] */
7619 }
7620 }
7621 lua_pop(L, 1);
7622 }
7623 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7624 lua_settable(L, -3);
7625 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
7626
7627 /* Pop a class sesison metatable and affect it to the userdata. */
7628 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
7629 lua_setmetatable(L, -2);
7630 return 1;
7631}
7632
7633/* Set the reply status code, and optionally the reason. If no reason is
7634 * provided, the default one corresponding to the status code is used.
7635 */
7636__LJMP static int hlua_txn_reply_set_status(lua_State *L)
7637{
7638 int status = MAY_LJMP(luaL_checkinteger(L, 2));
7639 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
7640
7641 /* First argument (self) must be a table */
7642 luaL_checktype(L, 1, LUA_TTABLE);
7643
7644 if (status < 100 || status > 599) {
7645 lua_pushboolean(L, 0);
7646 return 1;
7647 }
7648 if (!reason)
7649 reason = http_get_reason(status);
7650
7651 lua_pushinteger(L, status);
7652 lua_setfield(L, 1, "status");
7653
7654 lua_pushstring(L, reason);
7655 lua_setfield(L, 1, "reason");
7656
7657 lua_pushboolean(L, 1);
7658 return 1;
7659}
7660
7661/* Add a header into the reply object. Each header name is associated to an
7662 * array of values in the "headers" table. If the header name is not found, a
7663 * new entry is created.
7664 */
7665__LJMP static int hlua_txn_reply_add_header(lua_State *L)
7666{
7667 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7668 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
7669 int ret;
7670
7671 /* First argument (self) must be a table */
7672 luaL_checktype(L, 1, LUA_TTABLE);
7673
7674 /* Push in the stack the "headers" entry. */
7675 ret = lua_getfield(L, 1, "headers");
7676 if (ret != LUA_TTABLE) {
7677 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
7678 WILL_LJMP(lua_error(L));
7679 }
7680
7681 /* check if the header is already registered. If not, register it. */
7682 ret = lua_getfield(L, -1, name);
7683 if (ret == LUA_TNIL) {
7684 /* Entry not found. */
7685 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
7686
7687 /* Insert the new header name in the array in the top of the stack.
7688 * It left the new array in the top of the stack.
7689 */
7690 lua_newtable(L);
7691 lua_pushstring(L, name);
7692 lua_pushvalue(L, -2);
7693 lua_settable(L, -4);
7694 }
7695 else if (ret != LUA_TTABLE) {
7696 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
7697 WILL_LJMP(lua_error(L));
7698 }
7699
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07007700 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01007701 * the header value as new entry.
7702 */
7703 lua_pushstring(L, value);
7704 ret = lua_rawlen(L, -2);
7705 lua_rawseti(L, -2, ret + 1);
7706
7707 lua_pushboolean(L, 1);
7708 return 1;
7709}
7710
7711/* Remove all occurrences of a given header name. */
7712__LJMP static int hlua_txn_reply_del_header(lua_State *L)
7713{
7714 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7715 int ret;
7716
7717 /* First argument (self) must be a table */
7718 luaL_checktype(L, 1, LUA_TTABLE);
7719
7720 /* Push in the stack the "headers" entry. */
7721 ret = lua_getfield(L, 1, "headers");
7722 if (ret != LUA_TTABLE) {
7723 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
7724 WILL_LJMP(lua_error(L));
7725 }
7726
7727 lua_pushstring(L, name);
7728 lua_pushnil(L);
7729 lua_settable(L, -3);
7730
7731 lua_pushboolean(L, 1);
7732 return 1;
7733}
7734
7735/* Set the reply's body. Overwrite any existing entry. */
7736__LJMP static int hlua_txn_reply_set_body(lua_State *L)
7737{
7738 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
7739
7740 /* First argument (self) must be a table */
7741 luaL_checktype(L, 1, LUA_TTABLE);
7742
7743 lua_pushstring(L, payload);
7744 lua_setfield(L, 1, "body");
7745
7746 lua_pushboolean(L, 1);
7747 return 1;
7748}
7749
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007750__LJMP static int hlua_log(lua_State *L)
7751{
7752 int level;
7753 const char *msg;
7754
7755 MAY_LJMP(check_args(L, 2, "log"));
7756 level = MAY_LJMP(luaL_checkinteger(L, 1));
7757 msg = MAY_LJMP(luaL_checkstring(L, 2));
7758
7759 if (level < 0 || level >= NB_LOG_LEVELS)
7760 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7761
7762 hlua_sendlog(NULL, level, msg);
7763 return 0;
7764}
7765
7766__LJMP static int hlua_log_debug(lua_State *L)
7767{
7768 const char *msg;
7769
7770 MAY_LJMP(check_args(L, 1, "debug"));
7771 msg = MAY_LJMP(luaL_checkstring(L, 1));
7772 hlua_sendlog(NULL, LOG_DEBUG, msg);
7773 return 0;
7774}
7775
7776__LJMP static int hlua_log_info(lua_State *L)
7777{
7778 const char *msg;
7779
7780 MAY_LJMP(check_args(L, 1, "info"));
7781 msg = MAY_LJMP(luaL_checkstring(L, 1));
7782 hlua_sendlog(NULL, LOG_INFO, msg);
7783 return 0;
7784}
7785
7786__LJMP static int hlua_log_warning(lua_State *L)
7787{
7788 const char *msg;
7789
7790 MAY_LJMP(check_args(L, 1, "warning"));
7791 msg = MAY_LJMP(luaL_checkstring(L, 1));
7792 hlua_sendlog(NULL, LOG_WARNING, msg);
7793 return 0;
7794}
7795
7796__LJMP static int hlua_log_alert(lua_State *L)
7797{
7798 const char *msg;
7799
7800 MAY_LJMP(check_args(L, 1, "alert"));
7801 msg = MAY_LJMP(luaL_checkstring(L, 1));
7802 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007803 return 0;
7804}
7805
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007806__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007807{
7808 int wakeup_ms = lua_tointeger(L, -1);
7809 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02007810 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007811 return 0;
7812}
7813
7814__LJMP static int hlua_sleep(lua_State *L)
7815{
7816 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007817 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007818
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007819 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007820
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007821 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007822 wakeup_ms = tick_add(now_ms, delay);
7823 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007824
Willy Tarreau9635e032018-10-16 17:52:55 +02007825 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007826 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007827}
7828
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007829__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007830{
7831 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007832 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007833
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007834 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007835
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007836 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007837 wakeup_ms = tick_add(now_ms, delay);
7838 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007839
Willy Tarreau9635e032018-10-16 17:52:55 +02007840 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007841 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007842}
7843
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007844/* This functionis an LUA binding. it permits to give back
7845 * the hand at the HAProxy scheduler. It is used when the
7846 * LUA processing consumes a lot of time.
7847 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007848__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007849{
7850 return 0;
7851}
7852
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007853__LJMP static int hlua_yield(lua_State *L)
7854{
Willy Tarreau9635e032018-10-16 17:52:55 +02007855 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007856 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007857}
7858
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007859/* This function change the nice of the currently executed
7860 * task. It is used set low or high priority at the current
7861 * task.
7862 */
Willy Tarreau59551662015-03-10 14:23:13 +01007863__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007864{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007865 struct hlua *hlua;
7866 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007867
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007868 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007869 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007870
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007871 /* Get hlua struct, or NULL if we execute from main lua state */
7872 hlua = hlua_gethlua(L);
7873
7874 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007875 if (!hlua || !hlua->task)
7876 return 0;
7877
7878 if (nice < -1024)
7879 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007880 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007881 nice = 1024;
7882
7883 hlua->task->nice = nice;
7884 return 0;
7885}
7886
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007887/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007888 * HAProxy task subsystem when the task is awaked. The LUA runtime can
7889 * return an E_AGAIN signal, the emmiter of this signal must set a
7890 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007891 *
7892 * Task wrapper are longjmp safe because the only one Lua code
7893 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007894 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01007895struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007896{
Olivier Houchard9f6af332018-05-25 14:04:04 +02007897 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007898 enum hlua_exec status;
7899
Christopher Faulet5bc99722018-04-25 10:34:45 +02007900 if (task->thread_mask == MAX_THREADS_MASK)
7901 task_set_affinity(task, tid_bit);
7902
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007903 /* If it is the first call to the task, we must initialize the
7904 * execution timeouts.
7905 */
7906 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007907 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007908
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007909 /* Execute the Lua code. */
7910 status = hlua_ctx_resume(hlua, 1);
7911
7912 switch (status) {
7913 /* finished or yield */
7914 case HLUA_E_OK:
7915 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007916 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02007917 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007918 break;
7919
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01007920 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01007921 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02007922 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007923 break;
7924
7925 /* finished with error. */
7926 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007927 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007928 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007929 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007930 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007931 break;
7932
7933 case HLUA_E_ERR:
7934 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007935 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007936 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007937 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007938 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007939 break;
7940 }
Emeric Brun253e53e2017-10-17 18:58:40 +02007941 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007942}
7943
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007944/* This function is an LUA binding that register LUA function to be
7945 * executed after the HAProxy configuration parsing and before the
7946 * HAProxy scheduler starts. This function expect only one LUA
7947 * argument that is a function. This function returns nothing, but
7948 * throws if an error is encountered.
7949 */
7950__LJMP static int hlua_register_init(lua_State *L)
7951{
7952 struct hlua_init_function *init;
7953 int ref;
7954
7955 MAY_LJMP(check_args(L, 1, "register_init"));
7956
7957 ref = MAY_LJMP(hlua_checkfunction(L, 1));
7958
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007959 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007960 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007961 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007962
7963 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02007964 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007965 return 0;
7966}
7967
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007968/* This functio is an LUA binding. It permits to register a task
7969 * executed in parallel of the main HAroxy activity. The task is
7970 * created and it is set in the HAProxy scheduler. It can be called
7971 * from the "init" section, "post init" or during the runtime.
7972 *
7973 * Lua prototype:
7974 *
7975 * <none> core.register_task(<function>)
7976 */
7977static int hlua_register_task(lua_State *L)
7978{
Christopher Faulet5294ec02021-04-12 12:24:47 +02007979 struct hlua *hlua = NULL;
7980 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007981 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01007982 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007983
7984 MAY_LJMP(check_args(L, 1, "register_task"));
7985
7986 ref = MAY_LJMP(hlua_checkfunction(L, 1));
7987
Thierry Fournier75fc0292020-11-28 13:18:56 +01007988 /* Get the reference state. If the reference is NULL, L is the master
7989 * state, otherwise hlua->T is.
7990 */
7991 hlua = hlua_gethlua(L);
7992 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01007993 /* we are in runtime processing */
7994 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01007995 else
Thierry Fournier021d9862020-11-28 23:42:03 +01007996 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01007997 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01007998
Willy Tarreaubafbe012017-11-24 17:34:44 +01007999 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008000 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008001 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008002 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008003
Thierry Fournier59f11be2020-11-29 00:37:41 +01008004 /* We are in the common lua state, execute the task anywhere,
8005 * otherwise, inherit the current thread identifier
8006 */
8007 if (state_id == 0)
8008 task = task_new(MAX_THREADS_MASK);
8009 else
8010 task = task_new(tid_bit);
Willy Tarreaue09101e2018-10-16 17:37:12 +02008011 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008012 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008013
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008014 task->context = hlua;
8015 task->process = hlua_process_task;
8016
Thierry Fournier021d9862020-11-28 23:42:03 +01008017 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008018 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008019
8020 /* Restore the function in the stack. */
8021 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8022 hlua->nargs = 0;
8023
8024 /* Schedule task. */
8025 task_schedule(task, now_ms);
8026
8027 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008028
8029 alloc_error:
8030 task_destroy(task);
8031 hlua_ctx_destroy(hlua);
8032 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8033 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008034}
8035
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008036/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8037 * doesn't allow "yield" functions because the HAProxy engine cannot
8038 * resume converters.
8039 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008040static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008041{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008042 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008043 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008044 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008045
Willy Tarreaube508f12016-03-10 11:47:01 +01008046 if (!stream)
8047 return 0;
8048
Willy Tarreau87b09662015-04-03 00:22:06 +02008049 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008050 * Lua context can be not initialized. This behavior
8051 * permits to save performances because a systematic
8052 * Lua initialization cause 5% performances loss.
8053 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008054 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008055 struct hlua *hlua;
8056
8057 hlua = pool_alloc(pool_head_hlua);
8058 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008059 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8060 return 0;
8061 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008062 HLUA_INIT(hlua);
8063 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008064 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008065 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8066 return 0;
8067 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008068 }
8069
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008070 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008071 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008072
8073 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008074 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008075 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8076 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008077 else
8078 error = "critical error";
8079 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008080 return 0;
8081 }
8082
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008083 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008084 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008085 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008086 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008087 return 0;
8088 }
8089
8090 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008091 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008092
8093 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008094 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008095 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008096 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008097 return 0;
8098 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008099 hlua_smp2lua(stream->hlua->T, smp);
8100 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008101
8102 /* push keywords in the stack. */
8103 if (arg_p) {
8104 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008105 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008106 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008107 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008108 return 0;
8109 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008110 hlua_arg2lua(stream->hlua->T, arg_p);
8111 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008112 }
8113 }
8114
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008115 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008116 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008117
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008118 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008119 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008120 }
8121
8122 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008123 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008124 /* finished. */
8125 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008126 /* If the stack is empty, the function fails. */
8127 if (lua_gettop(stream->hlua->T) <= 0)
8128 return 0;
8129
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008130 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008131 hlua_lua2smp(stream->hlua->T, -1, smp);
8132 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008133 return 1;
8134
8135 /* yield. */
8136 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008137 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008138 return 0;
8139
8140 /* finished with error. */
8141 case HLUA_E_ERRMSG:
8142 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008143 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008144 fcn->name, lua_tostring(stream->hlua->T, -1));
8145 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008146 return 0;
8147
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008148 case HLUA_E_ETMOUT:
8149 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8150 return 0;
8151
8152 case HLUA_E_NOMEM:
8153 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8154 return 0;
8155
8156 case HLUA_E_YIELD:
8157 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8158 return 0;
8159
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008160 case HLUA_E_ERR:
8161 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008162 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008163 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008164
8165 default:
8166 return 0;
8167 }
8168}
8169
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008170/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8171 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008172 * resume sample-fetches. This function will be called by the sample
8173 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008174 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008175static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8176 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008177{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008178 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008179 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008180 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008181 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008182
Willy Tarreaube508f12016-03-10 11:47:01 +01008183 if (!stream)
8184 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008185
Willy Tarreau87b09662015-04-03 00:22:06 +02008186 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008187 * Lua context can be not initialized. This behavior
8188 * permits to save performances because a systematic
8189 * Lua initialization cause 5% performances loss.
8190 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008191 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008192 struct hlua *hlua;
8193
8194 hlua = pool_alloc(pool_head_hlua);
8195 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008196 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8197 return 0;
8198 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008199 hlua->T = NULL;
8200 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008201 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008202 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8203 return 0;
8204 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008205 }
8206
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008207 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008208 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008209
8210 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008211 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008212 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8213 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008214 else
8215 error = "critical error";
8216 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008217 return 0;
8218 }
8219
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008220 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008221 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008222 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008223 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008224 return 0;
8225 }
8226
8227 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008228 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008229
8230 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008231 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008232 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008233 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008234 return 0;
8235 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008236 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008237
8238 /* push keywords in the stack. */
8239 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8240 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008241 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008242 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008243 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008244 return 0;
8245 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008246 hlua_arg2lua(stream->hlua->T, arg_p);
8247 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008248 }
8249
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008250 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008251 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008252
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008253 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008254 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008255 }
8256
8257 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008258 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008259 /* finished. */
8260 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008261 /* If the stack is empty, the function fails. */
8262 if (lua_gettop(stream->hlua->T) <= 0)
8263 return 0;
8264
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008265 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008266 hlua_lua2smp(stream->hlua->T, -1, smp);
8267 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008268
8269 /* Set the end of execution flag. */
8270 smp->flags &= ~SMP_F_MAY_CHANGE;
8271 return 1;
8272
8273 /* yield. */
8274 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008275 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008276 return 0;
8277
8278 /* finished with error. */
8279 case HLUA_E_ERRMSG:
8280 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008281 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008282 fcn->name, lua_tostring(stream->hlua->T, -1));
8283 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008284 return 0;
8285
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008286 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008287 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8288 return 0;
8289
8290 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008291 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8292 return 0;
8293
8294 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008295 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8296 return 0;
8297
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008298 case HLUA_E_ERR:
8299 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008300 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008301 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008302
8303 default:
8304 return 0;
8305 }
8306}
8307
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008308/* This function is an LUA binding used for registering
8309 * "sample-conv" functions. It expects a converter name used
8310 * in the haproxy configuration file, and an LUA function.
8311 */
8312__LJMP static int hlua_register_converters(lua_State *L)
8313{
8314 struct sample_conv_kw_list *sck;
8315 const char *name;
8316 int ref;
8317 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008318 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008319 struct sample_conv *sc;
8320 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008321
8322 MAY_LJMP(check_args(L, 2, "register_converters"));
8323
8324 /* First argument : converter name. */
8325 name = MAY_LJMP(luaL_checkstring(L, 1));
8326
8327 /* Second argument : lua function. */
8328 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8329
Thierry Fournierf67442e2020-11-28 20:41:07 +01008330 /* Check if the converter is already registered */
8331 trash = get_trash_chunk();
8332 chunk_printf(trash, "lua.%s", name);
8333 sc = find_sample_conv(trash->area, trash->data);
8334 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008335 fcn = sc->private;
8336 if (fcn->function_ref[hlua_state_id] != -1) {
8337 ha_warning("Trying to register converter 'lua.%s' more than once. "
8338 "This will become a hard error in version 2.5.\n", name);
8339 }
8340 fcn->function_ref[hlua_state_id] = ref;
8341 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008342 }
8343
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008344 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008345 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008346 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008347 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008348 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008349 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008350 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008351
8352 /* Fill fcn. */
8353 fcn->name = strdup(name);
8354 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008355 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008356 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008357
8358 /* List head */
8359 sck->list.n = sck->list.p = NULL;
8360
8361 /* converter keyword. */
8362 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008363 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008364 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008365 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008366
8367 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8368 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008369 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 +01008370 sck->kw[0].val_args = NULL;
8371 sck->kw[0].in_type = SMP_T_STR;
8372 sck->kw[0].out_type = SMP_T_STR;
8373 sck->kw[0].private = fcn;
8374
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008375 /* Register this new converter */
8376 sample_register_convs(sck);
8377
8378 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008379
8380 alloc_error:
8381 release_hlua_function(fcn);
8382 ha_free(&sck);
8383 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8384 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008385}
8386
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008387/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008388 * "sample-fetch" functions. It expects a converter name used
8389 * in the haproxy configuration file, and an LUA function.
8390 */
8391__LJMP static int hlua_register_fetches(lua_State *L)
8392{
8393 const char *name;
8394 int ref;
8395 int len;
8396 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008397 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008398 struct sample_fetch *sf;
8399 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008400
8401 MAY_LJMP(check_args(L, 2, "register_fetches"));
8402
8403 /* First argument : sample-fetch name. */
8404 name = MAY_LJMP(luaL_checkstring(L, 1));
8405
8406 /* Second argument : lua function. */
8407 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8408
Thierry Fournierf67442e2020-11-28 20:41:07 +01008409 /* Check if the sample-fetch is already registered */
8410 trash = get_trash_chunk();
8411 chunk_printf(trash, "lua.%s", name);
8412 sf = find_sample_fetch(trash->area, trash->data);
8413 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008414 fcn = sf->private;
8415 if (fcn->function_ref[hlua_state_id] != -1) {
8416 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8417 "This will become a hard error in version 2.5.\n", name);
8418 }
8419 fcn->function_ref[hlua_state_id] = ref;
8420 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008421 }
8422
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008423 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008424 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008425 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008426 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008427 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008428 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008429 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008430
8431 /* Fill fcn. */
8432 fcn->name = strdup(name);
8433 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008434 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008435 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008436
8437 /* List head */
8438 sfk->list.n = sfk->list.p = NULL;
8439
8440 /* sample-fetch keyword. */
8441 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008442 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008443 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008444 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008445
8446 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8447 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008448 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 +01008449 sfk->kw[0].val_args = NULL;
8450 sfk->kw[0].out_type = SMP_T_STR;
8451 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8452 sfk->kw[0].val = 0;
8453 sfk->kw[0].private = fcn;
8454
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008455 /* Register this new fetch. */
8456 sample_register_fetches(sfk);
8457
8458 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008459
8460 alloc_error:
8461 release_hlua_function(fcn);
8462 ha_free(&sfk);
8463 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8464 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008465}
8466
Christopher Faulet501465d2020-02-26 14:54:16 +01008467/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008468 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008469__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008470{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008471 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008472 unsigned int delay;
8473 unsigned int wakeup_ms;
8474
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008475 /* Get hlua struct, or NULL if we execute from main lua state */
8476 hlua = hlua_gethlua(L);
8477 if (!hlua) {
8478 return 0;
8479 }
8480
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008481 MAY_LJMP(check_args(L, 1, "wake_time"));
8482
8483 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8484 wakeup_ms = tick_add(now_ms, delay);
8485 hlua->wake_time = wakeup_ms;
8486 return 0;
8487}
8488
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008489/* This function is a wrapper to execute each LUA function declared as an action
8490 * wrapper during the initialisation period. This function may return any
8491 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8492 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8493 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008494 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008495static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02008496 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008497{
8498 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008499 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008500 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008501 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008502
8503 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008504 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
8505 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
8506 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
8507 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008508 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008509 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008510 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008511 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008512
Willy Tarreau87b09662015-04-03 00:22:06 +02008513 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008514 * Lua context can be not initialized. This behavior
8515 * permits to save performances because a systematic
8516 * Lua initialization cause 5% performances loss.
8517 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008518 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008519 struct hlua *hlua;
8520
8521 hlua = pool_alloc(pool_head_hlua);
8522 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008523 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008524 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008525 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008526 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008527 HLUA_INIT(hlua);
8528 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008529 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 +01008530 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008531 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008532 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008533 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008534 }
8535
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008536 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008537 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008538
8539 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008540 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008541 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
8542 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008543 else
8544 error = "critical error";
8545 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008546 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008547 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008548 }
8549
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008550 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008551 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008552 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008553 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008554 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008555 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008556 }
8557
8558 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008559 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 +01008560
Willy Tarreau87b09662015-04-03 00:22:06 +02008561 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008562 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008563 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008564 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008565 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008566 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008567 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008568 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008569
8570 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008571 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008572 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008573 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008574 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008575 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008576 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008577 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008578 lua_pushstring(s->hlua->T, *arg);
8579 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008580 }
8581
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008582 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008583 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008584
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008585 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008586 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008587 }
8588
8589 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01008590 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008591 /* finished. */
8592 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008593 /* Catch the return value */
8594 if (lua_gettop(s->hlua->T) > 0)
8595 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008596
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008597 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02008598 if (act_ret == ACT_RET_YIELD) {
8599 if (flags & ACT_OPT_FINAL)
8600 goto err_yield;
8601
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008602 if (dir == SMP_OPT_DIR_REQ)
8603 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8604 s->hlua->wake_time);
8605 else
8606 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8607 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008608 }
8609 goto end;
8610
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008611 /* yield. */
8612 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008613 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008614 if (dir == SMP_OPT_DIR_REQ)
8615 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8616 s->hlua->wake_time);
8617 else
8618 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8619 s->hlua->wake_time);
8620
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008621 /* Some actions can be wake up when a "write" event
8622 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008623 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008624 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02008625 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008626 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008627 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008628 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008629 act_ret = ACT_RET_YIELD;
8630 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008631
8632 /* finished with error. */
8633 case HLUA_E_ERRMSG:
8634 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008635 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008636 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008637 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008638 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008639
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008640 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008641 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008642 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008643
8644 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008645 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008646 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008647
8648 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02008649 err_yield:
8650 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008651 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008652 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008653 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008654
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008655 case HLUA_E_ERR:
8656 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008657 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008658 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008659
8660 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008661 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008662 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008663
8664 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02008665 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008666 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008667 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008668}
8669
Willy Tarreau144f84a2021-03-02 16:09:26 +01008670struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008671{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008672 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008673
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008674 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02008675 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02008676 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008677}
8678
8679static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8680{
8681 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008682 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008683 struct task *task;
8684 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008685 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008686
Willy Tarreaubafbe012017-11-24 17:34:44 +01008687 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008688 if (!hlua) {
8689 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008690 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008691 return 0;
8692 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008693 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008694 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008695 ctx->ctx.hlua_apptcp.flags = 0;
8696
8697 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008698 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008699 if (!task) {
8700 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008701 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008702 return 0;
8703 }
8704 task->nice = 0;
8705 task->context = ctx;
8706 task->process = hlua_applet_wakeup;
8707 ctx->ctx.hlua_apptcp.task = task;
8708
8709 /* In the execution wrappers linked with a stream, the
8710 * Lua context can be not initialized. This behavior
8711 * permits to save performances because a systematic
8712 * Lua initialization cause 5% performances loss.
8713 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008714 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 +02008715 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008716 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008717 return 0;
8718 }
8719
8720 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008721 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008722
8723 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008724 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008725 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8726 error = lua_tostring(hlua->T, -1);
8727 else
8728 error = "critical error";
8729 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008730 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008731 return 0;
8732 }
8733
8734 /* Check stack available size. */
8735 if (!lua_checkstack(hlua->T, 1)) {
8736 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008737 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008738 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008739 return 0;
8740 }
8741
8742 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008743 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008744
8745 /* Create and and push object stream in the stack. */
8746 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
8747 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008748 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008749 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008750 return 0;
8751 }
8752 hlua->nargs = 1;
8753
8754 /* push keywords in the stack. */
8755 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8756 if (!lua_checkstack(hlua->T, 1)) {
8757 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008758 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008759 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008760 return 0;
8761 }
8762 lua_pushstring(hlua->T, *arg);
8763 hlua->nargs++;
8764 }
8765
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008766 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008767
8768 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008769 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01008770 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008771
8772 return 1;
8773}
8774
Willy Tarreau60409db2019-08-21 14:14:50 +02008775void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008776{
8777 struct stream_interface *si = ctx->owner;
8778 struct stream *strm = si_strm(si);
8779 struct channel *res = si_ic(si);
8780 struct act_rule *rule = ctx->rule;
8781 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008782 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008783
8784 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02008785 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
8786 /* eat the whole request */
8787 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008788 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02008789 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008790
8791 /* If the stream is disconnect or closed, ldo nothing. */
8792 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8793 return;
8794
8795 /* Execute the function. */
8796 switch (hlua_ctx_resume(hlua, 1)) {
8797 /* finished. */
8798 case HLUA_E_OK:
8799 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8800
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008801 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02008802 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008803 res->flags |= CF_READ_NULL;
8804 si_shutr(si);
8805 return;
8806
8807 /* yield. */
8808 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01008809 if (hlua->wake_time != TICK_ETERNITY)
8810 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008811 return;
8812
8813 /* finished with error. */
8814 case HLUA_E_ERRMSG:
8815 /* Display log. */
8816 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008817 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008818 lua_pop(hlua->T, 1);
8819 goto error;
8820
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008821 case HLUA_E_ETMOUT:
8822 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008823 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008824 goto error;
8825
8826 case HLUA_E_NOMEM:
8827 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008828 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008829 goto error;
8830
8831 case HLUA_E_YIELD: /* unexpected */
8832 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008833 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008834 goto error;
8835
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008836 case HLUA_E_ERR:
8837 /* Display log. */
8838 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008839 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008840 goto error;
8841
8842 default:
8843 goto error;
8844 }
8845
8846error:
8847
8848 /* For all other cases, just close the stream. */
8849 si_shutw(si);
8850 si_shutr(si);
8851 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8852}
8853
8854static void hlua_applet_tcp_release(struct appctx *ctx)
8855{
Olivier Houchard3f795f72019-04-17 22:51:06 +02008856 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008857 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008858 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008859 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008860}
8861
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008862/* The function returns 1 if the initialisation is complete, 0 if
8863 * an errors occurs and -1 if more data are required for initializing
8864 * the applet.
8865 */
8866static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8867{
8868 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008869 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008870 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008871 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008872 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008873 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008874
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008875 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01008876 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008877 if (!hlua) {
8878 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008879 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008880 return 0;
8881 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008882 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008883 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008884 ctx->ctx.hlua_apphttp.left_bytes = -1;
8885 ctx->ctx.hlua_apphttp.flags = 0;
8886
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01008887 if (txn->req.flags & HTTP_MSGF_VER_11)
8888 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
8889
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008890 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008891 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008892 if (!task) {
8893 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008894 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008895 return 0;
8896 }
8897 task->nice = 0;
8898 task->context = ctx;
8899 task->process = hlua_applet_wakeup;
8900 ctx->ctx.hlua_apphttp.task = task;
8901
8902 /* In the execution wrappers linked with a stream, the
8903 * Lua context can be not initialized. This behavior
8904 * permits to save performances because a systematic
8905 * Lua initialization cause 5% performances loss.
8906 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008907 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 +02008908 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008909 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008910 return 0;
8911 }
8912
8913 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008914 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008915
8916 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008917 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008918 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8919 error = lua_tostring(hlua->T, -1);
8920 else
8921 error = "critical error";
8922 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008923 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008924 return 0;
8925 }
8926
8927 /* Check stack available size. */
8928 if (!lua_checkstack(hlua->T, 1)) {
8929 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008930 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008931 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008932 return 0;
8933 }
8934
8935 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008936 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008937
8938 /* Create and and push object stream in the stack. */
8939 if (!hlua_applet_http_new(hlua->T, ctx)) {
8940 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008941 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008942 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008943 return 0;
8944 }
8945 hlua->nargs = 1;
8946
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008947 /* push keywords in the stack. */
8948 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8949 if (!lua_checkstack(hlua->T, 1)) {
8950 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008951 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008952 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008953 return 0;
8954 }
8955 lua_pushstring(hlua->T, *arg);
8956 hlua->nargs++;
8957 }
8958
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008959 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008960
8961 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008962 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008963
8964 return 1;
8965}
8966
Willy Tarreau60409db2019-08-21 14:14:50 +02008967void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008968{
8969 struct stream_interface *si = ctx->owner;
8970 struct stream *strm = si_strm(si);
8971 struct channel *req = si_oc(si);
8972 struct channel *res = si_ic(si);
8973 struct act_rule *rule = ctx->rule;
8974 struct proxy *px = strm->be;
8975 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
8976 struct htx *req_htx, *res_htx;
8977
8978 res_htx = htx_from_buf(&res->buf);
8979
8980 /* If the stream is disconnect or closed, ldo nothing. */
8981 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8982 goto out;
8983
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008984 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008985 if (!b_size(&res->buf)) {
8986 si_rx_room_blk(si);
8987 goto out;
8988 }
8989 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01008990 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008991 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
8992
8993 /* Set the currently running flag. */
8994 if (!HLUA_IS_RUNNING(hlua) &&
8995 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02008996 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008997 si_cant_get(si);
8998 goto out;
8999 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009000 }
9001
9002 /* Executes The applet if it is not done. */
9003 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9004
9005 /* Execute the function. */
9006 switch (hlua_ctx_resume(hlua, 1)) {
9007 /* finished. */
9008 case HLUA_E_OK:
9009 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9010 break;
9011
9012 /* yield. */
9013 case HLUA_E_AGAIN:
9014 if (hlua->wake_time != TICK_ETERNITY)
9015 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009016 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009017
9018 /* finished with error. */
9019 case HLUA_E_ERRMSG:
9020 /* Display log. */
9021 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009022 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009023 lua_pop(hlua->T, 1);
9024 goto error;
9025
9026 case HLUA_E_ETMOUT:
9027 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009028 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009029 goto error;
9030
9031 case HLUA_E_NOMEM:
9032 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009033 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009034 goto error;
9035
9036 case HLUA_E_YIELD: /* unexpected */
9037 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009038 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009039 goto error;
9040
9041 case HLUA_E_ERR:
9042 /* Display log. */
9043 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009044 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009045 goto error;
9046
9047 default:
9048 goto error;
9049 }
9050 }
9051
9052 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009053 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9054 goto done;
9055
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009056 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9057 goto error;
9058
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009059 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
9060 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009061 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9062 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009063 }
9064
9065 done:
9066 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009067 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009068 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009069 si_shutr(si);
9070 }
9071
9072 /* eat the whole request */
9073 if (co_data(req)) {
9074 req_htx = htx_from_buf(&req->buf);
9075 co_htx_skip(req, req_htx, co_data(req));
9076 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009077 }
9078 }
9079
9080 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009081 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009082 return;
9083
9084 error:
9085
9086 /* If we are in HTTP mode, and we are not send any
9087 * data, return a 500 server error in best effort:
9088 * if there is no room available in the buffer,
9089 * just close the connection.
9090 */
9091 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009092 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009093
9094 channel_erase(res);
9095 res->buf.data = b_data(err);
9096 memcpy(res->buf.area, b_head(err), b_data(err));
9097 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009098 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009099 }
9100 if (!(strm->flags & SF_ERR_MASK))
9101 strm->flags |= SF_ERR_RESOURCE;
9102 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9103 goto done;
9104}
9105
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009106static void hlua_applet_http_release(struct appctx *ctx)
9107{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009108 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009109 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009110 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009111 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009112}
9113
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009114/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009115 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009116 *
9117 * This function can fail with an abort() due to an Lua critical error.
9118 * We are in the configuration parsing process of HAProxy, this abort() is
9119 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009120 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009121static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9122 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009123{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009124 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009125 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009126
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009127 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009128 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009129 if (!rule->arg.hlua_rule) {
9130 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009131 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009132 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009133
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009134 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009135 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9136 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009137 if (!rule->arg.hlua_rule->args) {
9138 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009139 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009140 }
9141
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009142 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009143 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009144
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009145 /* Expect some arguments */
9146 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009147 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009148 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009149 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009150 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009151 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009152 if (!rule->arg.hlua_rule->args[i]) {
9153 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009154 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009155 }
9156 (*cur_arg)++;
9157 }
9158 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009159
Thierry FOURNIER42148732015-09-02 17:17:33 +02009160 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009161 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009162 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009163
9164 error:
9165 if (rule->arg.hlua_rule) {
9166 if (rule->arg.hlua_rule->args) {
9167 for (i = 0; i < fcn->nargs; i++)
9168 ha_free(&rule->arg.hlua_rule->args[i]);
9169 ha_free(&rule->arg.hlua_rule->args);
9170 }
9171 ha_free(&rule->arg.hlua_rule);
9172 }
9173 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009174}
9175
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009176static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9177 struct act_rule *rule, char **err)
9178{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009179 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009180
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009181 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009182 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009183 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009184 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009185 * the call of this analyzer.
9186 */
9187 if (rule->from != ACT_F_HTTP_REQ) {
9188 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9189 return ACT_RET_PRS_ERR;
9190 }
9191
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009192 /* Memory for the rule. */
9193 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9194 if (!rule->arg.hlua_rule) {
9195 memprintf(err, "out of memory error");
9196 return ACT_RET_PRS_ERR;
9197 }
9198
9199 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009200 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009201
9202 /* TODO: later accept arguments. */
9203 rule->arg.hlua_rule->args = NULL;
9204
9205 /* Add applet pointer in the rule. */
9206 rule->applet.obj_type = OBJ_TYPE_APPLET;
9207 rule->applet.name = fcn->name;
9208 rule->applet.init = hlua_applet_http_init;
9209 rule->applet.fct = hlua_applet_http_fct;
9210 rule->applet.release = hlua_applet_http_release;
9211 rule->applet.timeout = hlua_timeout_applet;
9212
9213 return ACT_RET_PRS_OK;
9214}
9215
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009216/* This function is an LUA binding used for registering
9217 * "sample-conv" functions. It expects a converter name used
9218 * in the haproxy configuration file, and an LUA function.
9219 */
9220__LJMP static int hlua_register_action(lua_State *L)
9221{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009222 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009223 const char *name;
9224 int ref;
9225 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009226 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009227 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009228 struct buffer *trash;
9229 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009230
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009231 /* Initialise the number of expected arguments at 0. */
9232 nargs = 0;
9233
9234 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9235 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009236
9237 /* First argument : converter name. */
9238 name = MAY_LJMP(luaL_checkstring(L, 1));
9239
9240 /* Second argument : environment. */
9241 if (lua_type(L, 2) != LUA_TTABLE)
9242 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9243
9244 /* Third argument : lua function. */
9245 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9246
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009247 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009248 if (lua_gettop(L) >= 4)
9249 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9250
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009251 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009252 lua_pushnil(L);
9253 while (lua_next(L, 2) != 0) {
9254 if (lua_type(L, -1) != LUA_TSTRING)
9255 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9256
Thierry Fournierf67442e2020-11-28 20:41:07 +01009257 /* Check if action exists */
9258 trash = get_trash_chunk();
9259 chunk_printf(trash, "lua.%s", name);
9260 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9261 akw = tcp_req_cont_action(trash->area);
9262 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9263 akw = tcp_res_cont_action(trash->area);
9264 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9265 akw = action_http_req_custom(trash->area);
9266 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9267 akw = action_http_res_custom(trash->area);
9268 } else {
9269 akw = NULL;
9270 }
9271 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009272 fcn = akw->private;
9273 if (fcn->function_ref[hlua_state_id] != -1) {
9274 ha_warning("Trying to register action 'lua.%s' more than once. "
9275 "This will become a hard error in version 2.5.\n", name);
9276 }
9277 fcn->function_ref[hlua_state_id] = ref;
9278
9279 /* pop the environment string. */
9280 lua_pop(L, 1);
9281 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009282 }
9283
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009284 /* Check required environment. Only accepted "http" or "tcp". */
9285 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009286 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009287 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009288 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009289 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009290 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009291 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009292
9293 /* Fill fcn. */
9294 fcn->name = strdup(name);
9295 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009296 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009297 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009298
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009299 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009300 fcn->nargs = nargs;
9301
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009302 /* List head */
9303 akl->list.n = akl->list.p = NULL;
9304
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009305 /* action keyword. */
9306 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009307 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009308 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009309 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009310
9311 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9312
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009313 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009314 akl->kw[0].private = fcn;
9315 akl->kw[0].parse = action_register_lua;
9316
9317 /* select the action registering point. */
9318 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9319 tcp_req_cont_keywords_register(akl);
9320 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9321 tcp_res_cont_keywords_register(akl);
9322 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9323 http_req_keywords_register(akl);
9324 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9325 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009326 else {
9327 release_hlua_function(fcn);
9328 if (akl)
9329 ha_free((char **)&(akl->kw[0].kw));
9330 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009331 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009332 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9333 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009334 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009335
9336 /* pop the environment string. */
9337 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009338
9339 /* reset for next loop */
9340 akl = NULL;
9341 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009342 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009343 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009344
9345 alloc_error:
9346 release_hlua_function(fcn);
9347 ha_free(&akl);
9348 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9349 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009350}
9351
9352static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9353 struct act_rule *rule, char **err)
9354{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009355 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009356
Christopher Faulet280f85b2019-07-15 15:02:04 +02009357 if (px->mode == PR_MODE_HTTP) {
9358 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009359 return ACT_RET_PRS_ERR;
9360 }
9361
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009362 /* Memory for the rule. */
9363 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9364 if (!rule->arg.hlua_rule) {
9365 memprintf(err, "out of memory error");
9366 return ACT_RET_PRS_ERR;
9367 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009368
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009369 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009370 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009371
9372 /* TODO: later accept arguments. */
9373 rule->arg.hlua_rule->args = NULL;
9374
9375 /* Add applet pointer in the rule. */
9376 rule->applet.obj_type = OBJ_TYPE_APPLET;
9377 rule->applet.name = fcn->name;
9378 rule->applet.init = hlua_applet_tcp_init;
9379 rule->applet.fct = hlua_applet_tcp_fct;
9380 rule->applet.release = hlua_applet_tcp_release;
9381 rule->applet.timeout = hlua_timeout_applet;
9382
9383 return 0;
9384}
9385
9386/* This function is an LUA binding used for registering
9387 * "sample-conv" functions. It expects a converter name used
9388 * in the haproxy configuration file, and an LUA function.
9389 */
9390__LJMP static int hlua_register_service(lua_State *L)
9391{
9392 struct action_kw_list *akl;
9393 const char *name;
9394 const char *env;
9395 int ref;
9396 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009397 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009398 struct buffer *trash;
9399 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009400
9401 MAY_LJMP(check_args(L, 3, "register_service"));
9402
9403 /* First argument : converter name. */
9404 name = MAY_LJMP(luaL_checkstring(L, 1));
9405
9406 /* Second argument : environment. */
9407 env = MAY_LJMP(luaL_checkstring(L, 2));
9408
9409 /* Third argument : lua function. */
9410 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9411
Thierry Fournierf67442e2020-11-28 20:41:07 +01009412 /* Check for service already registered */
9413 trash = get_trash_chunk();
9414 chunk_printf(trash, "lua.%s", name);
9415 akw = service_find(trash->area);
9416 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009417 fcn = akw->private;
9418 if (fcn->function_ref[hlua_state_id] != -1) {
9419 ha_warning("Trying to register service 'lua.%s' more than once. "
9420 "This will become a hard error in version 2.5.\n", name);
9421 }
9422 fcn->function_ref[hlua_state_id] = ref;
9423 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009424 }
9425
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009426 /* Allocate and fill the sample fetch keyword struct. */
9427 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9428 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009429 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009430 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009431 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009432 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009433
9434 /* Fill fcn. */
9435 len = strlen("<lua.>") + strlen(name) + 1;
9436 fcn->name = calloc(1, len);
9437 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009438 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009439 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009440 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009441
9442 /* List head */
9443 akl->list.n = akl->list.p = NULL;
9444
9445 /* converter keyword. */
9446 len = strlen("lua.") + strlen(name) + 1;
9447 akl->kw[0].kw = calloc(1, len);
9448 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009449 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009450
9451 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9452
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009453 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009454 if (strcmp(env, "tcp") == 0)
9455 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009456 else if (strcmp(env, "http") == 0)
9457 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009458 else {
9459 release_hlua_function(fcn);
9460 if (akl)
9461 ha_free((char **)&(akl->kw[0].kw));
9462 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009463 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009464 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009465 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009466
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009467 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009468 akl->kw[0].private = fcn;
9469
9470 /* End of array. */
9471 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9472
9473 /* Register this new converter */
9474 service_keywords_register(akl);
9475
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009476 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009477
9478 alloc_error:
9479 release_hlua_function(fcn);
9480 ha_free(&akl);
9481 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9482 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009483}
9484
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009485/* This function initialises Lua cli handler. It copies the
9486 * arguments in the Lua stack and create channel IO objects.
9487 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02009488static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009489{
9490 struct hlua *hlua;
9491 struct hlua_function *fcn;
9492 int i;
9493 const char *error;
9494
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009495 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009496 appctx->ctx.hlua_cli.fcn = private;
9497
Willy Tarreaubafbe012017-11-24 17:34:44 +01009498 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009499 if (!hlua) {
9500 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009501 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009502 }
9503 HLUA_INIT(hlua);
9504 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009505
9506 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05009507 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009508 * applet_http. It is absolutely compatible.
9509 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01009510 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009511 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01009512 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009513 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009514 }
9515 appctx->ctx.hlua_cli.task->nice = 0;
9516 appctx->ctx.hlua_cli.task->context = appctx;
9517 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
9518
9519 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +01009520 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 +01009521 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009522 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009523 }
9524
9525 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009526 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009527 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9528 error = lua_tostring(hlua->T, -1);
9529 else
9530 error = "critical error";
9531 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
9532 goto error;
9533 }
9534
9535 /* Check stack available size. */
9536 if (!lua_checkstack(hlua->T, 2)) {
9537 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9538 goto error;
9539 }
9540
9541 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009542 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009543
9544 /* Once the arguments parsed, the CLI is like an AppletTCP,
9545 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009546 */
9547 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
9548 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9549 goto error;
9550 }
9551 hlua->nargs = 1;
9552
9553 /* push keywords in the stack. */
9554 for (i = 0; *args[i]; i++) {
9555 /* Check stack available size. */
9556 if (!lua_checkstack(hlua->T, 1)) {
9557 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9558 goto error;
9559 }
9560 lua_pushstring(hlua->T, args[i]);
9561 hlua->nargs++;
9562 }
9563
9564 /* We must initialize the execution timeouts. */
9565 hlua->max_time = hlua_timeout_session;
9566
9567 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009568 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009569
9570 /* It's ok */
9571 return 0;
9572
9573 /* It's not ok. */
9574error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009575 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009576 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009577 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009578 return 1;
9579}
9580
9581static int hlua_cli_io_handler_fct(struct appctx *appctx)
9582{
9583 struct hlua *hlua;
9584 struct stream_interface *si;
9585 struct hlua_function *fcn;
9586
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009587 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009588 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01009589 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009590
9591 /* If the stream is disconnect or closed, ldo nothing. */
9592 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9593 return 1;
9594
9595 /* Execute the function. */
9596 switch (hlua_ctx_resume(hlua, 1)) {
9597
9598 /* finished. */
9599 case HLUA_E_OK:
9600 return 1;
9601
9602 /* yield. */
9603 case HLUA_E_AGAIN:
9604 /* We want write. */
9605 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01009606 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009607 /* Set the timeout. */
9608 if (hlua->wake_time != TICK_ETERNITY)
9609 task_schedule(hlua->task, hlua->wake_time);
9610 return 0;
9611
9612 /* finished with error. */
9613 case HLUA_E_ERRMSG:
9614 /* Display log. */
9615 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
9616 fcn->name, lua_tostring(hlua->T, -1));
9617 lua_pop(hlua->T, 1);
9618 return 1;
9619
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009620 case HLUA_E_ETMOUT:
9621 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
9622 fcn->name);
9623 return 1;
9624
9625 case HLUA_E_NOMEM:
9626 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
9627 fcn->name);
9628 return 1;
9629
9630 case HLUA_E_YIELD: /* unexpected */
9631 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
9632 fcn->name);
9633 return 1;
9634
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009635 case HLUA_E_ERR:
9636 /* Display log. */
9637 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
9638 fcn->name);
9639 return 1;
9640
9641 default:
9642 return 1;
9643 }
9644
9645 return 1;
9646}
9647
9648static void hlua_cli_io_release_fct(struct appctx *appctx)
9649{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009650 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009651 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009652}
9653
9654/* This function is an LUA binding used for registering
9655 * new keywords in the cli. It expects a list of keywords
9656 * which are the "path". It is limited to 5 keywords. A
9657 * description of the command, a function to be executed
9658 * for the parsing and a function for io handlers.
9659 */
9660__LJMP static int hlua_register_cli(lua_State *L)
9661{
9662 struct cli_kw_list *cli_kws;
9663 const char *message;
9664 int ref_io;
9665 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009666 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009667 int index;
9668 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009669 struct buffer *trash;
9670 const char *kw[5];
9671 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009672 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009673
9674 MAY_LJMP(check_args(L, 3, "register_cli"));
9675
9676 /* First argument : an array of maximum 5 keywords. */
9677 if (!lua_istable(L, 1))
9678 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
9679
9680 /* Second argument : string with contextual message. */
9681 message = MAY_LJMP(luaL_checkstring(L, 2));
9682
9683 /* Third and fourth argument : lua function. */
9684 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
9685
Thierry Fournierf67442e2020-11-28 20:41:07 +01009686 /* Check for CLI service already registered */
9687 trash = get_trash_chunk();
9688 index = 0;
9689 lua_pushnil(L);
9690 memset(kw, 0, sizeof(kw));
9691 while (lua_next(L, 1) != 0) {
9692 if (index >= CLI_PREFIX_KW_NB)
9693 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
9694 if (lua_type(L, -1) != LUA_TSTRING)
9695 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
9696 kw[index] = lua_tostring(L, -1);
9697 if (index == 0)
9698 chunk_printf(trash, "%s", kw[index]);
9699 else
9700 chunk_appendf(trash, " %s", kw[index]);
9701 index++;
9702 lua_pop(L, 1);
9703 }
9704 cli_kw = cli_find_kw_exact((char **)kw);
9705 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009706 fcn = cli_kw->private;
9707 if (fcn->function_ref[hlua_state_id] != -1) {
9708 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
9709 "This will become a hard error in version 2.5.\n", trash->area);
9710 }
9711 fcn->function_ref[hlua_state_id] = ref_io;
9712 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009713 }
9714
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009715 /* Allocate and fill the sample fetch keyword struct. */
9716 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009717 if (!cli_kws) {
9718 errmsg = "Lua out of memory error.";
9719 goto error;
9720 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009721 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009722 if (!fcn) {
9723 errmsg = "Lua out of memory error.";
9724 goto error;
9725 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009726
9727 /* Fill path. */
9728 index = 0;
9729 lua_pushnil(L);
9730 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009731 if (index >= 5) {
9732 errmsg = "1st argument must be a table with a maximum of 5 entries";
9733 goto error;
9734 }
9735 if (lua_type(L, -1) != LUA_TSTRING) {
9736 errmsg = "1st argument must be a table filled with strings";
9737 goto error;
9738 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009739 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009740 if (!cli_kws->kw[0].str_kw[index]) {
9741 errmsg = "Lua out of memory error.";
9742 goto error;
9743 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009744 index++;
9745 lua_pop(L, 1);
9746 }
9747
9748 /* Copy help message. */
9749 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009750 if (!cli_kws->kw[0].usage) {
9751 errmsg = "Lua out of memory error.";
9752 goto error;
9753 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009754
9755 /* Fill fcn io handler. */
9756 len = strlen("<lua.cli>") + 1;
9757 for (i = 0; i < index; i++)
9758 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
9759 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009760 if (!fcn->name) {
9761 errmsg = "Lua out of memory error.";
9762 goto error;
9763 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009764 strncat((char *)fcn->name, "<lua.cli", len);
9765 for (i = 0; i < index; i++) {
9766 strncat((char *)fcn->name, ".", len);
9767 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
9768 }
9769 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +01009770 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009771
9772 /* Fill last entries. */
9773 cli_kws->kw[0].private = fcn;
9774 cli_kws->kw[0].parse = hlua_cli_parse_fct;
9775 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
9776 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
9777
9778 /* Register this new converter */
9779 cli_register_kw(cli_kws);
9780
9781 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009782
9783 error:
9784 release_hlua_function(fcn);
9785 if (cli_kws) {
9786 for (i = 0; i < index; i++)
9787 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
9788 ha_free((char **)&(cli_kws->kw[0].usage));
9789 }
9790 ha_free(&cli_kws);
9791 WILL_LJMP(luaL_error(L, errmsg));
9792 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009793}
9794
Christopher Faulet69c581a2021-05-31 08:54:04 +02009795static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
9796{
9797 struct hlua_flt_config *conf = fconf->conf;
9798 lua_State *L;
9799 int error, pos, state_id, flt_ref;
9800
9801 state_id = reg_flt_to_stack_id(conf->reg);
9802 L = hlua_states[state_id];
9803 pos = lua_gettop(L);
9804
9805 /* The filter parsing function */
9806 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
9807
9808 /* Push the filter class on the stack and resolve all callbacks */
9809 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
9810
9811 /* Duplicate the filter class so each filter will have its own copy */
9812 lua_newtable(L);
9813 lua_pushnil(L);
9814
9815 while (lua_next(L, pos+2)) {
9816 lua_pushvalue(L, -2);
9817 lua_insert(L, -2);
9818 lua_settable(L, -4);
9819 }
9820 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
9821
9822 /* Remove the original lua filter class from the stack */
9823 lua_pop(L, 1);
9824
9825 /* Push the copy on the stack */
9826 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
9827
9828 /* extra args are pushed in a table */
9829 lua_newtable(L);
9830 for (pos = 0; conf->args[pos]; pos++) {
9831 /* Check stack available size. */
9832 if (!lua_checkstack(L, 1)) {
9833 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
9834 goto error;
9835 }
9836 lua_pushstring(L, conf->args[pos]);
9837 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
9838 }
9839
9840 error = lua_pcall(L, 2, LUA_MULTRET, 0);
9841 switch (error) {
9842 case LUA_OK:
9843 /* replace the filter ref */
9844 conf->ref[state_id] = flt_ref;
9845 break;
9846 case LUA_ERRRUN:
9847 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
9848 goto error;
9849 case LUA_ERRMEM:
9850 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
9851 goto error;
9852 case LUA_ERRERR:
9853 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
9854 goto error;
9855#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
9856 case LUA_ERRGCMM:
9857 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
9858 goto error;
9859#endif
9860 default:
9861 ha_alert("Lua filter '%s' : unknonwn error : %s", conf->reg->name, lua_tostring(L, -1));
9862 goto error;
9863 }
9864
9865 lua_settop(L, 0);
9866 return 0;
9867
9868 error:
9869 lua_settop(L, 0);
9870 return -1;
9871}
9872
9873static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
9874{
9875 struct hlua_flt_config *conf = fconf->conf;
9876 lua_State *L;
9877 int state_id;
9878
9879 if (!conf)
9880 return;
9881
9882 state_id = reg_flt_to_stack_id(conf->reg);
9883 L = hlua_states[state_id];
9884 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
9885}
9886
9887static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
9888{
9889 struct hlua_flt_config *conf = fconf->conf;
9890 int state_id = reg_flt_to_stack_id(conf->reg);
9891
9892 /* Rely on per-thread init for global scripts */
9893 if (!state_id)
9894 return hlua_filter_init_per_thread(px, fconf);
9895 return 0;
9896}
9897
9898static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
9899{
9900
9901 if (fconf->conf) {
9902 struct hlua_flt_config *conf = fconf->conf;
9903 int state_id = reg_flt_to_stack_id(conf->reg);
9904 int pos;
9905
9906 /* Rely on per-thread deinit for global scripts */
9907 if (!state_id)
9908 hlua_filter_deinit_per_thread(px, fconf);
9909
9910 for (pos = 0; conf->args[pos]; pos++)
9911 free(conf->args[pos]);
9912 free(conf->args);
9913 }
9914 ha_free(&fconf->conf);
9915 ha_free((char **)&fconf->id);
9916 ha_free(&fconf->ops);
9917}
9918
9919static int hlua_filter_new(struct stream *s, struct filter *filter)
9920{
9921 struct hlua_flt_config *conf = FLT_CONF(filter);
9922 struct hlua_flt_ctx *flt_ctx = NULL;
9923 int ret = 1;
9924
9925 /* In the execution wrappers linked with a stream, the
9926 * Lua context can be not initialized. This behavior
9927 * permits to save performances because a systematic
9928 * Lua initialization cause 5% performances loss.
9929 */
9930 if (!s->hlua) {
9931 struct hlua *hlua;
9932
9933 hlua = pool_alloc(pool_head_hlua);
9934 if (!hlua) {
9935 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9936 conf->reg->name);
9937 ret = 0;
9938 goto end;
9939 }
9940 HLUA_INIT(hlua);
9941 s->hlua = hlua;
9942 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9943 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9944 conf->reg->name);
9945 ret = 0;
9946 goto end;
9947 }
9948 }
9949
9950 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
9951 if (!flt_ctx) {
9952 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9953 conf->reg->name);
9954 ret = 0;
9955 goto end;
9956 }
9957 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
9958 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
9959 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
9960 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9961 conf->reg->name);
9962 ret = 0;
9963 goto end;
9964 }
9965 HLUA_INIT(flt_ctx->hlua[0]);
9966 HLUA_INIT(flt_ctx->hlua[1]);
9967 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
9968 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9969 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9970 conf->reg->name);
9971 ret = 0;
9972 goto end;
9973 }
9974
9975 if (!HLUA_IS_RUNNING(s->hlua)) {
9976 /* The following Lua calls can fail. */
9977 if (!SET_SAFE_LJMP(s->hlua)) {
9978 const char *error;
9979
9980 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9981 error = lua_tostring(s->hlua->T, -1);
9982 else
9983 error = "critical error";
9984 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
9985 ret = 0;
9986 goto end;
9987 }
9988
9989 /* Check stack size. */
9990 if (!lua_checkstack(s->hlua->T, 1)) {
9991 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
9992 ret = 0;
9993 goto end;
9994 }
9995
9996 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
9997 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
9998 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
9999 conf->reg->name);
10000 RESET_SAFE_LJMP(s->hlua);
10001 ret = 0;
10002 goto end;
10003 }
10004 lua_insert(s->hlua->T, -2);
10005
10006 /* Push the copy on the stack */
10007 s->hlua->nargs = 1;
10008
10009 /* We must initialize the execution timeouts. */
10010 s->hlua->max_time = hlua_timeout_session;
10011
10012 /* At this point the execution is safe. */
10013 RESET_SAFE_LJMP(s->hlua);
10014 }
10015
10016 switch (hlua_ctx_resume(s->hlua, 0)) {
10017 case HLUA_E_OK:
10018 /* Nothing returned or not a table, ignore the filter for current stream */
10019 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10020 ret = 0;
10021 goto end;
10022 }
10023
10024 /* Attached the filter pointer to the ctx */
10025 lua_pushstring(s->hlua->T, "__filter");
10026 lua_pushlightuserdata(s->hlua->T, filter);
10027 lua_settable(s->hlua->T, -3);
10028
10029 /* Save a ref on the filter ctx */
10030 lua_pushvalue(s->hlua->T, 1);
10031 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10032 filter->ctx = flt_ctx;
10033 break;
10034 case HLUA_E_ERRMSG:
10035 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10036 ret = -1;
10037 goto end;
10038 case HLUA_E_ETMOUT:
10039 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10040 ret = 0;
10041 goto end;
10042 case HLUA_E_NOMEM:
10043 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10044 ret = 0;
10045 goto end;
10046 case HLUA_E_AGAIN:
10047 case HLUA_E_YIELD:
10048 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10049 " are not allowed from 'new' function.\n", conf->reg->name);
10050 ret = 0;
10051 goto end;
10052 case HLUA_E_ERR:
10053 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10054 ret = 0;
10055 goto end;
10056 default:
10057 ret = 0;
10058 goto end;
10059 }
10060
10061 end:
10062 if (s->hlua)
10063 lua_settop(s->hlua->T, 0);
10064 if (ret <= 0) {
10065 if (flt_ctx) {
10066 hlua_ctx_destroy(flt_ctx->hlua[0]);
10067 hlua_ctx_destroy(flt_ctx->hlua[1]);
10068 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10069 }
10070 }
10071 return ret;
10072}
10073
10074static void hlua_filter_delete(struct stream *s, struct filter *filter)
10075{
10076 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10077
10078 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10079 hlua_ctx_destroy(flt_ctx->hlua[0]);
10080 hlua_ctx_destroy(flt_ctx->hlua[1]);
10081 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10082 filter->ctx = NULL;
10083}
10084
Christopher Faulet9f55a502020-02-25 15:21:02 +010010085static int hlua_filter_from_payload(struct filter *filter)
10086{
10087 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10088
10089 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10090}
10091
Christopher Fauletc404f112020-02-26 15:03:09 +010010092static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10093 int dir, unsigned int flags)
10094{
10095 struct hlua *flt_hlua;
10096 struct hlua_flt_config *conf = FLT_CONF(filter);
10097 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10098 unsigned int hflags = HLUA_TXN_FLT_CTX;
10099 int ret = 1;
10100
10101 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10102 if (!flt_hlua)
10103 goto end;
10104
10105 if (!HLUA_IS_RUNNING(flt_hlua)) {
10106 int extra_idx = lua_gettop(flt_hlua->T);
10107
10108 /* The following Lua calls can fail. */
10109 if (!SET_SAFE_LJMP(flt_hlua)) {
10110 const char *error;
10111
10112 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10113 error = lua_tostring(flt_hlua->T, -1);
10114 else
10115 error = "critical error";
10116 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10117 goto end;
10118 }
10119
10120 /* Check stack size. */
10121 if (!lua_checkstack(flt_hlua->T, 3)) {
10122 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10123 RESET_SAFE_LJMP(flt_hlua);
10124 goto end;
10125 }
10126
10127 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10128 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10129 RESET_SAFE_LJMP(flt_hlua);
10130 goto end;
10131 }
10132 lua_insert(flt_hlua->T, -2);
10133
10134 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10135 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10136 RESET_SAFE_LJMP(flt_hlua);
10137 goto end;
10138 }
10139 flt_hlua->nargs = 2;
10140
10141 if (flags & HLUA_FLT_CB_ARG_CHN) {
10142 if (dir == SMP_OPT_DIR_REQ)
10143 lua_getfield(flt_hlua->T, -1, "req");
10144 else
10145 lua_getfield(flt_hlua->T, -1, "res");
10146 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10147 lua_pushstring(flt_hlua->T, "__filter");
10148 lua_pushlightuserdata(flt_hlua->T, filter);
10149 lua_settable(flt_hlua->T, -3);
10150 }
10151 flt_hlua->nargs++;
10152 }
10153 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010154 if (dir == SMP_OPT_DIR_REQ)
10155 lua_getfield(flt_hlua->T, -1, "http_req");
10156 else
10157 lua_getfield(flt_hlua->T, -1, "http_res");
10158 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10159 lua_pushstring(flt_hlua->T, "__filter");
10160 lua_pushlightuserdata(flt_hlua->T, filter);
10161 lua_settable(flt_hlua->T, -3);
10162 }
10163 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010164 }
10165
10166 /* Check stack size. */
10167 if (!lua_checkstack(flt_hlua->T, 1)) {
10168 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10169 RESET_SAFE_LJMP(flt_hlua);
10170 goto end;
10171 }
10172
10173 while (extra_idx--) {
10174 lua_pushvalue(flt_hlua->T, 1);
10175 lua_remove(flt_hlua->T, 1);
10176 flt_hlua->nargs++;
10177 }
10178
10179 /* We must initialize the execution timeouts. */
10180 flt_hlua->max_time = hlua_timeout_session;
10181
10182 /* At this point the execution is safe. */
10183 RESET_SAFE_LJMP(flt_hlua);
10184 }
10185
10186 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10187 case HLUA_E_OK:
10188 /* Catch the return value if it required */
10189 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10190 ret = lua_tointeger(flt_hlua->T, -1);
10191 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10192 }
10193
10194 /* Set timeout in the required channel. */
10195 if (flt_hlua->wake_time != TICK_ETERNITY) {
10196 if (dir == SMP_OPT_DIR_REQ)
10197 s->req.analyse_exp = flt_hlua->wake_time;
10198 else
10199 s->res.analyse_exp = flt_hlua->wake_time;
10200 }
10201 break;
10202 case HLUA_E_AGAIN:
10203 /* Set timeout in the required channel. */
10204 if (flt_hlua->wake_time != TICK_ETERNITY) {
10205 if (dir == SMP_OPT_DIR_REQ)
10206 s->req.analyse_exp = flt_hlua->wake_time;
10207 else
10208 s->res.analyse_exp = flt_hlua->wake_time;
10209 }
10210 /* Some actions can be wake up when a "write" event
10211 * is detected on a response channel. This is useful
10212 * only for actions targeted on the requests.
10213 */
10214 if (HLUA_IS_WAKERESWR(flt_hlua))
10215 s->res.flags |= CF_WAKE_WRITE;
10216 if (HLUA_IS_WAKEREQWR(flt_hlua))
10217 s->req.flags |= CF_WAKE_WRITE;
10218 ret = 0;
10219 goto end;
10220 case HLUA_E_ERRMSG:
10221 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10222 ret = -1;
10223 goto end;
10224 case HLUA_E_ETMOUT:
10225 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10226 goto end;
10227 case HLUA_E_NOMEM:
10228 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10229 goto end;
10230 case HLUA_E_YIELD:
10231 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10232 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10233 goto end;
10234 case HLUA_E_ERR:
10235 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10236 goto end;
10237 default:
10238 goto end;
10239 }
10240
10241
10242 end:
10243 return ret;
10244}
10245
10246static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10247{
10248 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10249
10250 flt_ctx->flags = 0;
10251 return hlua_filter_callback(s, filter, "start_analyze",
10252 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10253 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10254}
10255
10256static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10257{
10258 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10259
10260 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10261 return hlua_filter_callback(s, filter, "end_analyze",
10262 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10263 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10264}
10265
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010266static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10267{
10268 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10269
10270 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10271 return hlua_filter_callback(s, filter, "http_headers",
10272 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10273 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10274}
10275
10276static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10277 unsigned int offset, unsigned int len)
10278{
10279 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10280 struct hlua *flt_hlua;
10281 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10282 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10283 int ret;
10284
10285 flt_hlua = flt_ctx->hlua[idx];
10286 flt_ctx->cur_off[idx] = offset;
10287 flt_ctx->cur_len[idx] = len;
10288 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10289 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10290 if (ret != -1) {
10291 ret = flt_ctx->cur_len[idx];
10292 if (lua_gettop(flt_hlua->T) > 0) {
10293 ret = lua_tointeger(flt_hlua->T, -1);
10294 if (ret > flt_ctx->cur_len[idx])
10295 ret = flt_ctx->cur_len[idx];
10296 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10297 }
10298 }
10299 return ret;
10300}
10301
10302static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10303{
10304 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10305
10306 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10307 return hlua_filter_callback(s, filter, "http_end",
10308 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10309 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10310}
10311
Christopher Fauletc404f112020-02-26 15:03:09 +010010312static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10313 unsigned int offset, unsigned int len)
10314{
10315 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10316 struct hlua *flt_hlua;
10317 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10318 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10319 int ret;
10320
10321 flt_hlua = flt_ctx->hlua[idx];
10322 flt_ctx->cur_off[idx] = offset;
10323 flt_ctx->cur_len[idx] = len;
10324 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10325 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10326 if (ret != -1) {
10327 ret = flt_ctx->cur_len[idx];
10328 if (lua_gettop(flt_hlua->T) > 0) {
10329 ret = lua_tointeger(flt_hlua->T, -1);
10330 if (ret > flt_ctx->cur_len[idx])
10331 ret = flt_ctx->cur_len[idx];
10332 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10333 }
10334 }
10335 return ret;
10336}
10337
Christopher Faulet69c581a2021-05-31 08:54:04 +020010338static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10339 struct flt_conf *fconf, char **err, void *private)
10340{
10341 struct hlua_reg_filter *reg_flt = private;
10342 lua_State *L;
10343 struct hlua_flt_config *conf = NULL;
10344 const char *flt_id = NULL;
10345 int state_id, pos, flt_flags = 0;
10346 struct flt_ops *hlua_flt_ops = NULL;
10347
10348 state_id = reg_flt_to_stack_id(reg_flt);
10349 L = hlua_states[state_id];
10350
10351 /* Initialize the filter ops with default callbacks */
10352 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010353 if (!hlua_flt_ops)
10354 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010355 hlua_flt_ops->init = hlua_filter_init;
10356 hlua_flt_ops->deinit = hlua_filter_deinit;
10357 if (state_id) {
10358 /* Set per-thread callback if script is loaded per-thread */
10359 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10360 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10361 }
10362 hlua_flt_ops->attach = hlua_filter_new;
10363 hlua_flt_ops->detach = hlua_filter_delete;
10364
10365 /* Push the filter class on the stack and resolve all callbacks */
10366 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10367
Christopher Fauletc404f112020-02-26 15:03:09 +010010368 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10369 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10370 lua_pop(L, 1);
10371 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10372 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10373 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010374 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10375 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10376 lua_pop(L, 1);
10377 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10378 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10379 lua_pop(L, 1);
10380 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10381 hlua_flt_ops->http_end = hlua_filter_http_end;
10382 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010383 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10384 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10385 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010386
10387 /* Get id and flags of the filter class */
10388 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10389 flt_id = lua_tostring(L, -1);
10390 lua_pop(L, 1);
10391 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10392 flt_flags = lua_tointeger(L, -1);
10393 lua_pop(L, 1);
10394
10395 /* Create the filter config */
10396 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010397 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010398 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010399 conf->reg = reg_flt;
10400
10401 /* duplicate args */
10402 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10403 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010404 if (!conf->args)
10405 goto error;
10406 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010407 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010408 if (!conf->args[pos])
10409 goto error;
10410 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010411 conf->args[pos] = NULL;
10412 *cur_arg += pos + 1;
10413
Christopher Fauletc86bb872021-08-13 08:33:57 +020010414 if (flt_id) {
10415 fconf->id = strdup(flt_id);
10416 if (!fconf->id)
10417 goto error;
10418 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010419 fconf->flags = flt_flags;
10420 fconf->conf = conf;
10421 fconf->ops = hlua_flt_ops;
10422
10423 lua_settop(L, 0);
10424 return 0;
10425
10426 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010427 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010428 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010429 if (conf && conf->args) {
10430 for (pos = 0; conf->args[pos]; pos++)
10431 free(conf->args[pos]);
10432 free(conf->args);
10433 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010434 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010435 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010436 lua_settop(L, 0);
10437 return -1;
10438}
10439
Christopher Fauletc404f112020-02-26 15:03:09 +010010440__LJMP static int hlua_register_data_filter(lua_State *L)
10441{
10442 struct filter *filter;
10443 struct channel *chn;
10444
10445 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10446 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10447 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10448
10449 lua_getfield(L, 1, "__filter");
10450 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10451 filter = lua_touserdata (L, -1);
10452 lua_pop(L, 1);
10453
10454 register_data_filter(chn_strm(chn), chn, filter);
10455 return 1;
10456}
10457
10458__LJMP static int hlua_unregister_data_filter(lua_State *L)
10459{
10460 struct filter *filter;
10461 struct channel *chn;
10462
10463 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10464 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10465 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10466
10467 lua_getfield(L, 1, "__filter");
10468 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10469 filter = lua_touserdata (L, -1);
10470 lua_pop(L, 1);
10471
10472 unregister_data_filter(chn_strm(chn), chn, filter);
10473 return 1;
10474}
10475
Christopher Faulet69c581a2021-05-31 08:54:04 +020010476/* This function is an LUA binding used for registering a filter. It expects a
10477 * fileter name used in the haproxy configuration file and a LUA function to
10478 * parse configuration arguments.
10479 */
10480__LJMP static int hlua_register_filter(lua_State *L)
10481{
10482 struct buffer *trash;
10483 struct flt_kw_list *fkl;
10484 struct flt_kw *fkw;
10485 const char *name;
10486 struct hlua_reg_filter *reg_flt= NULL;
10487 int flt_ref, fun_ref;
10488 int len;
10489
10490 MAY_LJMP(check_args(L, 3, "register_filter"));
10491
10492 /* First argument : filter name. */
10493 name = MAY_LJMP(luaL_checkstring(L, 1));
10494
10495 /* Second argument : The filter class */
10496 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
10497
10498 /* Third argument : lua function. */
10499 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
10500
10501 trash = get_trash_chunk();
10502 chunk_printf(trash, "lua.%s", name);
10503 fkw = flt_find_kw(trash->area);
10504 if (fkw != NULL) {
10505 reg_flt = fkw->private;
10506 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
10507 ha_warning("Trying to register filter 'lua.%s' more than once. "
10508 "This will become a hard error in version 2.5.\n", name);
10509 }
10510 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10511 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10512 return 0;
10513 }
10514
10515 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
10516 if (!fkl)
10517 goto alloc_error;
10518 fkl->scope = "HLUA";
10519
10520 reg_flt = new_hlua_reg_filter(name);
10521 if (!reg_flt)
10522 goto alloc_error;
10523
10524 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10525 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10526
10527 /* The filter keyword */
10528 len = strlen("lua.") + strlen(name) + 1;
10529 fkl->kw[0].kw = calloc(1, len);
10530 if (!fkl->kw[0].kw)
10531 goto alloc_error;
10532
10533 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
10534
10535 fkl->kw[0].parse = hlua_filter_parse_fct;
10536 fkl->kw[0].private = reg_flt;
10537 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
10538
10539 /* Register this new filter */
10540 flt_register_keywords(fkl);
10541
10542 return 0;
10543
10544 alloc_error:
10545 release_hlua_reg_filter(reg_flt);
10546 ha_free(&fkl);
10547 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10548 return 0; /* Never reached */
10549}
10550
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010551static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010552 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010553 char **err, unsigned int *timeout)
10554{
10555 const char *error;
10556
10557 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020010558 if (error == PARSE_TIME_OVER) {
10559 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
10560 args[1], args[0]);
10561 return -1;
10562 }
10563 else if (error == PARSE_TIME_UNDER) {
10564 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
10565 args[1], args[0]);
10566 return -1;
10567 }
10568 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010569 memprintf(err, "%s: invalid timeout", args[0]);
10570 return -1;
10571 }
10572 return 0;
10573}
10574
10575static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010576 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010577 char **err)
10578{
10579 return hlua_read_timeout(args, section_type, curpx, defpx,
10580 file, line, err, &hlua_timeout_session);
10581}
10582
10583static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010584 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010585 char **err)
10586{
10587 return hlua_read_timeout(args, section_type, curpx, defpx,
10588 file, line, err, &hlua_timeout_task);
10589}
10590
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010591static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010592 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010593 char **err)
10594{
10595 return hlua_read_timeout(args, section_type, curpx, defpx,
10596 file, line, err, &hlua_timeout_applet);
10597}
10598
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010599static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010600 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010601 char **err)
10602{
10603 char *error;
10604
10605 hlua_nb_instruction = strtoll(args[1], &error, 10);
10606 if (*error != '\0') {
10607 memprintf(err, "%s: invalid number", args[0]);
10608 return -1;
10609 }
10610 return 0;
10611}
10612
Willy Tarreau32f61e22015-03-18 17:54:59 +010010613static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010614 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010010615 char **err)
10616{
10617 char *error;
10618
10619 if (*(args[1]) == 0) {
10620 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
10621 return -1;
10622 }
10623 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
10624 if (*error != '\0') {
10625 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
10626 return -1;
10627 }
10628 return 0;
10629}
10630
10631
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010632/* This function is called by the main configuration key "lua-load". It loads and
10633 * execute an lua file during the parsing of the HAProxy configuration file. It is
10634 * the main lua entry point.
10635 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010636 * This function runs with the HAProxy keywords API. It returns -1 if an error
10637 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010638 *
10639 * In some error case, LUA set an error message in top of the stack. This function
10640 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010641 *
10642 * This function can fail with an abort() due to an Lua critical error.
10643 * We are in the configuration parsing process of HAProxy, this abort() is
10644 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010645 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010646static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010647{
10648 int error;
10649
10650 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010651 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010652 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010653 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
10654 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010655 return -1;
10656 }
10657
10658 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010659 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010660 switch (error) {
10661 case LUA_OK:
10662 break;
10663 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010664 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
10665 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010666 return -1;
10667 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010010668 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010669 return -1;
10670 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010671 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
10672 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010673 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010674#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010675 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010676 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
10677 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010678 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010679#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010680 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010681 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
10682 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010683 return -1;
10684 }
10685
10686 return 0;
10687}
10688
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010689static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010690 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010691 char **err)
10692{
10693 if (*(args[1]) == 0) {
10694 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
10695 return -1;
10696 }
10697
Thierry Fournier59f11be2020-11-29 00:37:41 +010010698 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010010699 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010700 ha_set_tid(0);
Thierry Fournierafc63e22020-11-28 17:06:51 +010010701 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010702}
10703
Thierry Fournier59f11be2020-11-29 00:37:41 +010010704static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010705 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010010706 char **err)
10707{
10708 int len;
10709
10710 if (*(args[1]) == 0) {
10711 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
10712 return -1;
10713 }
10714
10715 if (per_thread_load == NULL) {
10716 /* allocate the first entry large enough to store the final NULL */
10717 per_thread_load = calloc(1, sizeof(*per_thread_load));
10718 if (per_thread_load == NULL) {
10719 memprintf(err, "out of memory error");
10720 return -1;
10721 }
10722 }
10723
10724 /* count used entries */
10725 for (len = 0; per_thread_load[len] != NULL; len++)
10726 ;
10727
10728 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
10729 if (per_thread_load == NULL) {
10730 memprintf(err, "out of memory error");
10731 return -1;
10732 }
10733
10734 per_thread_load[len] = strdup(args[1]);
10735 per_thread_load[len + 1] = NULL;
10736
10737 if (per_thread_load[len] == NULL) {
10738 memprintf(err, "out of memory error");
10739 return -1;
10740 }
10741
10742 /* loading for thread 1 only */
10743 hlua_state_id = 1;
10744 ha_set_tid(0);
10745 return hlua_load_state(args[1], hlua_states[1], err);
10746}
10747
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010748/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
10749 * in the given <ctx>.
10750 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010751static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010752{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010753 lua_getglobal(L, "package"); /* push package variable */
10754 lua_pushstring(L, path); /* push given path */
10755 lua_pushstring(L, ";"); /* push semicolon */
10756 lua_getfield(L, -3, type); /* push old path */
10757 lua_concat(L, 3); /* concatenate to new path */
10758 lua_setfield(L, -2, type); /* store new path */
10759 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010760
10761 return 0;
10762}
10763
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010764static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010765 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010766 char **err)
10767{
10768 char *path;
10769 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010770 struct prepend_path *p = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010771
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010772 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010773 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010774 }
10775
10776 if (!(*args[1])) {
10777 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010778 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010779 }
10780 path = args[1];
10781
10782 if (*args[2]) {
10783 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
10784 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010785 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010786 }
10787 type = args[2];
10788 }
10789
Thierry Fournier59f11be2020-11-29 00:37:41 +010010790 p = calloc(1, sizeof(*p));
10791 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010792 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010793 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010794 }
10795 p->path = strdup(path);
10796 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010797 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010798 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010799 }
10800 p->type = strdup(type);
10801 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010802 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010803 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010804 }
Willy Tarreau2b718102021-04-21 07:32:39 +020010805 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010806
10807 hlua_prepend_path(hlua_states[0], type, path);
10808 hlua_prepend_path(hlua_states[1], type, path);
10809 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010810
10811err2:
10812 free(p->type);
10813 free(p->path);
10814err:
10815 free(p);
10816 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010817}
10818
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010819/* configuration keywords declaration */
10820static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010821 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010822 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010010823 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010824 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
10825 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020010826 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010827 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010010828 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010829 { 0, NULL, NULL },
10830}};
10831
Willy Tarreau0108d902018-11-25 19:14:37 +010010832INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
10833
Christopher Fauletafd8f102018-11-08 11:34:21 +010010834
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010835/* This function can fail with an abort() due to an Lua critical error.
10836 * We are in the initialisation process of HAProxy, this abort() is
10837 * tolerated.
10838 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010010839int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010840{
10841 struct hlua_init_function *init;
10842 const char *msg;
10843 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010844 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010010845 const char *kind;
10846 const char *trace;
10847 int return_status = 1;
10848#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
10849 int nres;
10850#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010851
Willy Tarreaucdb53462020-12-02 12:12:00 +010010852 /* disable memory limit checks if limit is not set */
10853 if (!hlua_global_allocator.limit)
10854 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
10855
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010856 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010010857 if (setjmp(safe_ljmp_env) != 0) {
10858 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010010859 if (lua_type(L, -1) == LUA_TSTRING)
10860 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010861 else
10862 error = "critical error";
10863 fprintf(stderr, "Lua post-init: %s.\n", error);
10864 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010010865 } else {
10866 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010867 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020010868
Thierry Fournierb8cef172020-11-28 15:37:17 +010010869 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010870
Thierry Fournierc7492592020-11-28 23:57:24 +010010871 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010010872 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010010873
10874#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010010875 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010010876#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010010877 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010010878#endif
10879 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010880 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010010881
10882 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010010883 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010010884 break;
Thierry Fournier670db242020-11-28 10:49:59 +010010885
10886 case LUA_ERRERR:
10887 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010888 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010889 case LUA_ERRRUN:
10890 if (!kind)
10891 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010010892 msg = lua_tostring(L, -1);
10893 lua_settop(L, 0); /* Empty the stack. */
10894 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010010895 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010010896 if (msg)
10897 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
10898 else
10899 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
10900 return_status = 0;
10901 break;
10902
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010903 default:
Thierry Fournier670db242020-11-28 10:49:59 +010010904 /* Unknown error */
10905 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010906 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010907 case LUA_YIELD:
10908 /* yield is not configured at this step, this state doesn't happen */
10909 if (!kind)
10910 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010911 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010912 case LUA_ERRMEM:
10913 if (!kind)
10914 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010010915 lua_settop(L, 0);
10916 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010010917 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010010918 ha_alert("Lua init: %s: %s\n", kind, trace);
10919 return_status = 0;
10920 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010921 }
Thierry Fournier670db242020-11-28 10:49:59 +010010922 if (!return_status)
10923 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010924 }
Thierry Fournier3c539322020-11-28 16:05:05 +010010925
10926 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010010927 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010928}
10929
Thierry Fournierb8cef172020-11-28 15:37:17 +010010930int hlua_post_init()
10931{
Thierry Fournier59f11be2020-11-29 00:37:41 +010010932 int ret;
10933 int i;
10934 int errors;
10935 char *err = NULL;
10936 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010937 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010938
Thierry Fournierb8cef172020-11-28 15:37:17 +010010939#if USE_OPENSSL
10940 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010010941 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010010942 int saved_used_backed = global.ssl_used_backend;
10943 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010010944 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010010945 global.ssl_used_backend = saved_used_backed;
10946 }
10947#endif
10948
Thierry Fournierc7492592020-11-28 23:57:24 +010010949 /* Perform post init of common thread */
10950 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010951 ha_set_tid(0);
10952 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
10953 if (ret == 0)
10954 return 0;
10955
10956 /* init remaining lua states and load files */
10957 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
10958
10959 /* set thread context */
10960 ha_set_tid(hlua_state_id - 1);
10961
10962 /* Init lua state */
10963 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
10964
10965 /* Load lua files */
10966 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
10967 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
10968 if (ret != 0) {
10969 ha_alert("Lua init: %s\n", err);
10970 return 0;
10971 }
10972 }
10973 }
10974
10975 /* Reset thread context */
10976 ha_set_tid(0);
10977
10978 /* Execute post init for all states */
10979 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
10980
10981 /* set thread context */
10982 ha_set_tid(hlua_state_id - 1);
10983
10984 /* run post init */
10985 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
10986 if (ret == 0)
10987 return 0;
10988 }
10989
10990 /* Reset thread context */
10991 ha_set_tid(0);
10992
10993 /* control functions registering. Each function must have:
10994 * - only the function_ref[0] set positive and all other to -1
10995 * - only the function_ref[0] set to -1 and all other positive
10996 * This ensure a same reference is not used both in shared
10997 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050010998 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010010999 * complicated to found for the end user.
11000 */
11001 errors = 0;
11002 list_for_each_entry(fcn, &referenced_functions, l) {
11003 ret = 0;
11004 for (i = 1; i < global.nbthread + 1; i++) {
11005 if (fcn->function_ref[i] == -1)
11006 ret--;
11007 else
11008 ret++;
11009 }
11010 if (abs(ret) != global.nbthread) {
11011 ha_alert("Lua function '%s' is not referenced in all thread. "
11012 "Expect function in all thread or in none thread.\n", fcn->name);
11013 errors++;
11014 continue;
11015 }
11016
11017 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011018 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11019 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011020 "exclusive.\n", fcn->name);
11021 errors++;
11022 }
11023 }
11024
Christopher Faulet69c581a2021-05-31 08:54:04 +020011025 /* Do the same with registered filters */
11026 list_for_each_entry(reg_flt, &referenced_filters, l) {
11027 ret = 0;
11028 for (i = 1; i < global.nbthread + 1; i++) {
11029 if (reg_flt->flt_ref[i] == -1)
11030 ret--;
11031 else
11032 ret++;
11033 }
11034 if (abs(ret) != global.nbthread) {
11035 ha_alert("Lua filter '%s' is not referenced in all thread. "
11036 "Expect function in all thread or in none thread.\n", reg_flt->name);
11037 errors++;
11038 continue;
11039 }
11040
11041 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11042 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11043 "and per-thread Lua context (through lua-load-per-thread). these two context "
11044 "exclusive.\n", fcn->name);
11045 errors++;
11046 }
11047 }
11048
11049
Thierry Fournier59f11be2020-11-29 00:37:41 +010011050 if (errors > 0)
11051 return 0;
11052
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011053 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011054 * -1 in order to have probably a segfault if someone use it
11055 */
11056 hlua_state_id = -1;
11057
11058 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011059}
11060
Willy Tarreau32f61e22015-03-18 17:54:59 +010011061/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11062 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11063 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011064 * allocation. <nsize> is the requested new size. A new allocation is
11065 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011066 * zero. This one verifies that the limits are respected but is optimized
11067 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011068 */
11069static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11070{
11071 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011072 size_t limit, old, new;
11073
Tim Duesterhus22586522021-01-08 10:35:33 +010011074 if (unlikely(!ptr && !nsize))
11075 return NULL;
11076
Willy Tarreaucdb53462020-12-02 12:12:00 +010011077 /* a limit of ~0 means unlimited and boot complete, so there's no need
11078 * for accounting anymore.
11079 */
Christopher Fauletcc2c4f82021-03-24 14:52:24 +010011080 if (likely(~zone->limit == 0))
11081 return realloc(ptr, nsize);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011082
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011083 if (!ptr)
11084 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011085
Willy Tarreaucdb53462020-12-02 12:12:00 +010011086 /* enforce strict limits across all threads */
11087 limit = zone->limit;
11088 old = _HA_ATOMIC_LOAD(&zone->allocated);
11089 do {
11090 new = old + nsize - osize;
11091 if (unlikely(nsize && limit && new > limit))
11092 return NULL;
11093 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011094
11095 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011096
11097 if (unlikely(!ptr && nsize)) // failed
11098 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11099
11100 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011101 return ptr;
11102}
11103
Thierry Fournierecb83c22020-11-28 15:49:44 +010011104/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011105 * We are in the initialisation process of HAProxy, this abort() is
11106 * tolerated.
11107 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011108lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011109{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011110 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011111 int idx;
11112 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011113 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011114 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011115 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011116 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011117 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011118 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011119
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011120 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011121 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011122
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011123 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011124 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011125 *context = NULL;
11126
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011127 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011128 * the Lua function can fail with an abort. We are in the initialisation
11129 * process of HAProxy, this abort() is tolerated.
11130 */
11131
Thierry Fournier3c539322020-11-28 16:05:05 +010011132 /* Call post initialisation function in safe environment. */
11133 if (setjmp(safe_ljmp_env) != 0) {
11134 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011135 if (lua_type(L, -1) == LUA_TSTRING)
11136 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011137 else
11138 error_msg = "critical error";
11139 fprintf(stderr, "Lua init: %s.\n", error_msg);
11140 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011141 } else {
11142 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011143 }
11144
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011145 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011146 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011147#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11148#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11149#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011150 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011151#endif
11152#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011153 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011154#endif
11155#undef HLUA_PREPEND_PATH_TOSTRING
11156#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011157
Thierry Fournier59f11be2020-11-29 00:37:41 +010011158 /* Apply configured prepend path */
11159 list_for_each_entry(pp, &prepend_path_list, l)
11160 hlua_prepend_path(L, pp->type, pp->path);
11161
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011162 /*
11163 *
11164 * Create "core" object.
11165 *
11166 */
11167
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011168 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011169 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011170
Thierry Fournierecb83c22020-11-28 15:49:44 +010011171 /* set the thread id */
11172 hlua_class_const_int(L, "thread", thread_num);
11173
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011174 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011175 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011176 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011177
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011178 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011179 hlua_class_function(L, "register_init", hlua_register_init);
11180 hlua_class_function(L, "register_task", hlua_register_task);
11181 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11182 hlua_class_function(L, "register_converters", hlua_register_converters);
11183 hlua_class_function(L, "register_action", hlua_register_action);
11184 hlua_class_function(L, "register_service", hlua_register_service);
11185 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011186 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011187 hlua_class_function(L, "yield", hlua_yield);
11188 hlua_class_function(L, "set_nice", hlua_set_nice);
11189 hlua_class_function(L, "sleep", hlua_sleep);
11190 hlua_class_function(L, "msleep", hlua_msleep);
11191 hlua_class_function(L, "add_acl", hlua_add_acl);
11192 hlua_class_function(L, "del_acl", hlua_del_acl);
11193 hlua_class_function(L, "set_map", hlua_set_map);
11194 hlua_class_function(L, "del_map", hlua_del_map);
11195 hlua_class_function(L, "tcp", hlua_socket_new);
11196 hlua_class_function(L, "log", hlua_log);
11197 hlua_class_function(L, "Debug", hlua_log_debug);
11198 hlua_class_function(L, "Info", hlua_log_info);
11199 hlua_class_function(L, "Warning", hlua_log_warning);
11200 hlua_class_function(L, "Alert", hlua_log_alert);
11201 hlua_class_function(L, "done", hlua_done);
11202 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011203
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011204 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011205
11206 /*
11207 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011208 * Create "act" object.
11209 *
11210 */
11211
11212 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011213 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011214
11215 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011216 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11217 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11218 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11219 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11220 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11221 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11222 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11223 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011224
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011225 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011226
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011227 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011228
11229 /*
11230 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011231 * Create "Filter" object.
11232 *
11233 */
11234
11235 /* This table entry is the object "filter" base. */
11236 lua_newtable(L);
11237
11238 /* push flags and constants */
11239 hlua_class_const_int(L, "CONTINUE", 1);
11240 hlua_class_const_int(L, "WAIT", 0);
11241 hlua_class_const_int(L, "ERROR", -1);
11242
11243 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
11244
Christopher Fauletc404f112020-02-26 15:03:09 +010011245 hlua_class_function(L, "wake_time", hlua_set_wake_time);
11246 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
11247 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
11248
Christopher Faulet69c581a2021-05-31 08:54:04 +020011249 lua_setglobal(L, "filter");
11250
11251 /*
11252 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011253 * Register class Map
11254 *
11255 */
11256
11257 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011258 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011259
11260 /* register pattern types. */
11261 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011262 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011263 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011264 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011265 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011266 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011267
11268 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011269 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011270
11271 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011272 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011273
Ilya Shipitsind4259502020-04-08 01:07:56 +050011274 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011275 lua_pushstring(L, "__index");
11276 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011277
11278 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011279 hlua_class_function(L, "lookup", hlua_map_lookup);
11280 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011281
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011282 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011283
Thierry Fournier45e78d72016-02-19 18:34:46 +010011284 /* Register previous table in the registry with reference and named entry.
11285 * The function hlua_register_metatable() pops the stack, so we
11286 * previously create a copy of the table.
11287 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011288 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
11289 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011290
11291 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011292 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011293
11294 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011295 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011296
11297 /*
11298 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011299 * Register class Channel
11300 *
11301 */
11302
11303 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011304 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011305
Ilya Shipitsind4259502020-04-08 01:07:56 +050011306 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011307 lua_pushstring(L, "__index");
11308 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011309
11310 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011311 hlua_class_function(L, "data", hlua_channel_get_data);
11312 hlua_class_function(L, "line", hlua_channel_get_line);
11313 hlua_class_function(L, "set", hlua_channel_set_data);
11314 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011315 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011316 hlua_class_function(L, "prepend", hlua_channel_prepend);
11317 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011318 hlua_class_function(L, "send", hlua_channel_send);
11319 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011320 hlua_class_function(L, "input", hlua_channel_get_in_len);
11321 hlua_class_function(L, "output", hlua_channel_get_out_len);
11322 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011323 hlua_class_function(L, "is_full", hlua_channel_is_full);
11324 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011325
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011326 /* Deprecated API */
11327 hlua_class_function(L, "get", hlua_channel_get);
11328 hlua_class_function(L, "dup", hlua_channel_dup);
11329 hlua_class_function(L, "getline", hlua_channel_getline);
11330 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
11331 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
11332
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011333 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011334
11335 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011336 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011337
11338 /*
11339 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011340 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011341 *
11342 */
11343
11344 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011345 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011346
Ilya Shipitsind4259502020-04-08 01:07:56 +050011347 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011348 lua_pushstring(L, "__index");
11349 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011350
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011351 /* Browse existing fetches and create the associated
11352 * object method.
11353 */
11354 sf = NULL;
11355 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011356 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11357 * by an underscore.
11358 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011359 strncpy(trash.area, sf->kw, trash.size);
11360 trash.area[trash.size - 1] = '\0';
11361 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011362 if (*p == '.' || *p == '-' || *p == '+')
11363 *p = '_';
11364
11365 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011366 lua_pushstring(L, trash.area);
11367 lua_pushlightuserdata(L, sf);
11368 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
11369 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011370 }
11371
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011372 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011373
11374 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011375 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011376
11377 /*
11378 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011379 * Register class Converters
11380 *
11381 */
11382
11383 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011384 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011385
11386 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011387 lua_pushstring(L, "__index");
11388 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011389
11390 /* Browse existing converters and create the associated
11391 * object method.
11392 */
11393 sc = NULL;
11394 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011395 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11396 * by an underscore.
11397 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011398 strncpy(trash.area, sc->kw, trash.size);
11399 trash.area[trash.size - 1] = '\0';
11400 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011401 if (*p == '.' || *p == '-' || *p == '+')
11402 *p = '_';
11403
11404 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011405 lua_pushstring(L, trash.area);
11406 lua_pushlightuserdata(L, sc);
11407 lua_pushcclosure(L, hlua_run_sample_conv, 1);
11408 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011409 }
11410
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011411 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011412
11413 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011414 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011415
11416 /*
11417 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011418 * Register class HTTP
11419 *
11420 */
11421
11422 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011423 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011424
Ilya Shipitsind4259502020-04-08 01:07:56 +050011425 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011426 lua_pushstring(L, "__index");
11427 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011428
11429 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011430 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
11431 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
11432 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
11433 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
11434 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
11435 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
11436 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
11437 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
11438 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
11439 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011440
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011441 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
11442 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
11443 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
11444 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
11445 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
11446 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
11447 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011448
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011449 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011450
11451 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011452 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011453
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011454 /*
11455 *
11456 * Register class HTTPMessage
11457 *
11458 */
11459
11460 /* Create and fill the metatable. */
11461 lua_newtable(L);
11462
11463 /* Create and fille the __index entry. */
11464 lua_pushstring(L, "__index");
11465 lua_newtable(L);
11466
11467 /* Register Lua functions. */
11468 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
11469 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
11470 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
11471 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
11472 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
11473 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
11474 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
11475 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
11476 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
11477 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
11478 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
11479 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
11480 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
11481 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
11482 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
11483 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
11484 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
11485 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
11486
11487 hlua_class_function(L, "body", hlua_http_msg_get_body);
11488 hlua_class_function(L, "set", hlua_http_msg_set_data);
11489 hlua_class_function(L, "remove", hlua_http_msg_del_data);
11490 hlua_class_function(L, "append", hlua_http_msg_append);
11491 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
11492 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
11493 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
11494 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
11495
11496 hlua_class_function(L, "send", hlua_http_msg_send);
11497 hlua_class_function(L, "forward", hlua_http_msg_forward);
11498
11499 lua_rawset(L, -3);
11500
11501 /* Register previous table in the registry with reference and named entry. */
11502 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011503 /*
11504 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011505 * Register class AppletTCP
11506 *
11507 */
11508
11509 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011510 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011511
Ilya Shipitsind4259502020-04-08 01:07:56 +050011512 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011513 lua_pushstring(L, "__index");
11514 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011515
11516 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011517 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
11518 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
11519 hlua_class_function(L, "send", hlua_applet_tcp_send);
11520 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
11521 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
11522 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
11523 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
11524 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011525
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011526 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011527
11528 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011529 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011530
11531 /*
11532 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011533 * Register class AppletHTTP
11534 *
11535 */
11536
11537 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011538 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011539
Ilya Shipitsind4259502020-04-08 01:07:56 +050011540 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011541 lua_pushstring(L, "__index");
11542 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011543
11544 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011545 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
11546 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
11547 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
11548 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
11549 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
11550 hlua_class_function(L, "getline", hlua_applet_http_getline);
11551 hlua_class_function(L, "receive", hlua_applet_http_recv);
11552 hlua_class_function(L, "send", hlua_applet_http_send);
11553 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
11554 hlua_class_function(L, "set_status", hlua_applet_http_status);
11555 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011556
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011557 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011558
11559 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011560 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011561
11562 /*
11563 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011564 * Register class TXN
11565 *
11566 */
11567
11568 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011569 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011570
Ilya Shipitsind4259502020-04-08 01:07:56 +050011571 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011572 lua_pushstring(L, "__index");
11573 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011574
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011575 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011576 hlua_class_function(L, "set_priv", hlua_set_priv);
11577 hlua_class_function(L, "get_priv", hlua_get_priv);
11578 hlua_class_function(L, "set_var", hlua_set_var);
11579 hlua_class_function(L, "unset_var", hlua_unset_var);
11580 hlua_class_function(L, "get_var", hlua_get_var);
11581 hlua_class_function(L, "done", hlua_txn_done);
11582 hlua_class_function(L, "reply", hlua_txn_reply_new);
11583 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
11584 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
11585 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
11586 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
11587 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
11588 hlua_class_function(L, "deflog", hlua_txn_deflog);
11589 hlua_class_function(L, "log", hlua_txn_log);
11590 hlua_class_function(L, "Debug", hlua_txn_log_debug);
11591 hlua_class_function(L, "Info", hlua_txn_log_info);
11592 hlua_class_function(L, "Warning", hlua_txn_log_warning);
11593 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011594
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011595 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011596
11597 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011598 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011599
11600 /*
11601 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010011602 * Register class reply
11603 *
11604 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011605 lua_newtable(L);
11606 lua_pushstring(L, "__index");
11607 lua_newtable(L);
11608 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
11609 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
11610 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
11611 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
11612 lua_settable(L, -3); /* Sets the __index entry. */
11613 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010011614
11615
11616 /*
11617 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011618 * Register class Socket
11619 *
11620 */
11621
11622 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011623 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011624
Ilya Shipitsind4259502020-04-08 01:07:56 +050011625 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011626 lua_pushstring(L, "__index");
11627 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011628
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011629#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011630 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011631#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011632 hlua_class_function(L, "connect", hlua_socket_connect);
11633 hlua_class_function(L, "send", hlua_socket_send);
11634 hlua_class_function(L, "receive", hlua_socket_receive);
11635 hlua_class_function(L, "close", hlua_socket_close);
11636 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
11637 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
11638 hlua_class_function(L, "setoption", hlua_socket_setoption);
11639 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011640
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011641 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011642
11643 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011644 lua_pushstring(L, "__gc");
11645 lua_pushcclosure(L, hlua_socket_gc, 0);
11646 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011647
11648 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011649 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011650
Thierry Fournieraafc7772020-12-04 11:47:47 +010011651 lua_atpanic(L, hlua_panic_safe);
11652
11653 return L;
11654}
11655
11656void hlua_init(void) {
11657 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011658 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010011659#ifdef USE_OPENSSL
11660 struct srv_kw *kw;
11661 int tmp_error;
11662 char *error;
11663 char *args[] = { /* SSL client configuration. */
11664 "ssl",
11665 "verify",
11666 "none",
11667 NULL
11668 };
11669#endif
11670
11671 /* Init post init function list head */
11672 for (i = 0; i < MAX_THREADS + 1; i++)
11673 LIST_INIT(&hlua_init_functions[i]);
11674
11675 /* Init state for common/shared lua parts */
11676 hlua_state_id = 0;
11677 ha_set_tid(0);
11678 hlua_states[0] = hlua_init_state(0);
11679
11680 /* Init state 1 for thread 0. We have at least one thread. */
11681 hlua_state_id = 1;
11682 ha_set_tid(0);
11683 hlua_states[1] = hlua_init_state(1);
11684
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011685 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020011686 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011687 if (!socket_proxy) {
11688 fprintf(stderr, "Lua init: %s\n", errmsg);
11689 exit(1);
11690 }
11691 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011692
11693 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011694 socket_tcp = new_server(socket_proxy);
11695 if (!socket_tcp) {
11696 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
11697 exit(1);
11698 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011699
11700#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011701 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011702 socket_ssl = new_server(socket_proxy);
11703 if (!socket_ssl) {
11704 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
11705 exit(1);
11706 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011707
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011708 socket_ssl->use_ssl = 1;
11709 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011710
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011711 for (i = 0; args[i] != NULL; i++) {
11712 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011713 /*
11714 *
11715 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011716 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011717 * features like client certificates and ssl_verify.
11718 *
11719 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011720 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011721 if (tmp_error != 0) {
11722 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
11723 abort(); /* This must be never arrives because the command line
11724 not editable by the user. */
11725 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011726 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011727 }
11728 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011729#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010011730
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011731}
Willy Tarreaubb57d942016-12-21 19:04:56 +010011732
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011733static void hlua_deinit()
11734{
Willy Tarreau186f3762020-12-04 11:48:12 +010011735 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011736 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
11737
11738 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
11739 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010011740
11741 for (thr = 0; thr < MAX_THREADS+1; thr++) {
11742 if (hlua_states[thr])
11743 lua_close(hlua_states[thr]);
11744 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011745
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011746 free_server(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011747
Willy Tarreau0f143af2021-03-05 10:41:48 +010011748#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011749 free_server(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010011750#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011751
11752 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011753}
11754
11755REGISTER_POST_DEINIT(hlua_deinit);
11756
Willy Tarreau80713382018-11-26 10:19:54 +010011757static void hlua_register_build_options(void)
11758{
Willy Tarreaubb57d942016-12-21 19:04:56 +010011759 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010011760
Willy Tarreaubb57d942016-12-21 19:04:56 +010011761 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
11762 hap_register_build_opts(ptr, 1);
11763}
Willy Tarreau80713382018-11-26 10:19:54 +010011764
11765INITCALL0(STG_REGISTER, hlua_register_build_options);