blob: be95a97296c97b15b7363215d3960d555a2cacb8 [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 Fauleta1ac5fb2021-08-09 10:22:46 +02003123 offset = MAX(0, input + offset);
3124 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 Fauleta1ac5fb2021-08-09 10:22:46 +02003186 offset = MAX(0, input + offset);
3187 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)
3522 offset = MAX(0, input + offset);
3523 offset += output;
3524
3525 if (offset < output || offset > output + input) {
3526 lua_pushfstring(L, "offset out of range.");
3527 WILL_LJMP(lua_error(L));
3528 }
3529 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003530 if (IS_HTX_STRM(chn_strm(chn))) {
3531 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3532 WILL_LJMP(lua_error(L));
3533 }
3534
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003535 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3536 if (ret > 0 && filter) {
3537 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003538
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003539 flt_update_offsets(filter, chn, ret);
3540 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003541 }
3542
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003543 lua_pushinteger(L, ret);
3544 return 1;
3545}
3546/* Replaces a given amount of input data at the given offset by a string
3547 * content. By default all remaining data are removed (offset = 0 and len =
3548 * -1). It returns the length of the written string, or -1 if the channel is
3549 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003550 *
3551 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003552 */
3553__LJMP static int hlua_channel_set_data(lua_State *L)
3554{
3555 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003556 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003557 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003558 size_t sz, input, output;
3559 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003560
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003561 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3562 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3563 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3564 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003565
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003566 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003567 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003568 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003569 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003570
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003571 output = co_data(chn);
3572 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003573
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003574 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3575 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003576 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003577
3578 offset = output;
3579 if (lua_gettop(L) > 2) {
3580 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3581 if (offset < 0)
3582 offset = MAX(0, input + offset);
3583 offset += output;
3584 if (offset < output || offset > input + output) {
3585 lua_pushfstring(L, "offset out of range.");
3586 WILL_LJMP(lua_error(L));
3587 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003588 }
3589
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003590 len = output + input - offset;
3591 if (lua_gettop(L) == 4) {
3592 len = MAY_LJMP(luaL_checkinteger(L, 4));
3593 if (!len)
3594 goto set;
3595 if (len == -1)
3596 len = output + input - offset;
3597 if (len < 0 || offset + len > output + input) {
3598 lua_pushfstring(L, "length out of range.");
3599 WILL_LJMP(lua_error(L));
3600 }
3601 }
3602
3603 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003604 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003605 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003606 lua_pushinteger(L, -1);
3607 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003608 _hlua_channel_delete(chn, offset, len);
3609 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3610 if (filter) {
3611 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3612
3613 len -= (ret > 0 ? ret : 0);
3614 flt_update_offsets(filter, chn, -len);
3615 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3616 }
3617
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003618 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003619 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003620 return 1;
3621}
3622
3623/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003624 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003625 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003626 *
3627 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003628 */
3629__LJMP static int hlua_channel_del_data(lua_State *L)
3630{
3631 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003632 struct filter *filter;
3633 size_t input, output;
3634 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003635
3636 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3637 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3638 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003639
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003640 if (IS_HTX_STRM(chn_strm(chn))) {
3641 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3642 WILL_LJMP(lua_error(L));
3643 }
3644
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003645 output = co_data(chn);
3646 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003647
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003648 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3649 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003650 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003651
3652 offset = output;
3653 if (lua_gettop(L) > 2) {
3654 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3655 if (offset < 0)
3656 offset = MAX(0, input + offset);
3657 offset += output;
3658 if (offset < output || offset > input + output) {
3659 lua_pushfstring(L, "offset out of range.");
3660 WILL_LJMP(lua_error(L));
3661 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003662 }
3663
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003664 len = output + input - offset;
3665 if (lua_gettop(L) == 4) {
3666 len = MAY_LJMP(luaL_checkinteger(L, 4));
3667 if (!len)
3668 goto end;
3669 if (len == -1)
3670 len = output + input - offset;
3671 if (len < 0 || offset + len > output + input) {
3672 lua_pushfstring(L, "length out of range.");
3673 WILL_LJMP(lua_error(L));
3674 }
3675 }
3676
3677 _hlua_channel_delete(chn, offset, len);
3678 if (filter) {
3679 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3680
3681 flt_update_offsets(filter, chn, -len);
3682 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3683 }
3684
3685 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003686 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003687 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003688}
3689
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003690/* Append data in the output side of the buffer. This data is immediately
3691 * sent. The function returns the amount of data written. If the buffer
3692 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003693 * if the channel is closed.
3694 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003695__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003696{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003697 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003698 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003699 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003700 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003701 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003702 struct hlua *hlua;
3703
3704 /* Get hlua struct, or NULL if we execute from main lua state */
3705 hlua = hlua_gethlua(L);
3706 if (!hlua) {
3707 lua_pushnil(L);
3708 return 1;
3709 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003710
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003711 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3712 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3713 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003714
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003715 offset = co_data(chn);
3716 len = ci_data(chn);
3717
3718 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3719 if (filter && !hlua_filter_from_payload(filter))
3720 WILL_LJMP(lua_error(L));
3721
3722
Willy Tarreau47860ed2015-03-10 14:07:50 +01003723 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003724 lua_pushinteger(L, -1);
3725 return 1;
3726 }
3727
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003728 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003729 if (len > sz -l) {
3730 if (filter) {
3731 lua_pushinteger(L, -1);
3732 return 1;
3733 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003734 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003735 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003736
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003737 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003738 if (ret == -1) {
3739 lua_pop(L, 1);
3740 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003741 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003742 }
3743 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003744 if (filter) {
3745 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3746
3747
3748 flt_update_offsets(filter, chn, ret);
3749 FLT_OFF(filter, chn) += ret;
3750 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3751 }
3752 else
3753 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003754
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003755 l += ret;
3756 lua_pop(L, 1);
3757 lua_pushinteger(L, l);
3758 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003759
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003760 if (l < sz) {
3761 /* Yield only if the channel's output is not empty.
3762 * Otherwise it means we cannot add more data. */
3763 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003764 return 1;
3765
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003766 /* If we are waiting for space in the response buffer, we
3767 * must set the flag WAKERESWR. This flag required the task
3768 * wake up if any activity is detected on the response buffer.
3769 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003770 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003771 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003772 else
3773 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003774 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003775 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003776
3777 return 1;
3778}
3779
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003780/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003781 * yield the LUA process, and resume it without checking the
3782 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003783 *
3784 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003785 */
3786__LJMP static int hlua_channel_send(lua_State *L)
3787{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003788 struct channel *chn;
3789
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003790 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003791 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3792 if (IS_HTX_STRM(chn_strm(chn))) {
3793 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3794 WILL_LJMP(lua_error(L));
3795 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003796 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003797 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003798}
3799
3800/* This function forward and amount of butes. The data pass from
3801 * the input side of the buffer to the output side, and can be
3802 * forwarded. This function never fails.
3803 *
3804 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003805 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003806 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003807__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003808{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003809 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003810 struct filter *filter;
3811 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003812 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003813 struct hlua *hlua;
3814
3815 /* Get hlua struct, or NULL if we execute from main lua state */
3816 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003817 if (!hlua) {
3818 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003819 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003820 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003821
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003822 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003823 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003824 l = MAY_LJMP(luaL_checkinteger(L, -1));
3825
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003826 offset = co_data(chn);
3827 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003828
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003829 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3830 if (filter && !hlua_filter_from_payload(filter))
3831 WILL_LJMP(lua_error(L));
3832
3833 max = fwd - l;
3834 if (max > len)
3835 max = len;
3836
3837 if (filter) {
3838 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3839
3840 FLT_OFF(filter, chn) += max;
3841 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3842 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3843 }
3844 else
3845 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003846
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003847 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003848 lua_pop(L, 1);
3849 lua_pushinteger(L, l);
3850
3851 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003852 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003853 /* The the input channel or the output channel are closed, we
3854 * must return the amount of data forwarded.
3855 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003856 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003857 return 1;
3858
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003859 /* If we are waiting for space data in the response buffer, we
3860 * must set the flag WAKERESWR. This flag required the task
3861 * wake up if any activity is detected on the response buffer.
3862 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003863 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003864 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003865 else
3866 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003867
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003868 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003869 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003870 }
3871
3872 return 1;
3873}
3874
3875/* Just check the input and prepare the stack for the previous
3876 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003877 *
3878 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003879 */
3880__LJMP static int hlua_channel_forward(lua_State *L)
3881{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003882 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003883
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003884 MAY_LJMP(check_args(L, 2, "forward"));
3885 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3886 if (IS_HTX_STRM(chn_strm(chn))) {
3887 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3888 WILL_LJMP(lua_error(L));
3889 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003890 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003891 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003892}
3893
3894/* Just returns the number of bytes available in the input
3895 * side of the buffer. This function never fails.
3896 */
3897__LJMP static int hlua_channel_get_in_len(lua_State *L)
3898{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003899 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003900 struct filter *filter;
3901 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003902
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003903 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003904 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003905
3906 output = co_data(chn);
3907 input = ci_data(chn);
3908 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3909 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3910 lua_pushinteger(L, input);
3911 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003912 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003913
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003914 lua_pushinteger(L, htx->data - co_data(chn));
3915 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003916 return 1;
3917}
3918
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003919/* Returns true if the channel is full. */
3920__LJMP static int hlua_channel_is_full(lua_State *L)
3921{
3922 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003923
3924 MAY_LJMP(check_args(L, 1, "is_full"));
3925 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003926 /* ignore the reserve, we are not on a producer side (ie in an
3927 * applet).
3928 */
3929 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003930 return 1;
3931}
3932
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003933/* Returns true if the channel may still receive data. */
3934__LJMP static int hlua_channel_may_recv(lua_State *L)
3935{
3936 struct channel *chn;
3937
3938 MAY_LJMP(check_args(L, 1, "may_recv"));
3939 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3940 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3941 return 1;
3942}
3943
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003944/* Returns true if the channel is the response channel. */
3945__LJMP static int hlua_channel_is_resp(lua_State *L)
3946{
3947 struct channel *chn;
3948
3949 MAY_LJMP(check_args(L, 1, "is_resp"));
3950 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3951
3952 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3953 return 1;
3954}
3955
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003956/* Just returns the number of bytes available in the output
3957 * side of the buffer. This function never fails.
3958 */
3959__LJMP static int hlua_channel_get_out_len(lua_State *L)
3960{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003961 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003962 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003963
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003964 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003965 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003966
3967 output = co_data(chn);
3968 input = ci_data(chn);
3969 hlua_channel_filter(L, 1, chn, &output, &input);
3970
3971 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003972 return 1;
3973}
3974
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003975/*
3976 *
3977 *
3978 * Class Fetches
3979 *
3980 *
3981 */
3982
3983/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003984 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003985 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003986__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003987{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003988 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003989}
3990
3991/* This function creates and push in the stack a fetch object according
3992 * with a current TXN.
3993 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003994static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003995{
Willy Tarreau7073c472015-04-06 11:15:40 +02003996 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003997
3998 /* Check stack size. */
3999 if (!lua_checkstack(L, 3))
4000 return 0;
4001
4002 /* Create the object: obj[0] = userdata.
4003 * Note that the base of the Fetches object is the
4004 * transaction object.
4005 */
4006 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004007 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004008 lua_rawseti(L, -2, 0);
4009
Willy Tarreau7073c472015-04-06 11:15:40 +02004010 hsmp->s = txn->s;
4011 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004012 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004013 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004014
4015 /* Pop a class sesison metatable and affect it to the userdata. */
4016 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4017 lua_setmetatable(L, -2);
4018
4019 return 1;
4020}
4021
4022/* This function is an LUA binding. It is called with each sample-fetch.
4023 * It uses closure argument to store the associated sample-fetch. It
4024 * returns only one argument or throws an error. An error is thrown
4025 * only if an error is encountered during the argument parsing. If
4026 * the "sample-fetch" function fails, nil is returned.
4027 */
4028__LJMP static int hlua_run_sample_fetch(lua_State *L)
4029{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004030 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004031 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004032 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004033 int i;
4034 struct sample smp;
4035
4036 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004037 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004038
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004039 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004040 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004041
Thierry FOURNIERca988662015-12-20 18:43:03 +01004042 /* Check execution authorization. */
4043 if (f->use & SMP_USE_HTTP_ANY &&
4044 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4045 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4046 "is not available in Lua services", f->kw);
4047 WILL_LJMP(lua_error(L));
4048 }
4049
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004050 /* Get extra arguments. */
4051 for (i = 0; i < lua_gettop(L) - 1; i++) {
4052 if (i >= ARGM_NBARGS)
4053 break;
4054 hlua_lua2arg(L, i + 2, &args[i]);
4055 }
4056 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004057 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004058
4059 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004060 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004061
4062 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004063 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004064 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004065 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004066 }
4067
4068 /* Initialise the sample. */
4069 memset(&smp, 0, sizeof(smp));
4070
4071 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004072 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004073 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004074 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004075 lua_pushstring(L, "");
4076 else
4077 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004078 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004079 }
4080
4081 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004082 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004083 hlua_smp2lua_str(L, &smp);
4084 else
4085 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004086
4087 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004088 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004089 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004090
4091 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004092 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004093 WILL_LJMP(lua_error(L));
4094 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004095}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004096
4097/*
4098 *
4099 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004100 * Class Converters
4101 *
4102 *
4103 */
4104
4105/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004106 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004107 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004108__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004109{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004110 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004111}
4112
4113/* This function creates and push in the stack a Converters object
4114 * according with a current TXN.
4115 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004116static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004117{
Willy Tarreau7073c472015-04-06 11:15:40 +02004118 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004119
4120 /* Check stack size. */
4121 if (!lua_checkstack(L, 3))
4122 return 0;
4123
4124 /* Create the object: obj[0] = userdata.
4125 * Note that the base of the Converters object is the
4126 * same than the TXN object.
4127 */
4128 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004129 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004130 lua_rawseti(L, -2, 0);
4131
Willy Tarreau7073c472015-04-06 11:15:40 +02004132 hsmp->s = txn->s;
4133 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004134 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004135 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004136
Willy Tarreau87b09662015-04-03 00:22:06 +02004137 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004138 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4139 lua_setmetatable(L, -2);
4140
4141 return 1;
4142}
4143
4144/* This function is an LUA binding. It is called with each converter.
4145 * It uses closure argument to store the associated converter. It
4146 * returns only one argument or throws an error. An error is thrown
4147 * only if an error is encountered during the argument parsing. If
4148 * the converter function function fails, nil is returned.
4149 */
4150__LJMP static int hlua_run_sample_conv(lua_State *L)
4151{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004152 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004153 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004154 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004155 int i;
4156 struct sample smp;
4157
4158 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004159 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004160
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004161 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004162 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004163
4164 /* Get extra arguments. */
4165 for (i = 0; i < lua_gettop(L) - 2; i++) {
4166 if (i >= ARGM_NBARGS)
4167 break;
4168 hlua_lua2arg(L, i + 3, &args[i]);
4169 }
4170 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004171 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004172
4173 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004174 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004175
4176 /* Run the special args checker. */
4177 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4178 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004179 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004180 }
4181
4182 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004183 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004184 if (!hlua_lua2smp(L, 2, &smp)) {
4185 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004186 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004187 }
4188
Willy Tarreau1777ea62016-03-10 16:15:46 +01004189 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4190
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004191 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004192 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004193 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004194 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004195 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004196 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004197 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4198 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004199 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004200 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004201 }
4202
4203 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004204 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004205 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004206 lua_pushstring(L, "");
4207 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004208 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004209 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210 }
4211
4212 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004213 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004214 hlua_smp2lua_str(L, &smp);
4215 else
4216 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004217 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004218 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004219 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004220
4221 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004222 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004223 WILL_LJMP(lua_error(L));
4224 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004225}
4226
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004227/*
4228 *
4229 *
4230 * Class AppletTCP
4231 *
4232 *
4233 */
4234
4235/* Returns a struct hlua_txn if the stack entry "ud" is
4236 * a class stream, otherwise it throws an error.
4237 */
4238__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4239{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004240 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004241}
4242
4243/* This function creates and push in the stack an Applet object
4244 * according with a current TXN.
4245 */
4246static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4247{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004248 struct hlua_appctx *luactx;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004249 struct stream_interface *si = ctx->owner;
4250 struct stream *s = si_strm(si);
4251 struct proxy *p = s->be;
4252
4253 /* Check stack size. */
4254 if (!lua_checkstack(L, 3))
4255 return 0;
4256
4257 /* Create the object: obj[0] = userdata.
4258 * Note that the base of the Converters object is the
4259 * same than the TXN object.
4260 */
4261 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004262 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004263 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004264 luactx->appctx = ctx;
4265 luactx->htxn.s = s;
4266 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004267
4268 /* Create the "f" field that contains a list of fetches. */
4269 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004270 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004271 return 0;
4272 lua_settable(L, -3);
4273
4274 /* Create the "sf" field that contains a list of stringsafe fetches. */
4275 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004276 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004277 return 0;
4278 lua_settable(L, -3);
4279
4280 /* Create the "c" field that contains a list of converters. */
4281 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004282 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004283 return 0;
4284 lua_settable(L, -3);
4285
4286 /* Create the "sc" field that contains a list of stringsafe converters. */
4287 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004288 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004289 return 0;
4290 lua_settable(L, -3);
4291
4292 /* Pop a class stream metatable and affect it to the table. */
4293 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4294 lua_setmetatable(L, -2);
4295
4296 return 1;
4297}
4298
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004299__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4300{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004301 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004302 struct stream *s;
4303 const char *name;
4304 size_t len;
4305 struct sample smp;
4306
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004307 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4308 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004309
4310 /* It is useles to retrieve the stream, but this function
4311 * runs only in a stream context.
4312 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004313 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004314 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004315 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004316
4317 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004318 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004319 hlua_lua2smp(L, 3, &smp);
4320
4321 /* Store the sample in a variable. */
4322 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004323
4324 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4325 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4326 else
4327 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4328
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004329 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004330}
4331
4332__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4333{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004334 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004335 struct stream *s;
4336 const char *name;
4337 size_t len;
4338 struct sample smp;
4339
4340 MAY_LJMP(check_args(L, 2, "unset_var"));
4341
4342 /* It is useles to retrieve the stream, but this function
4343 * runs only in a stream context.
4344 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004345 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004346 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004347 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004348
4349 /* Unset the variable. */
4350 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004351 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4352 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004353}
4354
4355__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4356{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004357 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004358 struct stream *s;
4359 const char *name;
4360 size_t len;
4361 struct sample smp;
4362
4363 MAY_LJMP(check_args(L, 2, "get_var"));
4364
4365 /* It is useles to retrieve the stream, but this function
4366 * runs only in a stream context.
4367 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004368 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004369 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004370 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004371
4372 smp_set_owner(&smp, s->be, s->sess, s, 0);
4373 if (!vars_get_by_name(name, len, &smp)) {
4374 lua_pushnil(L);
4375 return 1;
4376 }
4377
4378 return hlua_smp2lua(L, &smp);
4379}
4380
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004381__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4382{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004383 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4384 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004385 struct hlua *hlua;
4386
4387 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004388 if (!s->hlua)
4389 return 0;
4390 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004391
4392 MAY_LJMP(check_args(L, 2, "set_priv"));
4393
4394 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004395 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004396
4397 /* Get and store new value. */
4398 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4399 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4400
4401 return 0;
4402}
4403
4404__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4405{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004406 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4407 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004408 struct hlua *hlua;
4409
4410 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004411 if (!s->hlua) {
4412 lua_pushnil(L);
4413 return 1;
4414 }
4415 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004416
4417 /* Push configuration index in the stack. */
4418 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4419
4420 return 1;
4421}
4422
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004423/* If expected data not yet available, it returns a yield. This function
4424 * consumes the data in the buffer. It returns a string containing the
4425 * data. This string can be empty.
4426 */
4427__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4428{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004429 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4430 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004431 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004432 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004433 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004434 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004435 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004436
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004437 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004438 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004439
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004440 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004441 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004442 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004443 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004444 }
4445
4446 /* End of data: commit the total strings and return. */
4447 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004448 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004449 return 1;
4450 }
4451
4452 /* Ensure that the block 2 length is usable. */
4453 if (ret == 1)
4454 len2 = 0;
4455
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004456 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004457 luaL_addlstring(&luactx->b, blk1, len1);
4458 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004459
4460 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004461 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004462 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004463 return 1;
4464}
4465
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004466/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004467__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4468{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004469 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004470
4471 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004472 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004473
4474 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4475}
4476
4477/* If expected data not yet available, it returns a yield. This function
4478 * consumes the data in the buffer. It returns a string containing the
4479 * data. This string can be empty.
4480 */
4481__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4482{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004483 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4484 struct stream_interface *si = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004485 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004486 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004487 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004488 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004489 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004490 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004491
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004492 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004493 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004494
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004495 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004496 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004497 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004498 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004499 }
4500
4501 /* End of data: commit the total strings and return. */
4502 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004503 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004504 return 1;
4505 }
4506
4507 /* Ensure that the block 2 length is usable. */
4508 if (ret == 1)
4509 len2 = 0;
4510
4511 if (len == -1) {
4512
4513 /* If len == -1, catenate all the data avalaile and
4514 * yield because we want to get all the data until
4515 * the end of data stream.
4516 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004517 luaL_addlstring(&luactx->b, blk1, len1);
4518 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004519 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004520 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004521 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004522
4523 } else {
4524
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004525 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004526 if (len1 > len)
4527 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004528 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004529 len -= len1;
4530
4531 /* Copy the second block. */
4532 if (len2 > len)
4533 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004534 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004535 len -= len2;
4536
4537 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004538 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004539
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004540 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004541 if (len > 0) {
4542 lua_pushinteger(L, len);
4543 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004544 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004545 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004546 }
4547
4548 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004549 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004550 return 1;
4551 }
4552
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004553 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004554 hlua_pusherror(L, "Lua: internal error");
4555 WILL_LJMP(lua_error(L));
4556 return 0;
4557}
4558
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004559/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004560__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4561{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004562 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004563 int len = -1;
4564
4565 if (lua_gettop(L) > 2)
4566 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4567 if (lua_gettop(L) >= 2) {
4568 len = MAY_LJMP(luaL_checkinteger(L, 2));
4569 lua_pop(L, 1);
4570 }
4571
4572 /* Confirm or set the required length */
4573 lua_pushinteger(L, len);
4574
4575 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004576 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004577
4578 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4579}
4580
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004581/* Append data in the output side of the buffer. This data is immediately
4582 * sent. The function returns the amount of data written. If the buffer
4583 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004584 * if the channel is closed.
4585 */
4586__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4587{
4588 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004589 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004590 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4591 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004592 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004593 struct channel *chn = si_ic(si);
4594 int max;
4595
4596 /* Get the max amount of data which can write as input in the channel. */
4597 max = channel_recv_max(chn);
4598 if (max > (len - l))
4599 max = len - l;
4600
4601 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004602 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004603
4604 /* update counters. */
4605 l += max;
4606 lua_pop(L, 1);
4607 lua_pushinteger(L, l);
4608
4609 /* If some data is not send, declares the situation to the
4610 * applet, and returns a yield.
4611 */
4612 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004613 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004614 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004615 }
4616
4617 return 1;
4618}
4619
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004620/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004621 * yield the LUA process, and resume it without checking the
4622 * input arguments.
4623 */
4624__LJMP static int hlua_applet_tcp_send(lua_State *L)
4625{
4626 MAY_LJMP(check_args(L, 2, "send"));
4627 lua_pushinteger(L, 0);
4628
4629 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4630}
4631
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004632/*
4633 *
4634 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004635 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004636 *
4637 *
4638 */
4639
4640/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004641 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004642 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004643__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004644{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004645 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004646}
4647
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004648/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004649 * according with a current TXN.
4650 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004651static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004652{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004653 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004654 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004655 struct stream_interface *si = ctx->owner;
4656 struct stream *s = si_strm(si);
4657 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004658 struct htx *htx;
4659 struct htx_blk *blk;
4660 struct htx_sl *sl;
4661 struct ist path;
4662 unsigned long long len = 0;
4663 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004664 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004665
4666 /* Check stack size. */
4667 if (!lua_checkstack(L, 3))
4668 return 0;
4669
4670 /* Create the object: obj[0] = userdata.
4671 * Note that the base of the Converters object is the
4672 * same than the TXN object.
4673 */
4674 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004675 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004676 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004677 luactx->appctx = ctx;
4678 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4679 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4680 luactx->htxn.s = s;
4681 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004682
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004683 /* Create the "f" field that contains a list of fetches. */
4684 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004685 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004686 return 0;
4687 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004688
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004689 /* Create the "sf" field that contains a list of stringsafe fetches. */
4690 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004691 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004692 return 0;
4693 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004694
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004695 /* Create the "c" field that contains a list of converters. */
4696 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004697 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004698 return 0;
4699 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004700
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004701 /* Create the "sc" field that contains a list of stringsafe converters. */
4702 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004703 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004704 return 0;
4705 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004706
Christopher Fauleta2097962019-07-15 16:25:33 +02004707 htx = htxbuf(&s->req.buf);
4708 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004709 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004710 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004711
Christopher Fauleta2097962019-07-15 16:25:33 +02004712 /* Stores the request method. */
4713 lua_pushstring(L, "method");
4714 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4715 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004716
Christopher Fauleta2097962019-07-15 16:25:33 +02004717 /* Stores the http version. */
4718 lua_pushstring(L, "version");
4719 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4720 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004721
Christopher Fauleta2097962019-07-15 16:25:33 +02004722 /* creates an array of headers. hlua_http_get_headers() crates and push
4723 * the array on the top of the stack.
4724 */
4725 lua_pushstring(L, "headers");
4726 htxn.s = s;
4727 htxn.p = px;
4728 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004729 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004730 return 0;
4731 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004732
Amaury Denoyellec453f952021-07-06 11:40:12 +02004733 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4734 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004735 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004736 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004737
Christopher Fauleta2097962019-07-15 16:25:33 +02004738 p = path.ptr;
4739 end = path.ptr + path.len;
4740 q = p;
4741 while (q < end && *q != '?')
4742 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004743
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004744 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004745 lua_pushstring(L, "path");
4746 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004747 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004748
Christopher Fauleta2097962019-07-15 16:25:33 +02004749 /* Stores the query string. */
4750 lua_pushstring(L, "qs");
4751 if (*q == '?')
4752 q++;
4753 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004754 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004755 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004756
Christopher Fauleta2097962019-07-15 16:25:33 +02004757 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4758 struct htx_blk *blk = htx_get_blk(htx, pos);
4759 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004760
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004761 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004762 break;
4763 if (type == HTX_BLK_DATA)
4764 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004765 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004766 if (htx->extra != ULLONG_MAX)
4767 len += htx->extra;
4768
4769 /* Stores the request path. */
4770 lua_pushstring(L, "length");
4771 lua_pushinteger(L, len);
4772 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004773
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004774 /* Create an empty array of HTTP request headers. */
4775 lua_pushstring(L, "response");
4776 lua_newtable(L);
4777 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004778
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004779 /* Pop a class stream metatable and affect it to the table. */
4780 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4781 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004782
4783 return 1;
4784}
4785
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004786__LJMP static int hlua_applet_http_set_var(lua_State *L)
4787{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004788 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004789 struct stream *s;
4790 const char *name;
4791 size_t len;
4792 struct sample smp;
4793
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004794 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4795 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004796
4797 /* It is useles to retrieve the stream, but this function
4798 * runs only in a stream context.
4799 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004800 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004801 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004802 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004803
4804 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004805 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004806 hlua_lua2smp(L, 3, &smp);
4807
4808 /* Store the sample in a variable. */
4809 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004810
4811 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4812 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4813 else
4814 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4815
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004816 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004817}
4818
4819__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4820{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004821 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004822 struct stream *s;
4823 const char *name;
4824 size_t len;
4825 struct sample smp;
4826
4827 MAY_LJMP(check_args(L, 2, "unset_var"));
4828
4829 /* It is useles to retrieve the stream, but this function
4830 * runs only in a stream context.
4831 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004832 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004833 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004834 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004835
4836 /* Unset the variable. */
4837 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004838 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4839 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004840}
4841
4842__LJMP static int hlua_applet_http_get_var(lua_State *L)
4843{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004844 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004845 struct stream *s;
4846 const char *name;
4847 size_t len;
4848 struct sample smp;
4849
4850 MAY_LJMP(check_args(L, 2, "get_var"));
4851
4852 /* It is useles to retrieve the stream, but this function
4853 * runs only in a stream context.
4854 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004855 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004856 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004857 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004858
4859 smp_set_owner(&smp, s->be, s->sess, s, 0);
4860 if (!vars_get_by_name(name, len, &smp)) {
4861 lua_pushnil(L);
4862 return 1;
4863 }
4864
4865 return hlua_smp2lua(L, &smp);
4866}
4867
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004868__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4869{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004870 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4871 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004872 struct hlua *hlua;
4873
4874 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004875 if (!s->hlua)
4876 return 0;
4877 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004878
4879 MAY_LJMP(check_args(L, 2, "set_priv"));
4880
4881 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004882 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004883
4884 /* Get and store new value. */
4885 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4886 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4887
4888 return 0;
4889}
4890
4891__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4892{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004893 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4894 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004895 struct hlua *hlua;
4896
4897 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004898 if (!s->hlua) {
4899 lua_pushnil(L);
4900 return 1;
4901 }
4902 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004903
4904 /* Push configuration index in the stack. */
4905 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4906
4907 return 1;
4908}
4909
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004910/* If expected data not yet available, it returns a yield. This function
4911 * consumes the data in the buffer. It returns a string containing the
4912 * data. This string can be empty.
4913 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004914__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004915{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004916 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4917 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004918 struct channel *req = si_oc(si);
4919 struct htx *htx;
4920 struct htx_blk *blk;
4921 size_t count;
4922 int stop = 0;
4923
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004924 htx = htx_from_buf(&req->buf);
4925 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004926 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004927
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004928 while (count && !stop && blk) {
4929 enum htx_blk_type type = htx_get_blk_type(blk);
4930 uint32_t sz = htx_get_blksz(blk);
4931 struct ist v;
4932 uint32_t vlen;
4933 char *nl;
4934
4935 vlen = sz;
4936 if (vlen > count) {
4937 if (type != HTX_BLK_DATA)
4938 break;
4939 vlen = count;
4940 }
4941
4942 switch (type) {
4943 case HTX_BLK_UNUSED:
4944 break;
4945
4946 case HTX_BLK_DATA:
4947 v = htx_get_blk_value(htx, blk);
4948 v.len = vlen;
4949 nl = istchr(v, '\n');
4950 if (nl != NULL) {
4951 stop = 1;
4952 vlen = nl - v.ptr + 1;
4953 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004954 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004955 break;
4956
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004957 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004958 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004959 stop = 1;
4960 break;
4961
4962 default:
4963 break;
4964 }
4965
4966 co_set_data(req, co_data(req) - vlen);
4967 count -= vlen;
4968 if (sz == vlen)
4969 blk = htx_remove_blk(htx, blk);
4970 else {
4971 htx_cut_data_blk(htx, blk, vlen);
4972 break;
4973 }
4974 }
4975
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004976 /* The message was fully consumed and no more data are expected
4977 * (EOM flag set).
4978 */
4979 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
4980 stop = 1;
4981
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004982 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004983 if (!stop) {
4984 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004985 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004986 }
4987
4988 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004989 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004990 return 1;
4991}
4992
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004993
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004994/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004995__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004996{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004997 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004998
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004999 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005000 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005001
Christopher Fauleta2097962019-07-15 16:25:33 +02005002 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005003}
5004
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005005/* If expected data not yet available, it returns a yield. This function
5006 * consumes the data in the buffer. It returns a string containing the
5007 * data. This string can be empty.
5008 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005009__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005010{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005011 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5012 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005013 struct channel *req = si_oc(si);
5014 struct htx *htx;
5015 struct htx_blk *blk;
5016 size_t count;
5017 int len;
5018
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005019 htx = htx_from_buf(&req->buf);
5020 len = MAY_LJMP(luaL_checkinteger(L, 2));
5021 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005022 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005023 while (count && len && blk) {
5024 enum htx_blk_type type = htx_get_blk_type(blk);
5025 uint32_t sz = htx_get_blksz(blk);
5026 struct ist v;
5027 uint32_t vlen;
5028
5029 vlen = sz;
5030 if (len > 0 && vlen > len)
5031 vlen = len;
5032 if (vlen > count) {
5033 if (type != HTX_BLK_DATA)
5034 break;
5035 vlen = count;
5036 }
5037
5038 switch (type) {
5039 case HTX_BLK_UNUSED:
5040 break;
5041
5042 case HTX_BLK_DATA:
5043 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005044 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005045 break;
5046
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005047 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005048 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005049 len = 0;
5050 break;
5051
5052 default:
5053 break;
5054 }
5055
5056 co_set_data(req, co_data(req) - vlen);
5057 count -= vlen;
5058 if (len > 0)
5059 len -= vlen;
5060 if (sz == vlen)
5061 blk = htx_remove_blk(htx, blk);
5062 else {
5063 htx_cut_data_blk(htx, blk, vlen);
5064 break;
5065 }
5066 }
5067
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005068 /* The message was fully consumed and no more data are expected
5069 * (EOM flag set).
5070 */
5071 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5072 len = 0;
5073
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005074 htx_to_buf(htx, &req->buf);
5075
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005076 /* If we are no other data available, yield waiting for new data. */
5077 if (len) {
5078 if (len > 0) {
5079 lua_pushinteger(L, len);
5080 lua_replace(L, 2);
5081 }
5082 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005083 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005084 }
5085
5086 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005087 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005088 return 1;
5089}
5090
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005091/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005092__LJMP static int hlua_applet_http_recv(lua_State *L)
5093{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005094 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005095 int len = -1;
5096
5097 /* Check arguments. */
5098 if (lua_gettop(L) > 2)
5099 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5100 if (lua_gettop(L) >= 2) {
5101 len = MAY_LJMP(luaL_checkinteger(L, 2));
5102 lua_pop(L, 1);
5103 }
5104
Christopher Fauleta2097962019-07-15 16:25:33 +02005105 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005106
Christopher Fauleta2097962019-07-15 16:25:33 +02005107 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005108 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005109
Christopher Fauleta2097962019-07-15 16:25:33 +02005110 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005111}
5112
5113/* Append data in the output side of the buffer. This data is immediately
5114 * sent. The function returns the amount of data written. If the buffer
5115 * cannot contain the data, the function yields. The function returns -1
5116 * if the channel is closed.
5117 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005118__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005119{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005120 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5121 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005122 struct channel *res = si_ic(si);
5123 struct htx *htx = htx_from_buf(&res->buf);
5124 const char *data;
5125 size_t len;
5126 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5127 int max;
5128
Christopher Faulet9060fc02019-07-03 11:39:30 +02005129 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005130 if (!max)
5131 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005132
5133 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5134
5135 /* Get the max amount of data which can write as input in the channel. */
5136 if (max > (len - l))
5137 max = len - l;
5138
5139 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005140 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005141 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005142
5143 /* update counters. */
5144 l += max;
5145 lua_pop(L, 1);
5146 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005147
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005148 /* If some data is not send, declares the situation to the
5149 * applet, and returns a yield.
5150 */
5151 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005152 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005153 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005154 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005155 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005156 }
5157
Christopher Fauleta2097962019-07-15 16:25:33 +02005158 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005159 return 1;
5160}
5161
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005162/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005163 * yield the LUA process, and resume it without checking the
5164 * input arguments.
5165 */
5166__LJMP static int hlua_applet_http_send(lua_State *L)
5167{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005168 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005169
5170 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005171 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005172 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5173 WILL_LJMP(lua_error(L));
5174 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005175
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005176 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005177 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005178
Christopher Fauleta2097962019-07-15 16:25:33 +02005179 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005180}
5181
5182__LJMP static int hlua_applet_http_addheader(lua_State *L)
5183{
5184 const char *name;
5185 int ret;
5186
5187 MAY_LJMP(hlua_checkapplet_http(L, 1));
5188 name = MAY_LJMP(luaL_checkstring(L, 2));
5189 MAY_LJMP(luaL_checkstring(L, 3));
5190
5191 /* Push in the stack the "response" entry. */
5192 ret = lua_getfield(L, 1, "response");
5193 if (ret != LUA_TTABLE) {
5194 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5195 "is expected as an array. %s found", lua_typename(L, ret));
5196 WILL_LJMP(lua_error(L));
5197 }
5198
5199 /* check if the header is already registered if it is not
5200 * the case, register it.
5201 */
5202 ret = lua_getfield(L, -1, name);
5203 if (ret == LUA_TNIL) {
5204
5205 /* Entry not found. */
5206 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5207
5208 /* Insert the new header name in the array in the top of the stack.
5209 * It left the new array in the top of the stack.
5210 */
5211 lua_newtable(L);
5212 lua_pushvalue(L, 2);
5213 lua_pushvalue(L, -2);
5214 lua_settable(L, -4);
5215
5216 } else if (ret != LUA_TTABLE) {
5217
5218 /* corruption error. */
5219 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5220 "is expected as an array. %s found", name, lua_typename(L, ret));
5221 WILL_LJMP(lua_error(L));
5222 }
5223
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005224 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005225 * the header value as new entry.
5226 */
5227 lua_pushvalue(L, 3);
5228 ret = lua_rawlen(L, -2);
5229 lua_rawseti(L, -2, ret + 1);
5230 lua_pushboolean(L, 1);
5231 return 1;
5232}
5233
5234__LJMP static int hlua_applet_http_status(lua_State *L)
5235{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005236 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005237 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005238 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005239
5240 if (status < 100 || status > 599) {
5241 lua_pushboolean(L, 0);
5242 return 1;
5243 }
5244
Willy Tarreau7e702d12021-04-28 17:59:21 +02005245 luactx->appctx->ctx.hlua_apphttp.status = status;
5246 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005247 lua_pushboolean(L, 1);
5248 return 1;
5249}
5250
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005251
Christopher Fauleta2097962019-07-15 16:25:33 +02005252__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005253{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005254 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5255 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005256 struct channel *res = si_ic(si);
5257 struct htx *htx;
5258 struct htx_sl *sl;
5259 struct h1m h1m;
5260 const char *status, *reason;
5261 const char *name, *value;
5262 size_t nlen, vlen;
5263 unsigned int flags;
5264
5265 /* Send the message at once. */
5266 htx = htx_from_buf(&res->buf);
5267 h1m_init_res(&h1m);
5268
5269 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005270 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5271 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005272 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005273 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5274 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005275 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5276 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5277 }
5278 else {
5279 flags = HTX_SL_F_IS_RESP;
5280 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5281 }
5282 if (!sl) {
5283 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005284 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005285 WILL_LJMP(lua_error(L));
5286 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005287 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005288
5289 /* Get the array associated to the field "response" in the object AppletHTTP. */
5290 lua_pushvalue(L, 0);
5291 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5292 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005293 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005294 WILL_LJMP(lua_error(L));
5295 }
5296
5297 /* Browse the list of headers. */
5298 lua_pushnil(L);
5299 while(lua_next(L, -2) != 0) {
5300 /* We expect a string as -2. */
5301 if (lua_type(L, -2) != LUA_TSTRING) {
5302 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005303 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005304 lua_typename(L, lua_type(L, -2)));
5305 WILL_LJMP(lua_error(L));
5306 }
5307 name = lua_tolstring(L, -2, &nlen);
5308
5309 /* We expect an array as -1. */
5310 if (lua_type(L, -1) != LUA_TTABLE) {
5311 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 +02005312 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005313 name,
5314 lua_typename(L, lua_type(L, -1)));
5315 WILL_LJMP(lua_error(L));
5316 }
5317
5318 /* Browse the table who is on the top of the stack. */
5319 lua_pushnil(L);
5320 while(lua_next(L, -2) != 0) {
5321 int id;
5322
5323 /* We expect a number as -2. */
5324 if (lua_type(L, -2) != LUA_TNUMBER) {
5325 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 +02005326 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005327 name,
5328 lua_typename(L, lua_type(L, -2)));
5329 WILL_LJMP(lua_error(L));
5330 }
5331 id = lua_tointeger(L, -2);
5332
5333 /* We expect a string as -2. */
5334 if (lua_type(L, -1) != LUA_TSTRING) {
5335 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 +02005336 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005337 name, id,
5338 lua_typename(L, lua_type(L, -1)));
5339 WILL_LJMP(lua_error(L));
5340 }
5341 value = lua_tolstring(L, -1, &vlen);
5342
5343 /* Simple Protocol checks. */
5344 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01005345 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005346 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5347 struct ist v = ist2(value, vlen);
5348 int ret;
5349
5350 ret = h1_parse_cont_len_header(&h1m, &v);
5351 if (ret < 0) {
5352 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005353 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005354 name);
5355 WILL_LJMP(lua_error(L));
5356 }
5357 else if (ret == 0)
5358 goto next; /* Skip it */
5359 }
5360
5361 /* Add a new header */
5362 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5363 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005364 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005365 name);
5366 WILL_LJMP(lua_error(L));
5367 }
5368 next:
5369 /* Remove the array from the stack, and get next element with a remaining string. */
5370 lua_pop(L, 1);
5371 }
5372
5373 /* Remove the array from the stack, and get next element with a remaining string. */
5374 lua_pop(L, 1);
5375 }
5376
5377 if (h1m.flags & H1_MF_CHNK)
5378 h1m.flags &= ~H1_MF_CLEN;
5379 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5380 h1m.flags |= H1_MF_XFER_LEN;
5381
5382 /* Uset HTX start-line flags */
5383 if (h1m.flags & H1_MF_XFER_ENC)
5384 flags |= HTX_SL_F_XFER_ENC;
5385 if (h1m.flags & H1_MF_XFER_LEN) {
5386 flags |= HTX_SL_F_XFER_LEN;
5387 if (h1m.flags & H1_MF_CHNK)
5388 flags |= HTX_SL_F_CHNK;
5389 else if (h1m.flags & H1_MF_CLEN)
5390 flags |= HTX_SL_F_CLEN;
5391 if (h1m.body_len == 0)
5392 flags |= HTX_SL_F_BODYLESS;
5393 }
5394 sl->flags |= flags;
5395
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005396 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005397 * and the status code implies the presence of a message body, we must
5398 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005399 * for the keepalive compliance. If the applet announces a transfer-encoding
5400 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005401 */
5402 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005403 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5404 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5405 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005406 /* Add a new header */
5407 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5408 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5409 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005410 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005411 WILL_LJMP(lua_error(L));
5412 }
5413 }
5414
5415 /* Finalize headers. */
5416 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5417 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005418 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005419 WILL_LJMP(lua_error(L));
5420 }
5421
5422 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5423 b_reset(&res->buf);
5424 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5425 WILL_LJMP(lua_error(L));
5426 }
5427
5428 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005429 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005430
5431 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005432 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005433 return 0;
5434
5435}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005436/* We will build the status line and the headers of the HTTP response.
5437 * We will try send at once if its not possible, we give back the hand
5438 * waiting for more room.
5439 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005440__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005441{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005442 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5443 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005444 struct channel *res = si_ic(si);
5445
5446 if (co_data(res)) {
5447 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005448 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005449 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005450 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005451}
5452
5453
Christopher Fauleta2097962019-07-15 16:25:33 +02005454__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005455{
Christopher Fauleta2097962019-07-15 16:25:33 +02005456 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005457}
5458
Christopher Fauleta2097962019-07-15 16:25:33 +02005459/*
5460 *
5461 *
5462 * Class HTTP
5463 *
5464 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005465 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005466
5467/* Returns a struct hlua_txn if the stack entry "ud" is
5468 * a class stream, otherwise it throws an error.
5469 */
5470__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005471{
Christopher Fauleta2097962019-07-15 16:25:33 +02005472 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5473}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005474
Christopher Fauleta2097962019-07-15 16:25:33 +02005475/* This function creates and push in the stack a HTTP object
5476 * according with a current TXN.
5477 */
5478static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5479{
5480 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005481
Christopher Fauleta2097962019-07-15 16:25:33 +02005482 /* Check stack size. */
5483 if (!lua_checkstack(L, 3))
5484 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005485
Christopher Fauleta2097962019-07-15 16:25:33 +02005486 /* Create the object: obj[0] = userdata.
5487 * Note that the base of the Converters object is the
5488 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005489 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005490 lua_newtable(L);
5491 htxn = lua_newuserdata(L, sizeof(*htxn));
5492 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005493
5494 htxn->s = txn->s;
5495 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005496 htxn->dir = txn->dir;
5497 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005498
5499 /* Pop a class stream metatable and affect it to the table. */
5500 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5501 lua_setmetatable(L, -2);
5502
5503 return 1;
5504}
5505
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005506/* This function creates and returns an array containing the status-line
5507 * elements. This function does not fails.
5508 */
5509__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5510{
5511 /* Create the table. */
5512 lua_newtable(L);
5513
5514 if (sl->flags & HTX_SL_F_IS_RESP) {
5515 lua_pushstring(L, "version");
5516 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5517 lua_settable(L, -3);
5518 lua_pushstring(L, "code");
5519 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5520 lua_settable(L, -3);
5521 lua_pushstring(L, "reason");
5522 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5523 lua_settable(L, -3);
5524 }
5525 else {
5526 lua_pushstring(L, "method");
5527 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5528 lua_settable(L, -3);
5529 lua_pushstring(L, "uri");
5530 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5531 lua_settable(L, -3);
5532 lua_pushstring(L, "version");
5533 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5534 lua_settable(L, -3);
5535 }
5536 return 1;
5537}
5538
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005539/* This function creates ans returns an array of HTTP headers.
5540 * This function does not fails. It is used as wrapper with the
5541 * 2 following functions.
5542 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005543__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005544{
Christopher Fauleta2097962019-07-15 16:25:33 +02005545 struct htx *htx;
5546 int32_t pos;
5547
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005548 /* Create the table. */
5549 lua_newtable(L);
5550
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005551
Christopher Fauleta2097962019-07-15 16:25:33 +02005552 htx = htxbuf(&msg->chn->buf);
5553 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5554 struct htx_blk *blk = htx_get_blk(htx, pos);
5555 enum htx_blk_type type = htx_get_blk_type(blk);
5556 struct ist n, v;
5557 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005558
Christopher Fauleta2097962019-07-15 16:25:33 +02005559 if (type == HTX_BLK_HDR) {
5560 n = htx_get_blk_name(htx,blk);
5561 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005562 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005563 else if (type == HTX_BLK_EOH)
5564 break;
5565 else
5566 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005567
Christopher Fauleta2097962019-07-15 16:25:33 +02005568 /* Check for existing entry:
5569 * assume that the table is on the top of the stack, and
5570 * push the key in the stack, the function lua_gettable()
5571 * perform the lookup.
5572 */
5573 lua_pushlstring(L, n.ptr, n.len);
5574 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005575
Christopher Fauleta2097962019-07-15 16:25:33 +02005576 switch (lua_type(L, -1)) {
5577 case LUA_TNIL:
5578 /* Table not found, create it. */
5579 lua_pop(L, 1); /* remove the nil value. */
5580 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5581 lua_newtable(L); /* create and push empty table. */
5582 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5583 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5584 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005585 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005586
Christopher Fauleta2097962019-07-15 16:25:33 +02005587 case LUA_TTABLE:
5588 /* Entry found: push the value in the table. */
5589 len = lua_rawlen(L, -1);
5590 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5591 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5592 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5593 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005594
Christopher Fauleta2097962019-07-15 16:25:33 +02005595 default:
5596 /* Other cases are errors. */
5597 hlua_pusherror(L, "internal error during the parsing of headers.");
5598 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005599 }
5600 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005601 return 1;
5602}
5603
5604__LJMP static int hlua_http_req_get_headers(lua_State *L)
5605{
5606 struct hlua_txn *htxn;
5607
5608 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5609 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5610
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005611 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005612 WILL_LJMP(lua_error(L));
5613
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005614 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005615}
5616
5617__LJMP static int hlua_http_res_get_headers(lua_State *L)
5618{
5619 struct hlua_txn *htxn;
5620
5621 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5622 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5623
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005624 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005625 WILL_LJMP(lua_error(L));
5626
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005627 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005628}
5629
5630/* This function replace full header, or just a value in
5631 * the request or in the response. It is a wrapper fir the
5632 * 4 following functions.
5633 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005634__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005635{
5636 size_t name_len;
5637 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5638 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5639 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005640 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005641 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005642
Dragan Dosen26743032019-04-30 15:54:36 +02005643 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005644 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5645
Christopher Fauleta2097962019-07-15 16:25:33 +02005646 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005647 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005648 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005649 return 0;
5650}
5651
5652__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5653{
5654 struct hlua_txn *htxn;
5655
5656 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5657 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5658
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005659 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005660 WILL_LJMP(lua_error(L));
5661
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005662 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005663}
5664
5665__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5666{
5667 struct hlua_txn *htxn;
5668
5669 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5670 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5671
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005672 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005673 WILL_LJMP(lua_error(L));
5674
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005675 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005676}
5677
5678__LJMP static int hlua_http_req_rep_val(lua_State *L)
5679{
5680 struct hlua_txn *htxn;
5681
5682 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5683 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5684
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005685 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005686 WILL_LJMP(lua_error(L));
5687
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005688 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005689}
5690
5691__LJMP static int hlua_http_res_rep_val(lua_State *L)
5692{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005693 struct hlua_txn *htxn;
5694
5695 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5696 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5697
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005698 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005699 WILL_LJMP(lua_error(L));
5700
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005701 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005702}
5703
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005704/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005705 * It is a wrapper for the 2 following functions.
5706 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005707__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005708{
5709 size_t len;
5710 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005711 struct htx *htx = htxbuf(&msg->chn->buf);
5712 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005713
Christopher Fauleta2097962019-07-15 16:25:33 +02005714 ctx.blk = NULL;
5715 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5716 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005717 return 0;
5718}
5719
5720__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5721{
5722 struct hlua_txn *htxn;
5723
5724 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5725 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5726
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005727 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005728 WILL_LJMP(lua_error(L));
5729
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005730 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005731}
5732
5733__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5734{
5735 struct hlua_txn *htxn;
5736
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005737 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005738 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5739
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005740 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005741 WILL_LJMP(lua_error(L));
5742
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005743 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005744}
5745
5746/* This function adds an header. It is a wrapper used by
5747 * the 2 following functions.
5748 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005749__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005750{
5751 size_t name_len;
5752 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5753 size_t value_len;
5754 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005755 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005756
Christopher Fauleta2097962019-07-15 16:25:33 +02005757 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5758 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005759 return 0;
5760}
5761
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005762__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5763{
5764 struct hlua_txn *htxn;
5765
5766 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5767 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5768
5769 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5770 WILL_LJMP(lua_error(L));
5771
5772 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5773}
5774
5775__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5776{
5777 struct hlua_txn *htxn;
5778
5779 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5780 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5781
5782 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5783 WILL_LJMP(lua_error(L));
5784
5785 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5786}
5787
5788static int hlua_http_req_set_hdr(lua_State *L)
5789{
5790 struct hlua_txn *htxn;
5791
5792 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5793 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5794
5795 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5796 WILL_LJMP(lua_error(L));
5797
5798 hlua_http_del_hdr(L, &htxn->s->txn->req);
5799 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5800}
5801
5802static int hlua_http_res_set_hdr(lua_State *L)
5803{
5804 struct hlua_txn *htxn;
5805
5806 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5807 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5808
5809 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5810 WILL_LJMP(lua_error(L));
5811
5812 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5813 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5814}
5815
5816/* This function set the method. */
5817static int hlua_http_req_set_meth(lua_State *L)
5818{
5819 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5820 size_t name_len;
5821 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5822
5823 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5824 WILL_LJMP(lua_error(L));
5825
5826 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5827 return 1;
5828}
5829
5830/* This function set the method. */
5831static int hlua_http_req_set_path(lua_State *L)
5832{
5833 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5834 size_t name_len;
5835 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5836
5837 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5838 WILL_LJMP(lua_error(L));
5839
5840 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5841 return 1;
5842}
5843
5844/* This function set the query-string. */
5845static int hlua_http_req_set_query(lua_State *L)
5846{
5847 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5848 size_t name_len;
5849 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5850
5851 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5852 WILL_LJMP(lua_error(L));
5853
5854 /* Check length. */
5855 if (name_len > trash.size - 1) {
5856 lua_pushboolean(L, 0);
5857 return 1;
5858 }
5859
5860 /* Add the mark question as prefix. */
5861 chunk_reset(&trash);
5862 trash.area[trash.data++] = '?';
5863 memcpy(trash.area + trash.data, name, name_len);
5864 trash.data += name_len;
5865
5866 lua_pushboolean(L,
5867 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5868 return 1;
5869}
5870
5871/* This function set the uri. */
5872static int hlua_http_req_set_uri(lua_State *L)
5873{
5874 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5875 size_t name_len;
5876 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5877
5878 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5879 WILL_LJMP(lua_error(L));
5880
5881 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5882 return 1;
5883}
5884
5885/* This function set the response code & optionally reason. */
5886static int hlua_http_res_set_status(lua_State *L)
5887{
5888 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5889 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5890 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5891 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5892
5893 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5894 WILL_LJMP(lua_error(L));
5895
5896 http_res_set_status(code, reason, htxn->s);
5897 return 0;
5898}
5899
5900/*
5901 *
5902 *
5903 * Class HTTPMessage
5904 *
5905 *
5906 */
5907
5908/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5909 * otherwise it throws an error.
5910 */
5911__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5912{
5913 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5914}
5915
5916/* Creates and pushes on the stack a HTTP object according with a current TXN.
5917 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005918static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005919{
5920 /* Check stack size. */
5921 if (!lua_checkstack(L, 3))
5922 return 0;
5923
5924 lua_newtable(L);
5925 lua_pushlightuserdata(L, msg);
5926 lua_rawseti(L, -2, 0);
5927
5928 /* Create the "channel" field that contains the request channel object. */
5929 lua_pushstring(L, "channel");
5930 if (!hlua_channel_new(L, msg->chn))
5931 return 0;
5932 lua_rawset(L, -3);
5933
5934 /* Pop a class stream metatable and affect it to the table. */
5935 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5936 lua_setmetatable(L, -2);
5937
5938 return 1;
5939}
5940
5941/* Helper function returning a filter attached to the HTTP message at the
5942 * position <ud> in the stack, filling the current offset and length of the
5943 * filter. If no filter is attached, NULL is returned and <offet> and <len> are
5944 * filled with output and input length respectively.
5945 */
5946static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5947{
5948 struct channel *chn = msg->chn;
5949 struct htx *htx = htxbuf(&chn->buf);
5950 struct filter *filter = NULL;
5951
5952 *offset = co_data(msg->chn);
5953 *len = htx->data - co_data(msg->chn);
5954
5955 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5956 filter = lua_touserdata (L, -1);
5957 if (msg->msg_state >= HTTP_MSG_DATA) {
5958 struct hlua_flt_ctx *flt_ctx = filter->ctx;
5959
5960 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
5961 *len = flt_ctx->cur_len[CHN_IDX(chn)];
5962 }
5963 }
5964
5965 lua_pop(L, 1);
5966 return filter;
5967}
5968
5969/* Returns true if the channel attached to the HTTP message is the response
5970 * channel.
5971 */
5972__LJMP static int hlua_http_msg_is_resp(lua_State *L)
5973{
5974 struct http_msg *msg;
5975
5976 MAY_LJMP(check_args(L, 1, "is_resp"));
5977 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
5978
5979 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
5980 return 1;
5981}
5982
5983/* Returns an array containing the elements status-line of the HTTP message. It relies
5984 * on hlua_http_get_stline().
5985 */
5986__LJMP static int hlua_http_msg_get_stline(lua_State *L)
5987{
5988 struct http_msg *msg;
5989 struct htx *htx;
5990 struct htx_sl *sl;
5991
5992 MAY_LJMP(check_args(L, 1, "get_stline"));
5993 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
5994
5995 if (msg->msg_state > HTTP_MSG_BODY)
5996 WILL_LJMP(lua_error(L));
5997
5998 htx = htxbuf(&msg->chn->buf);
5999 sl = http_get_stline(htx);
6000 if (!sl)
6001 return 0;
6002 return hlua_http_get_stline(L, sl);
6003}
6004
6005/* Returns an array containing all headers of the HTTP message. it relies on
6006 * hlua_http_get_headers().
6007 */
6008__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6009{
6010 struct http_msg *msg;
6011
6012 MAY_LJMP(check_args(L, 1, "get_headers"));
6013 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6014
6015 if (msg->msg_state > HTTP_MSG_BODY)
6016 WILL_LJMP(lua_error(L));
6017
6018 return hlua_http_get_headers(L, msg);
6019}
6020
6021/* Deletes all occurrences of an header in the HTTP message matching on its
6022 * name. It relies on hlua_http_del_hdr().
6023 */
6024__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6025{
6026 struct http_msg *msg;
6027
6028 MAY_LJMP(check_args(L, 2, "del_header"));
6029 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6030
6031 if (msg->msg_state > HTTP_MSG_BODY)
6032 WILL_LJMP(lua_error(L));
6033
6034 return hlua_http_del_hdr(L, msg);
6035}
6036
6037/* Matches the full value line of all occurences of an header in the HTTP
6038 * message given its name against a regex and replaces it if it matches. It
6039 * relies on hlua_http_rep_hdr().
6040 */
6041__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6042{
6043 struct http_msg *msg;
6044
6045 MAY_LJMP(check_args(L, 4, "rep_header"));
6046 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6047
6048 if (msg->msg_state > HTTP_MSG_BODY)
6049 WILL_LJMP(lua_error(L));
6050
6051 return hlua_http_rep_hdr(L, msg, 1);
6052}
6053
6054/* Matches all comma-separated values of all occurences of an header in the HTTP
6055 * message given its name against a regex and replaces it if it matches. It
6056 * relies on hlua_http_rep_hdr().
6057 */
6058__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6059{
6060 struct http_msg *msg;
6061
6062 MAY_LJMP(check_args(L, 4, "rep_value"));
6063 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6064
6065 if (msg->msg_state > HTTP_MSG_BODY)
6066 WILL_LJMP(lua_error(L));
6067
6068 return hlua_http_rep_hdr(L, msg, 0);
6069}
6070
6071/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6072__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6073{
6074 struct http_msg *msg;
6075
6076 MAY_LJMP(check_args(L, 3, "add_header"));
6077 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6078
6079 if (msg->msg_state > HTTP_MSG_BODY)
6080 WILL_LJMP(lua_error(L));
6081
6082 return hlua_http_add_hdr(L, msg);
6083}
6084
6085/* Add an header in the HTTP message removing existing headers with the same
6086 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6087 */
6088__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6089{
6090 struct http_msg *msg;
6091
6092 MAY_LJMP(check_args(L, 3, "set_header"));
6093 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6094
6095 if (msg->msg_state > HTTP_MSG_BODY)
6096 WILL_LJMP(lua_error(L));
6097
6098 hlua_http_del_hdr(L, msg);
6099 return hlua_http_add_hdr(L, msg);
6100}
6101
6102/* Rewrites the request method. It relies on http_req_replace_stline(). */
6103__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6104{
6105 struct stream *s;
6106 struct http_msg *msg;
6107 const char *name;
6108 size_t name_len;
6109
6110 MAY_LJMP(check_args(L, 2, "set_method"));
6111 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6112 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6113
6114 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6115 WILL_LJMP(lua_error(L));
6116
6117 s = chn_strm(msg->chn);
6118 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6119 return 1;
6120}
6121
6122/* Rewrites the request path. It relies on http_req_replace_stline(). */
6123__LJMP static int hlua_http_msg_set_path(lua_State *L)
6124{
6125 struct stream *s;
6126 struct http_msg *msg;
6127 const char *name;
6128 size_t name_len;
6129
6130 MAY_LJMP(check_args(L, 2, "set_path"));
6131 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6132 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6133
6134 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6135 WILL_LJMP(lua_error(L));
6136
6137 s = chn_strm(msg->chn);
6138 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6139 return 1;
6140}
6141
6142/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6143__LJMP static int hlua_http_msg_set_query(lua_State *L)
6144{
6145 struct stream *s;
6146 struct http_msg *msg;
6147 const char *name;
6148 size_t name_len;
6149
6150 MAY_LJMP(check_args(L, 2, "set_query"));
6151 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6152 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6153
6154 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6155 WILL_LJMP(lua_error(L));
6156
6157 /* Check length. */
6158 if (name_len > trash.size - 1) {
6159 lua_pushboolean(L, 0);
6160 return 1;
6161 }
6162
6163 /* Add the mark question as prefix. */
6164 chunk_reset(&trash);
6165 trash.area[trash.data++] = '?';
6166 memcpy(trash.area + trash.data, name, name_len);
6167 trash.data += name_len;
6168
6169 s = chn_strm(msg->chn);
6170 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6171 return 1;
6172}
6173
6174/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6175__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6176{
6177 struct stream *s;
6178 struct http_msg *msg;
6179 const char *name;
6180 size_t name_len;
6181
6182 MAY_LJMP(check_args(L, 2, "set_uri"));
6183 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6184 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6185
6186 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6187 WILL_LJMP(lua_error(L));
6188
6189 s = chn_strm(msg->chn);
6190 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6191 return 1;
6192}
6193
6194/* Rewrites the response status code. It relies on http_res_set_status(). */
6195__LJMP static int hlua_http_msg_set_status(lua_State *L)
6196{
6197 struct http_msg *msg;
6198 unsigned int code;
6199 const char *reason;
6200 size_t reason_len;
6201
6202 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6203 code = MAY_LJMP(luaL_checkinteger(L, 2));
6204 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6205
6206 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6207 WILL_LJMP(lua_error(L));
6208
6209 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6210 return 1;
6211}
6212
6213/* Returns true if the HTTP message is full. */
6214__LJMP static int hlua_http_msg_is_full(lua_State *L)
6215{
6216 struct http_msg *msg;
6217
6218 MAY_LJMP(check_args(L, 1, "is_full"));
6219 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6220 lua_pushboolean(L, channel_full(msg->chn, 0));
6221 return 1;
6222}
6223
6224/* Returns true if the HTTP message may still receive data. */
6225__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6226{
6227 struct http_msg *msg;
6228 struct htx *htx;
6229
6230 MAY_LJMP(check_args(L, 1, "may_recv"));
6231 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6232 htx = htxbuf(&msg->chn->buf);
6233 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6234 return 1;
6235}
6236
6237/* Returns true if the HTTP message EOM was received */
6238__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6239{
6240 struct http_msg *msg;
6241 struct htx *htx;
6242
6243 MAY_LJMP(check_args(L, 1, "may_recv"));
6244 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6245 htx = htxbuf(&msg->chn->buf);
6246 lua_pushboolean(L, !htx_expect_more(htx));
6247 return 1;
6248}
6249
6250/* Returns the number of bytes available in the input side of the HTTP
6251 * message. This function never fails.
6252 */
6253__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6254{
6255 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006256 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006257
6258 MAY_LJMP(check_args(L, 1, "input"));
6259 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006260 hlua_http_msg_filter(L, 1, msg, &output, &input);
6261 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006262 return 1;
6263}
6264
6265/* Returns the number of bytes available in the output side of the HTTP
6266 * message. This function never fails.
6267 */
6268__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6269{
6270 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006271 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006272
6273 MAY_LJMP(check_args(L, 1, "output"));
6274 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006275 hlua_http_msg_filter(L, 1, msg, &output, &input);
6276 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006277 return 1;
6278}
6279
6280/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6281 * starting at the offset <offset> and put it in a string LUA variables. It
6282 * returns the length of the builded string. It stops on the first non-DATA HTX
6283 * block. This function is called during the payload filtering, so the headers
6284 * are already scheduled for output (from the filter point of view).
6285 */
6286static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6287{
6288 struct htx *htx = htxbuf(&msg->chn->buf);
6289 struct htx_blk *blk;
6290 struct htx_ret htxret;
6291 luaL_Buffer b;
6292 int ret = 0;
6293
6294 luaL_buffinit(L, &b);
6295 htxret = htx_find_offset(htx, offset);
6296 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6297 enum htx_blk_type type = htx_get_blk_type(blk);
6298 struct ist v;
6299
6300 switch (type) {
6301 case HTX_BLK_UNUSED:
6302 break;
6303
6304 case HTX_BLK_DATA:
6305 v = htx_get_blk_value(htx, blk);
6306 v.ptr += offset;
6307 v.len -= offset;
6308 if (v.len > len)
6309 v.len = len;
6310
6311 luaL_addlstring(&b, v.ptr, v.len);
6312 ret += v.len;
6313 break;
6314
6315 default:
6316 if (!ret) {
6317 /* Remove the empty string and push nil on the stack */
6318 lua_pop(L, 1);
6319 lua_pushnil(L);
6320 }
6321 goto end;
6322 }
6323 offset = 0;
6324 }
6325
6326 luaL_pushresult(&b);
6327
6328end:
6329 return ret;
6330}
6331
6332/* Copies the string <str> to the HTTP message <msg> at the offset
6333 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
6334 * returns the amount of data written. This function is responsibile to update
6335 * the filter context.
6336 */
6337static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6338{
6339 struct htx *htx = htx_from_buf(&msg->chn->buf);
6340 struct htx_ret htxret;
6341 int /*max, */ret = 0;
6342
6343 /* Nothing to do, just return */
6344 if (unlikely(istlen(str) == 0))
6345 goto end;
6346
6347 if (istlen(str) > htx_free_data_space(htx)) {
6348 ret = -1;
6349 goto end;
6350 }
6351
6352 htxret = htx_find_offset(htx, offset);
6353 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6354 if (!htx_add_last_data(htx, str))
6355 goto end;
6356 }
6357 else {
6358 struct ist v = htx_get_blk_value(htx, htxret.blk);
6359 v.ptr += htxret.ret;
6360 v.len = 0;
6361 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6362 goto end;
6363 }
6364 ret = str.len;
6365 if (ret) {
6366 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6367 flt_update_offsets(filter, msg->chn, ret);
6368 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6369 }
6370
6371 end:
6372 htx_to_buf(htx, &msg->chn->buf);
6373 return ret;
6374}
6375
6376/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6377 * position <offset>. It stops on the first non-DATA HTX block. This function is
6378 * called during the payload filtering, so the headers are already scheduled for
6379 * output (from the filter point of view). This function is responsibile to
6380 * update the filter context.
6381 */
6382static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6383{
6384 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6385 struct htx *htx = htx_from_buf(&msg->chn->buf);
6386 struct htx_blk *blk;
6387 struct htx_ret htxret;
6388 size_t ret = 0;
6389
6390 /* Be sure <len> is always the amount of DATA to remove */
6391 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6392 htx_truncate(htx, offset);
6393 ret = len;
6394 goto end;
6395 }
6396
6397 htxret = htx_find_offset(htx, offset);
6398 blk = htxret.blk;
6399 if (htxret.ret) {
6400 struct ist v;
6401
6402 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6403 goto end;
6404 v = htx_get_blk_value(htx, blk);
6405 v.ptr += htxret.ret;
6406 if (v.len > len)
6407 v.len = len;
6408 blk = htx_replace_blk_value(htx, blk, v, ist2(NULL, 0));
6409 len -= v.len;
6410 ret += v.len;
6411 }
6412
6413
6414 while (blk && len) {
6415 enum htx_blk_type type = htx_get_blk_type(blk);
6416 uint32_t sz = htx_get_blksz(blk);
6417
6418 switch (type) {
6419 case HTX_BLK_UNUSED:
6420 break;
6421
6422 case HTX_BLK_DATA:
6423 if (len < sz) {
6424 htx_cut_data_blk(htx, blk, len);
6425 ret += len;
6426 goto end;
6427 }
6428 break;
6429
6430 default:
6431 goto end;
6432 }
6433
6434 /* Remove oll the data block */
6435 len -= sz;
6436 ret += sz;
6437 blk = htx_remove_blk(htx, blk);
6438 }
6439
6440end:
6441 flt_update_offsets(filter, msg->chn, -ret);
6442 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6443 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6444 * to loose the EOM flag if the message is empty.
6445 */
6446}
6447
6448/* Copies input data found in an HTTP message. Unlike the channel function used
6449 * to duplicate raw data, this one can only be called inside a filter, from
6450 * http_payload callback. So it cannot yield. An exception is returned if it is
6451 * called from another callback. If nothing was copied, a nil value is pushed on
6452 * the stack.
6453 */
6454__LJMP static int hlua_http_msg_get_body(lua_State *L)
6455{
6456 struct http_msg *msg;
6457 struct filter *filter;
6458 size_t output, input;
6459 int offset, len;
6460
6461 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6462 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6463 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6464
6465 if (msg->msg_state < HTTP_MSG_DATA)
6466 WILL_LJMP(lua_error(L));
6467
6468 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6469 if (!filter || !hlua_filter_from_payload(filter))
6470 WILL_LJMP(lua_error(L));
6471
6472 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6473 lua_pushnil(L);
6474 return 1;
6475 }
6476
6477 offset = output;
6478 if (lua_gettop(L) > 1) {
6479 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6480 if (offset < 0)
6481 offset = MAX(0, input + offset);
6482 offset += output;
6483 if (offset < output || offset > input + output) {
6484 lua_pushfstring(L, "offset out of range.");
6485 WILL_LJMP(lua_error(L));
6486 }
6487 }
6488 len = output + input - offset;
6489 if (lua_gettop(L) == 3) {
6490 len = MAY_LJMP(luaL_checkinteger(L, 3));
6491 if (!len)
6492 goto dup;
6493 if (len == -1)
6494 len = global.tune.bufsize;
6495 if (len < 0) {
6496 lua_pushfstring(L, "length out of range.");
6497 WILL_LJMP(lua_error(L));
6498 }
6499 }
6500
6501 dup:
6502 _hlua_http_msg_dup(msg, L, offset, len);
6503 return 1;
6504}
6505
6506/* Appends a string to the HTTP message, after all existing DATA blocks but
6507 * before the trailers, if any. It returns the amount of data written or -1 if
6508 * nothing was copied. Unlike the channel function used to append data, this one
6509 * can only be called inside a filter, from http_payload callback. So it cannot
6510 * yield. An exception is returned if it is called from another callback.
6511 */
6512__LJMP static int hlua_http_msg_append(lua_State *L)
6513{
6514 struct http_msg *msg;
6515 struct filter *filter;
6516 const char *str;
6517 size_t offset, len, sz;
6518 int ret;
6519
6520 MAY_LJMP(check_args(L, 2, "append"));
6521 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6522
6523 if (msg->msg_state < HTTP_MSG_DATA)
6524 WILL_LJMP(lua_error(L));
6525
6526 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6527 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6528 if (!filter || !hlua_filter_from_payload(filter))
6529 WILL_LJMP(lua_error(L));
6530
6531 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6532 lua_pushinteger(L, ret);
6533 return 1;
6534}
6535
6536/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6537 * returns the amount of data written or -1 if nothing was copied. Unlike the
6538 * channel function used to prepend data, this one can only be called inside a
6539 * filter, from http_payload callback. So it cannot yield. An exception is
6540 * returned if it is called from another callback.
6541 */
6542__LJMP static int hlua_http_msg_prepend(lua_State *L)
6543{
6544 struct http_msg *msg;
6545 struct filter *filter;
6546 const char *str;
6547 size_t offset, len, sz;
6548 int ret;
6549
6550 MAY_LJMP(check_args(L, 2, "prepend"));
6551 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006552
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006553 if (msg->msg_state < HTTP_MSG_DATA)
6554 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006555
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006556 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6557 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6558 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006559 WILL_LJMP(lua_error(L));
6560
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006561 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6562 lua_pushinteger(L, ret);
6563 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006564}
6565
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006566/* Inserts a string to the HTTP message at a given offset. By default the string
6567 * is appended at the end of DATA blocks. It returns the amount of data written
6568 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6569 * this one can only be called inside a filter, from http_payload callback. So
6570 * it cannot yield. An exception is returned if it is called from another
6571 * callback.
6572 */
6573__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006574{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006575 struct http_msg *msg;
6576 struct filter *filter;
6577 const char *str;
6578 size_t input, output, sz;
6579 int offset;
6580 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006581
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006582 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6583 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6584 MAY_LJMP(check_args(L, 2, "insert"));
6585 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006586
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006587 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006588 WILL_LJMP(lua_error(L));
6589
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006590 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6591 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6592 if (!filter || !hlua_filter_from_payload(filter))
6593 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006594
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006595 offset = input + output;
6596 if (lua_gettop(L) > 2) {
6597 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6598 if (offset < 0)
6599 offset = MAX(0, input + offset);
6600 offset += output;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006601
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006602 if (offset < output || offset > output + input) {
6603 lua_pushfstring(L, "offset out of range.");
6604 WILL_LJMP(lua_error(L));
6605 }
6606 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006607
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006608 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6609 lua_pushinteger(L, ret);
6610 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006611}
6612
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006613/* Removes a given amount of data from the HTTP message at a given offset. By
6614 * default all DATA blocks are removed. It returns the amount of data
6615 * removed. Unlike the channel function used to remove data, this one can only
6616 * be called inside a filter, from http_payload callback. So it cannot yield. An
6617 * exception is returned if it is called from another callback.
6618 */
6619__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006620{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006621 struct http_msg *msg;
6622 struct filter *filter;
6623 size_t input, output;
6624 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006625
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006626 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6627 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6628 MAY_LJMP(check_args(L, 2, "insert"));
6629 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006630
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006631 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006632 WILL_LJMP(lua_error(L));
6633
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006634 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6635 if (!filter || !hlua_filter_from_payload(filter))
6636 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006637
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006638 offset = input + output;
6639 if (lua_gettop(L) > 2) {
6640 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6641 if (offset < 0)
6642 offset = MAX(0, input + offset);
6643 offset += output;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006644
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006645 if (offset < output || offset > output + input) {
6646 lua_pushfstring(L, "offset out of range.");
6647 WILL_LJMP(lua_error(L));
6648 }
6649 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006650
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006651 len = output + input - offset;
6652 if (lua_gettop(L) == 4) {
6653 len = MAY_LJMP(luaL_checkinteger(L, 4));
6654 if (!len)
6655 goto end;
6656 if (len == -1)
6657 len = output + input - offset;
6658 if (len < 0 || offset + len > output + input) {
6659 lua_pushfstring(L, "length out of range.");
6660 WILL_LJMP(lua_error(L));
6661 }
6662 }
6663
6664 _hlua_http_msg_delete(msg, filter, offset, len);
6665
6666 end:
6667 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006668 return 1;
6669}
6670
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006671/* Replaces a given amount of data at the given offet by a string. By default,
6672 * all remaining data are removed, accordingly to the filter context. It returns
6673 * the amount of data written or -1 if nothing was copied. Unlike the channel
6674 * function used to replace data, this one can only be called inside a filter,
6675 * from http_payload callback. So it cannot yield. An exception is returned if
6676 * it is called from another callback.
6677 */
6678__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006679{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006680 struct http_msg *msg;
6681 struct filter *filter;
6682 struct htx *htx;
6683 const char *str;
6684 size_t input, output, sz;
6685 int offset, len;
6686 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006687
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006688 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6689 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6690 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6691
6692 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006693 WILL_LJMP(lua_error(L));
6694
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006695 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6696 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6697 if (!filter || !hlua_filter_from_payload(filter))
6698 WILL_LJMP(lua_error(L));
6699
6700 offset = output;
6701 if (lua_gettop(L) > 2) {
6702 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6703 if (offset < 0)
6704 offset = MAX(0, input + offset);
6705 offset += output;
6706 if (offset < output || offset > input + output) {
6707 lua_pushfstring(L, "offset out of range.");
6708 WILL_LJMP(lua_error(L));
6709 }
6710 }
6711
6712 len = output + input - offset;
6713 if (lua_gettop(L) == 4) {
6714 len = MAY_LJMP(luaL_checkinteger(L, 4));
6715 if (!len)
6716 goto set;
6717 if (len == -1)
6718 len = output + input - offset;
6719 if (len < 0 || offset + len > output + input) {
6720 lua_pushfstring(L, "length out of range.");
6721 WILL_LJMP(lua_error(L));
6722 }
6723 }
6724
6725 set:
6726 /* Be sure we can copied the string once input data will be removed. */
6727 htx = htx_from_buf(&msg->chn->buf);
6728 if (sz > htx_free_data_space(htx) + len)
6729 lua_pushinteger(L, -1);
6730 else {
6731 _hlua_http_msg_delete(msg, filter, offset, len);
6732 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6733 lua_pushinteger(L, ret);
6734 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006735 return 1;
6736}
6737
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006738/* Prepends data into an HTTP message and forward it, from the filter point of
6739 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6740 * the channel function used to send data, this one can only be called inside a
6741 * filter, from http_payload callback. So it cannot yield. An exception is
6742 * returned if it is called from another callback.
6743 */
6744__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006745{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 struct http_msg *msg;
6747 struct filter *filter;
6748 struct htx *htx;
6749 const char *str;
6750 size_t offset, len, sz;
6751 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006752
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006753 MAY_LJMP(check_args(L, 2, "send"));
6754 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6755
6756 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006757 WILL_LJMP(lua_error(L));
6758
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006759 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6760 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6761 if (!filter || !hlua_filter_from_payload(filter))
6762 WILL_LJMP(lua_error(L));
6763
6764 /* Return an error if the channel's output is closed */
6765 if (unlikely(channel_output_closed(msg->chn))) {
6766 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006767 return 1;
6768 }
6769
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006770 htx = htx_from_buf(&msg->chn->buf);
6771 if (sz > htx_free_data_space(htx)) {
6772 lua_pushinteger(L, -1);
6773 return 1;
6774 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006775
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006776 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6777 if (ret > 0) {
6778 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6779
6780 FLT_OFF(filter, msg->chn) += ret;
6781 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6782 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6783 }
6784
6785 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006786 return 1;
6787}
6788
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006789/* Forwards a given amount of bytes. It return -1 if the channel's output is
6790 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6791 * channel function used to forward data, this one can only be called inside a
6792 * filter, from http_payload callback. So it cannot yield. An exception is
6793 * returned if it is called from another callback. All other functions deal with
6794 * DATA block, this one not.
6795*/
6796__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006797{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006798 struct http_msg *msg;
6799 struct filter *filter;
6800 size_t offset, len;
6801 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006802
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006803 MAY_LJMP(check_args(L, 2, "forward"));
6804 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6805
6806 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006807 WILL_LJMP(lua_error(L));
6808
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6810 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6811 if (!filter || !hlua_filter_from_payload(filter))
6812 WILL_LJMP(lua_error(L));
6813
6814 /* Nothing to do, just return */
6815 if (!fwd)
6816 goto end;
6817
6818 /* Return an error if the channel's output is closed */
6819 if (unlikely(channel_output_closed(msg->chn))) {
6820 ret = -1;
6821 goto end;
6822 }
6823
6824 ret = fwd;
6825 if (ret > len)
6826 ret = len;
6827
6828 if (ret) {
6829 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6830
6831 FLT_OFF(filter, msg->chn) += ret;
6832 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6833 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6834 }
6835
6836 end:
6837 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006838 return 1;
6839}
6840
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006841/* Set EOM flag on the HTX message.
6842 *
6843 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6844 * really know how to do without this feature.
6845 */
6846__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006847{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006848 struct http_msg *msg;
6849 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006850
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006851 MAY_LJMP(check_args(L, 1, "set_eom"));
6852 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6853 htx = htxbuf(&msg->chn->buf);
6854 htx->flags |= HTX_FL_EOM;
6855 return 0;
6856}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006857
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006858/* Unset EOM flag on the HTX message.
6859 *
6860 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6861 * really know how to do without this feature.
6862 */
6863__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6864{
6865 struct http_msg *msg;
6866 struct htx *htx;
6867
6868 MAY_LJMP(check_args(L, 1, "set_eom"));
6869 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6870 htx = htxbuf(&msg->chn->buf);
6871 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006872 return 0;
6873}
6874
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006875/*
6876 *
6877 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006878 * Class TXN
6879 *
6880 *
6881 */
6882
6883/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02006884 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006885 */
6886__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
6887{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006888 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006889}
6890
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006891__LJMP static int hlua_set_var(lua_State *L)
6892{
6893 struct hlua_txn *htxn;
6894 const char *name;
6895 size_t len;
6896 struct sample smp;
6897
Tim Duesterhus4e172c92020-05-19 13:49:42 +02006898 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6899 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006900
6901 /* It is useles to retrieve the stream, but this function
6902 * runs only in a stream context.
6903 */
6904 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6905 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6906
6907 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01006908 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006909 hlua_lua2smp(L, 3, &smp);
6910
6911 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01006912 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02006913
6914 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
6915 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
6916 else
6917 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
6918
Tim Duesterhus84ebc132020-05-19 13:49:41 +02006919 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006920}
6921
Christopher Faulet85d79c92016-11-09 16:54:56 +01006922__LJMP static int hlua_unset_var(lua_State *L)
6923{
6924 struct hlua_txn *htxn;
6925 const char *name;
6926 size_t len;
6927 struct sample smp;
6928
6929 MAY_LJMP(check_args(L, 2, "unset_var"));
6930
6931 /* It is useles to retrieve the stream, but this function
6932 * runs only in a stream context.
6933 */
6934 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6935 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6936
6937 /* Unset the variable. */
6938 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02006939 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
6940 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01006941}
6942
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006943__LJMP static int hlua_get_var(lua_State *L)
6944{
6945 struct hlua_txn *htxn;
6946 const char *name;
6947 size_t len;
6948 struct sample smp;
6949
6950 MAY_LJMP(check_args(L, 2, "get_var"));
6951
6952 /* It is useles to retrieve the stream, but this function
6953 * runs only in a stream context.
6954 */
6955 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6956 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6957
Willy Tarreau7560dd42016-03-10 16:28:58 +01006958 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01006959 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006960 lua_pushnil(L);
6961 return 1;
6962 }
6963
6964 return hlua_smp2lua(L, &smp);
6965}
6966
Willy Tarreau59551662015-03-10 14:23:13 +01006967__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006968{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006969 struct hlua *hlua;
6970
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006971 MAY_LJMP(check_args(L, 2, "set_priv"));
6972
Willy Tarreau87b09662015-04-03 00:22:06 +02006973 /* It is useles to retrieve the stream, but this function
6974 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006975 */
6976 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006977
6978 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006979 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006980 if (!hlua)
6981 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006982
6983 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02006984 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006985
6986 /* Get and store new value. */
6987 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
6988 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
6989
6990 return 0;
6991}
6992
Willy Tarreau59551662015-03-10 14:23:13 +01006993__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006994{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006995 struct hlua *hlua;
6996
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006997 MAY_LJMP(check_args(L, 1, "get_priv"));
6998
Willy Tarreau87b09662015-04-03 00:22:06 +02006999 /* It is useles to retrieve the stream, but this function
7000 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007001 */
7002 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007003
7004 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007005 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007006 if (!hlua) {
7007 lua_pushnil(L);
7008 return 1;
7009 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007010
7011 /* Push configuration index in the stack. */
7012 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7013
7014 return 1;
7015}
7016
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007017/* Create stack entry containing a class TXN. This function
7018 * return 0 if the stack does not contains free slots,
7019 * otherwise it returns 1.
7020 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007021static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007022{
Willy Tarreaude491382015-04-06 11:04:28 +02007023 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007024
7025 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007026 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007027 return 0;
7028
7029 /* NOTE: The allocation never fails. The failure
7030 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007031 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007032 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007033 /* Create the object: obj[0] = userdata. */
7034 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007035 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007036 lua_rawseti(L, -2, 0);
7037
Willy Tarreaude491382015-04-06 11:04:28 +02007038 htxn->s = s;
7039 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007040 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007041 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007042
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007043 /* Create the "f" field that contains a list of fetches. */
7044 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007045 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007046 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007047 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007048
7049 /* Create the "sf" field that contains a list of stringsafe fetches. */
7050 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007051 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007052 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007053 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007054
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007055 /* Create the "c" field that contains a list of converters. */
7056 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007057 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007058 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007059 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007060
7061 /* Create the "sc" field that contains a list of stringsafe converters. */
7062 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007063 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007064 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007065 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007066
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007067 /* Create the "req" field that contains the request channel object. */
7068 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007069 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007070 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007071 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007072
7073 /* Create the "res" field that contains the response channel object. */
7074 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007075 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007076 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007077 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007078
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007079 /* Creates the HTTP object is the current proxy allows http. */
7080 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007081 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007082 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007083 return 0;
7084 }
7085 else
7086 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007087 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007088
Christopher Faulet78c35472020-02-26 17:14:08 +01007089 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7090 /* HTTPMessage object are created when a lua TXN is created from
7091 * a filter context only
7092 */
7093
7094 /* Creates the HTTP-Request object is the current proxy allows http. */
7095 lua_pushstring(L, "http_req");
7096 if (p->mode == PR_MODE_HTTP) {
7097 if (!hlua_http_msg_new(L, &s->txn->req))
7098 return 0;
7099 }
7100 else
7101 lua_pushnil(L);
7102 lua_rawset(L, -3);
7103
7104 /* Creates the HTTP-Response object is the current proxy allows http. */
7105 lua_pushstring(L, "http_res");
7106 if (p->mode == PR_MODE_HTTP) {
7107 if (!hlua_http_msg_new(L, &s->txn->rsp))
7108 return 0;
7109 }
7110 else
7111 lua_pushnil(L);
7112 lua_rawset(L, -3);
7113 }
7114
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007115 /* Pop a class sesison metatable and affect it to the userdata. */
7116 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7117 lua_setmetatable(L, -2);
7118
7119 return 1;
7120}
7121
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007122__LJMP static int hlua_txn_deflog(lua_State *L)
7123{
7124 const char *msg;
7125 struct hlua_txn *htxn;
7126
7127 MAY_LJMP(check_args(L, 2, "deflog"));
7128 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7129 msg = MAY_LJMP(luaL_checkstring(L, 2));
7130
7131 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7132 return 0;
7133}
7134
7135__LJMP static int hlua_txn_log(lua_State *L)
7136{
7137 int level;
7138 const char *msg;
7139 struct hlua_txn *htxn;
7140
7141 MAY_LJMP(check_args(L, 3, "log"));
7142 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7143 level = MAY_LJMP(luaL_checkinteger(L, 2));
7144 msg = MAY_LJMP(luaL_checkstring(L, 3));
7145
7146 if (level < 0 || level >= NB_LOG_LEVELS)
7147 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7148
7149 hlua_sendlog(htxn->s->be, level, msg);
7150 return 0;
7151}
7152
7153__LJMP static int hlua_txn_log_debug(lua_State *L)
7154{
7155 const char *msg;
7156 struct hlua_txn *htxn;
7157
7158 MAY_LJMP(check_args(L, 2, "Debug"));
7159 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7160 msg = MAY_LJMP(luaL_checkstring(L, 2));
7161 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7162 return 0;
7163}
7164
7165__LJMP static int hlua_txn_log_info(lua_State *L)
7166{
7167 const char *msg;
7168 struct hlua_txn *htxn;
7169
7170 MAY_LJMP(check_args(L, 2, "Info"));
7171 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7172 msg = MAY_LJMP(luaL_checkstring(L, 2));
7173 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7174 return 0;
7175}
7176
7177__LJMP static int hlua_txn_log_warning(lua_State *L)
7178{
7179 const char *msg;
7180 struct hlua_txn *htxn;
7181
7182 MAY_LJMP(check_args(L, 2, "Warning"));
7183 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7184 msg = MAY_LJMP(luaL_checkstring(L, 2));
7185 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7186 return 0;
7187}
7188
7189__LJMP static int hlua_txn_log_alert(lua_State *L)
7190{
7191 const char *msg;
7192 struct hlua_txn *htxn;
7193
7194 MAY_LJMP(check_args(L, 2, "Alert"));
7195 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7196 msg = MAY_LJMP(luaL_checkstring(L, 2));
7197 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7198 return 0;
7199}
7200
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007201__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7202{
7203 struct hlua_txn *htxn;
7204 int ll;
7205
7206 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7207 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7208 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7209
7210 if (ll < 0 || ll > 7)
7211 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7212
7213 htxn->s->logs.level = ll;
7214 return 0;
7215}
7216
7217__LJMP static int hlua_txn_set_tos(lua_State *L)
7218{
7219 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007220 int tos;
7221
7222 MAY_LJMP(check_args(L, 2, "set_tos"));
7223 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7224 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7225
Willy Tarreau1a18b542018-12-11 16:37:42 +01007226 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007227 return 0;
7228}
7229
7230__LJMP static int hlua_txn_set_mark(lua_State *L)
7231{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007232 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007233 int mark;
7234
7235 MAY_LJMP(check_args(L, 2, "set_mark"));
7236 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7237 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7238
Lukas Tribus579e3e32019-08-11 18:03:45 +02007239 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007240 return 0;
7241}
7242
Patrick Hemmer268a7072018-05-11 12:52:31 -04007243__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7244{
7245 struct hlua_txn *htxn;
7246
7247 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7248 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7249 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7250 return 0;
7251}
7252
7253__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7254{
7255 struct hlua_txn *htxn;
7256
7257 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7258 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7259 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7260 return 0;
7261}
7262
Christopher Faulet700d9e82020-01-31 12:21:52 +01007263/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007264 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007265 * message and terminate the transaction. It returns 1 on success and 0 on
7266 * error. The Reply must be on top of the stack.
7267 */
7268__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7269{
7270 struct htx *htx;
7271 struct htx_sl *sl;
7272 struct h1m h1m;
7273 const char *status, *reason, *body;
7274 size_t status_len, reason_len, body_len;
7275 int ret, code, flags;
7276
7277 code = 200;
7278 status = "200";
7279 status_len = 3;
7280 ret = lua_getfield(L, -1, "status");
7281 if (ret == LUA_TNUMBER) {
7282 code = lua_tointeger(L, -1);
7283 status = lua_tolstring(L, -1, &status_len);
7284 }
7285 lua_pop(L, 1);
7286
7287 reason = http_get_reason(code);
7288 reason_len = strlen(reason);
7289 ret = lua_getfield(L, -1, "reason");
7290 if (ret == LUA_TSTRING)
7291 reason = lua_tolstring(L, -1, &reason_len);
7292 lua_pop(L, 1);
7293
7294 body = NULL;
7295 body_len = 0;
7296 ret = lua_getfield(L, -1, "body");
7297 if (ret == LUA_TSTRING)
7298 body = lua_tolstring(L, -1, &body_len);
7299 lua_pop(L, 1);
7300
7301 /* Prepare the response before inserting the headers */
7302 h1m_init_res(&h1m);
7303 htx = htx_from_buf(&s->res.buf);
7304 channel_htx_truncate(&s->res, htx);
7305 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7306 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7307 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7308 ist2(status, status_len), ist2(reason, reason_len));
7309 }
7310 else {
7311 flags = HTX_SL_F_IS_RESP;
7312 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7313 ist2(status, status_len), ist2(reason, reason_len));
7314 }
7315 if (!sl)
7316 goto fail;
7317 sl->info.res.status = code;
7318
7319 /* Push in the stack the "headers" entry. */
7320 ret = lua_getfield(L, -1, "headers");
7321 if (ret != LUA_TTABLE)
7322 goto skip_headers;
7323
7324 lua_pushnil(L);
7325 while (lua_next(L, -2) != 0) {
7326 struct ist name, value;
7327 const char *n, *v;
7328 size_t nlen, vlen;
7329
7330 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7331 /* Skip element if the key is not a string or if the value is not a table */
7332 goto next_hdr;
7333 }
7334
7335 n = lua_tolstring(L, -2, &nlen);
7336 name = ist2(n, nlen);
7337 if (isteqi(name, ist("content-length"))) {
7338 /* Always skip content-length header. It will be added
7339 * later with the correct len
7340 */
7341 goto next_hdr;
7342 }
7343
7344 /* Loop on header's values */
7345 lua_pushnil(L);
7346 while (lua_next(L, -2)) {
7347 if (!lua_isstring(L, -1)) {
7348 /* Skip the value if it is not a string */
7349 goto next_value;
7350 }
7351
7352 v = lua_tolstring(L, -1, &vlen);
7353 value = ist2(v, vlen);
7354
7355 if (isteqi(name, ist("transfer-encoding")))
7356 h1_parse_xfer_enc_header(&h1m, value);
7357 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7358 goto fail;
7359
7360 next_value:
7361 lua_pop(L, 1);
7362 }
7363
7364 next_hdr:
7365 lua_pop(L, 1);
7366 }
7367 skip_headers:
7368 lua_pop(L, 1);
7369
7370 /* Update h1m flags: CLEN is set if CHNK is not present */
7371 if (!(h1m.flags & H1_MF_CHNK)) {
7372 const char *clen = ultoa(body_len);
7373
7374 h1m.flags |= H1_MF_CLEN;
7375 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7376 goto fail;
7377 }
7378 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7379 h1m.flags |= H1_MF_XFER_LEN;
7380
7381 /* Update HTX start-line flags */
7382 if (h1m.flags & H1_MF_XFER_ENC)
7383 flags |= HTX_SL_F_XFER_ENC;
7384 if (h1m.flags & H1_MF_XFER_LEN) {
7385 flags |= HTX_SL_F_XFER_LEN;
7386 if (h1m.flags & H1_MF_CHNK)
7387 flags |= HTX_SL_F_CHNK;
7388 else if (h1m.flags & H1_MF_CLEN)
7389 flags |= HTX_SL_F_CLEN;
7390 if (h1m.body_len == 0)
7391 flags |= HTX_SL_F_BODYLESS;
7392 }
7393 sl->flags |= flags;
7394
7395
7396 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007397 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007398 goto fail;
7399
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007400 htx->flags |= HTX_FL_EOM;
7401
Christopher Faulet700d9e82020-01-31 12:21:52 +01007402 /* Now, forward the response and terminate the transaction */
7403 s->txn->status = code;
7404 htx_to_buf(htx, &s->res.buf);
7405 if (!http_forward_proxy_resp(s, 1))
7406 goto fail;
7407
7408 return 1;
7409
7410 fail:
7411 channel_htx_truncate(&s->res, htx);
7412 return 0;
7413}
7414
7415/* Terminate a transaction if called from a lua action. For TCP streams,
7416 * processing is just aborted. Nothing is returned to the client and all
7417 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7418 * is forwarded to the client before terminating the transaction. On success,
7419 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7420 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7421 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007422 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007423__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007424{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007425 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007426 struct stream *s;
7427 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007428
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007429 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007430
Christopher Faulet700d9e82020-01-31 12:21:52 +01007431 /* If the flags NOTERM is set, we cannot terminate the session, so we
7432 * just end the execution of the current lua code. */
7433 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007434 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007435
Christopher Faulet700d9e82020-01-31 12:21:52 +01007436 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007437 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007438 struct channel *req = &s->req;
7439 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007440
Christopher Faulet700d9e82020-01-31 12:21:52 +01007441 channel_auto_read(req);
7442 channel_abort(req);
7443 channel_auto_close(req);
7444 channel_erase(req);
7445
7446 res->wex = tick_add_ifset(now_ms, res->wto);
7447 channel_auto_read(res);
7448 channel_auto_close(res);
7449 channel_shutr_now(res);
7450
7451 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7452 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007453 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007454
Christopher Faulet700d9e82020-01-31 12:21:52 +01007455 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7456 /* No reply or invalid reply */
7457 s->txn->status = 0;
7458 http_reply_and_close(s, 0, NULL);
7459 }
7460 else {
7461 /* Remove extra args to have the reply on top of the stack */
7462 if (lua_gettop(L) > 2)
7463 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007464
Christopher Faulet700d9e82020-01-31 12:21:52 +01007465 if (!hlua_txn_forward_reply(L, s)) {
7466 if (!(s->flags & SF_ERR_MASK))
7467 s->flags |= SF_ERR_PRXCOND;
7468 lua_pushinteger(L, ACT_RET_ERR);
7469 WILL_LJMP(hlua_done(L));
7470 return 0; /* Never reached */
7471 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007472 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007473
Christopher Faulet700d9e82020-01-31 12:21:52 +01007474 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7475 if (htxn->dir == SMP_OPT_DIR_REQ) {
7476 /* let's log the request time */
7477 s->logs.tv_request = now;
7478 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007479 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007480 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007481
Christopher Faulet700d9e82020-01-31 12:21:52 +01007482 done:
7483 if (!(s->flags & SF_ERR_MASK))
7484 s->flags |= SF_ERR_LOCAL;
7485 if (!(s->flags & SF_FINST_MASK))
7486 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007487
Christopher Faulet4ad73102020-03-05 11:07:31 +01007488 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007489 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007490 return 0;
7491}
7492
Christopher Faulet700d9e82020-01-31 12:21:52 +01007493/*
7494 *
7495 *
7496 * Class REPLY
7497 *
7498 *
7499 */
7500
7501/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
7502 * free slots, the function fails and returns 0;
7503 */
7504static int hlua_txn_reply_new(lua_State *L)
7505{
7506 struct hlua_txn *htxn;
7507 const char *reason, *body = NULL;
7508 int ret, status;
7509
7510 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007511 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007512 hlua_pusherror(L, "txn object is not an HTTP transaction.");
7513 WILL_LJMP(lua_error(L));
7514 }
7515
7516 /* Default value */
7517 status = 200;
7518 reason = http_get_reason(status);
7519
7520 if (lua_istable(L, 2)) {
7521 /* load status and reason from the table argument at index 2 */
7522 ret = lua_getfield(L, 2, "status");
7523 if (ret == LUA_TNIL)
7524 goto reason;
7525 else if (ret != LUA_TNUMBER) {
7526 /* invalid status: ignore the reason */
7527 goto body;
7528 }
7529 status = lua_tointeger(L, -1);
7530
7531 reason:
7532 lua_pop(L, 1); /* restore the stack: remove status */
7533 ret = lua_getfield(L, 2, "reason");
7534 if (ret == LUA_TSTRING)
7535 reason = lua_tostring(L, -1);
7536
7537 body:
7538 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
7539 ret = lua_getfield(L, 2, "body");
7540 if (ret == LUA_TSTRING)
7541 body = lua_tostring(L, -1);
7542 lua_pop(L, 1); /* restore the stack: remove body */
7543 }
7544
7545 /* Create the Reply table */
7546 lua_newtable(L);
7547
7548 /* Add status element */
7549 lua_pushstring(L, "status");
7550 lua_pushinteger(L, status);
7551 lua_settable(L, -3);
7552
7553 /* Add reason element */
7554 reason = http_get_reason(status);
7555 lua_pushstring(L, "reason");
7556 lua_pushstring(L, reason);
7557 lua_settable(L, -3);
7558
7559 /* Add body element, nil if undefined */
7560 lua_pushstring(L, "body");
7561 if (body)
7562 lua_pushstring(L, body);
7563 else
7564 lua_pushnil(L);
7565 lua_settable(L, -3);
7566
7567 /* Add headers element */
7568 lua_pushstring(L, "headers");
7569 lua_newtable(L);
7570
7571 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7572 if (lua_istable(L, 2)) {
7573 /* load headers from the table argument at index 2. If it is a table, copy it. */
7574 ret = lua_getfield(L, 2, "headers");
7575 if (ret == LUA_TTABLE) {
7576 /* stack: [ ... <headers:table>, <table> ] */
7577 lua_pushnil(L);
7578 while (lua_next(L, -2) != 0) {
7579 /* stack: [ ... <headers:table>, <table>, k, v] */
7580 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
7581 /* invalid value type, skip it */
7582 lua_pop(L, 1);
7583 continue;
7584 }
7585
7586
7587 /* Duplicate the key and swap it with the value. */
7588 lua_pushvalue(L, -2);
7589 lua_insert(L, -2);
7590 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
7591
7592 lua_newtable(L);
7593 lua_insert(L, -2);
7594 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
7595
7596 if (lua_isstring(L, -1)) {
7597 /* push the value in the inner table */
7598 lua_rawseti(L, -2, 1);
7599 }
7600 else { /* table */
7601 lua_pushnil(L);
7602 while (lua_next(L, -2) != 0) {
7603 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
7604 if (!lua_isstring(L, -1)) {
7605 /* invalid value type, skip it*/
7606 lua_pop(L, 1);
7607 continue;
7608 }
7609 /* push the value in the inner table */
7610 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
7611 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
7612 }
7613 lua_pop(L, 1);
7614 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
7615 }
7616
7617 /* push (k,v) on the stack in the headers table:
7618 * stack: [ ... <headers:table>, <table>, k, k, v ]
7619 */
7620 lua_settable(L, -5);
7621 /* stack: [ ... <headers:table>, <table>, k ] */
7622 }
7623 }
7624 lua_pop(L, 1);
7625 }
7626 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7627 lua_settable(L, -3);
7628 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
7629
7630 /* Pop a class sesison metatable and affect it to the userdata. */
7631 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
7632 lua_setmetatable(L, -2);
7633 return 1;
7634}
7635
7636/* Set the reply status code, and optionally the reason. If no reason is
7637 * provided, the default one corresponding to the status code is used.
7638 */
7639__LJMP static int hlua_txn_reply_set_status(lua_State *L)
7640{
7641 int status = MAY_LJMP(luaL_checkinteger(L, 2));
7642 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
7643
7644 /* First argument (self) must be a table */
7645 luaL_checktype(L, 1, LUA_TTABLE);
7646
7647 if (status < 100 || status > 599) {
7648 lua_pushboolean(L, 0);
7649 return 1;
7650 }
7651 if (!reason)
7652 reason = http_get_reason(status);
7653
7654 lua_pushinteger(L, status);
7655 lua_setfield(L, 1, "status");
7656
7657 lua_pushstring(L, reason);
7658 lua_setfield(L, 1, "reason");
7659
7660 lua_pushboolean(L, 1);
7661 return 1;
7662}
7663
7664/* Add a header into the reply object. Each header name is associated to an
7665 * array of values in the "headers" table. If the header name is not found, a
7666 * new entry is created.
7667 */
7668__LJMP static int hlua_txn_reply_add_header(lua_State *L)
7669{
7670 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7671 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
7672 int ret;
7673
7674 /* First argument (self) must be a table */
7675 luaL_checktype(L, 1, LUA_TTABLE);
7676
7677 /* Push in the stack the "headers" entry. */
7678 ret = lua_getfield(L, 1, "headers");
7679 if (ret != LUA_TTABLE) {
7680 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
7681 WILL_LJMP(lua_error(L));
7682 }
7683
7684 /* check if the header is already registered. If not, register it. */
7685 ret = lua_getfield(L, -1, name);
7686 if (ret == LUA_TNIL) {
7687 /* Entry not found. */
7688 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
7689
7690 /* Insert the new header name in the array in the top of the stack.
7691 * It left the new array in the top of the stack.
7692 */
7693 lua_newtable(L);
7694 lua_pushstring(L, name);
7695 lua_pushvalue(L, -2);
7696 lua_settable(L, -4);
7697 }
7698 else if (ret != LUA_TTABLE) {
7699 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
7700 WILL_LJMP(lua_error(L));
7701 }
7702
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07007703 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01007704 * the header value as new entry.
7705 */
7706 lua_pushstring(L, value);
7707 ret = lua_rawlen(L, -2);
7708 lua_rawseti(L, -2, ret + 1);
7709
7710 lua_pushboolean(L, 1);
7711 return 1;
7712}
7713
7714/* Remove all occurrences of a given header name. */
7715__LJMP static int hlua_txn_reply_del_header(lua_State *L)
7716{
7717 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7718 int ret;
7719
7720 /* First argument (self) must be a table */
7721 luaL_checktype(L, 1, LUA_TTABLE);
7722
7723 /* Push in the stack the "headers" entry. */
7724 ret = lua_getfield(L, 1, "headers");
7725 if (ret != LUA_TTABLE) {
7726 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
7727 WILL_LJMP(lua_error(L));
7728 }
7729
7730 lua_pushstring(L, name);
7731 lua_pushnil(L);
7732 lua_settable(L, -3);
7733
7734 lua_pushboolean(L, 1);
7735 return 1;
7736}
7737
7738/* Set the reply's body. Overwrite any existing entry. */
7739__LJMP static int hlua_txn_reply_set_body(lua_State *L)
7740{
7741 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
7742
7743 /* First argument (self) must be a table */
7744 luaL_checktype(L, 1, LUA_TTABLE);
7745
7746 lua_pushstring(L, payload);
7747 lua_setfield(L, 1, "body");
7748
7749 lua_pushboolean(L, 1);
7750 return 1;
7751}
7752
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007753__LJMP static int hlua_log(lua_State *L)
7754{
7755 int level;
7756 const char *msg;
7757
7758 MAY_LJMP(check_args(L, 2, "log"));
7759 level = MAY_LJMP(luaL_checkinteger(L, 1));
7760 msg = MAY_LJMP(luaL_checkstring(L, 2));
7761
7762 if (level < 0 || level >= NB_LOG_LEVELS)
7763 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7764
7765 hlua_sendlog(NULL, level, msg);
7766 return 0;
7767}
7768
7769__LJMP static int hlua_log_debug(lua_State *L)
7770{
7771 const char *msg;
7772
7773 MAY_LJMP(check_args(L, 1, "debug"));
7774 msg = MAY_LJMP(luaL_checkstring(L, 1));
7775 hlua_sendlog(NULL, LOG_DEBUG, msg);
7776 return 0;
7777}
7778
7779__LJMP static int hlua_log_info(lua_State *L)
7780{
7781 const char *msg;
7782
7783 MAY_LJMP(check_args(L, 1, "info"));
7784 msg = MAY_LJMP(luaL_checkstring(L, 1));
7785 hlua_sendlog(NULL, LOG_INFO, msg);
7786 return 0;
7787}
7788
7789__LJMP static int hlua_log_warning(lua_State *L)
7790{
7791 const char *msg;
7792
7793 MAY_LJMP(check_args(L, 1, "warning"));
7794 msg = MAY_LJMP(luaL_checkstring(L, 1));
7795 hlua_sendlog(NULL, LOG_WARNING, msg);
7796 return 0;
7797}
7798
7799__LJMP static int hlua_log_alert(lua_State *L)
7800{
7801 const char *msg;
7802
7803 MAY_LJMP(check_args(L, 1, "alert"));
7804 msg = MAY_LJMP(luaL_checkstring(L, 1));
7805 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007806 return 0;
7807}
7808
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007809__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007810{
7811 int wakeup_ms = lua_tointeger(L, -1);
7812 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02007813 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007814 return 0;
7815}
7816
7817__LJMP static int hlua_sleep(lua_State *L)
7818{
7819 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007820 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007821
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007822 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007823
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007824 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007825 wakeup_ms = tick_add(now_ms, delay);
7826 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007827
Willy Tarreau9635e032018-10-16 17:52:55 +02007828 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007829 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007830}
7831
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007832__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007833{
7834 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007835 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007836
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007837 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007838
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007839 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007840 wakeup_ms = tick_add(now_ms, delay);
7841 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007842
Willy Tarreau9635e032018-10-16 17:52:55 +02007843 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007844 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007845}
7846
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007847/* This functionis an LUA binding. it permits to give back
7848 * the hand at the HAProxy scheduler. It is used when the
7849 * LUA processing consumes a lot of time.
7850 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007851__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007852{
7853 return 0;
7854}
7855
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007856__LJMP static int hlua_yield(lua_State *L)
7857{
Willy Tarreau9635e032018-10-16 17:52:55 +02007858 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007859 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007860}
7861
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007862/* This function change the nice of the currently executed
7863 * task. It is used set low or high priority at the current
7864 * task.
7865 */
Willy Tarreau59551662015-03-10 14:23:13 +01007866__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007867{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007868 struct hlua *hlua;
7869 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007870
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007871 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007872 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007873
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007874 /* Get hlua struct, or NULL if we execute from main lua state */
7875 hlua = hlua_gethlua(L);
7876
7877 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007878 if (!hlua || !hlua->task)
7879 return 0;
7880
7881 if (nice < -1024)
7882 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007883 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007884 nice = 1024;
7885
7886 hlua->task->nice = nice;
7887 return 0;
7888}
7889
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007890/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007891 * HAProxy task subsystem when the task is awaked. The LUA runtime can
7892 * return an E_AGAIN signal, the emmiter of this signal must set a
7893 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007894 *
7895 * Task wrapper are longjmp safe because the only one Lua code
7896 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007897 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01007898struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007899{
Olivier Houchard9f6af332018-05-25 14:04:04 +02007900 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007901 enum hlua_exec status;
7902
Christopher Faulet5bc99722018-04-25 10:34:45 +02007903 if (task->thread_mask == MAX_THREADS_MASK)
7904 task_set_affinity(task, tid_bit);
7905
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007906 /* If it is the first call to the task, we must initialize the
7907 * execution timeouts.
7908 */
7909 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007910 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007911
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007912 /* Execute the Lua code. */
7913 status = hlua_ctx_resume(hlua, 1);
7914
7915 switch (status) {
7916 /* finished or yield */
7917 case HLUA_E_OK:
7918 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007919 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02007920 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007921 break;
7922
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01007923 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01007924 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02007925 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007926 break;
7927
7928 /* finished with error. */
7929 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007930 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007931 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007932 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007933 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007934 break;
7935
7936 case HLUA_E_ERR:
7937 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007938 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007939 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007940 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007941 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007942 break;
7943 }
Emeric Brun253e53e2017-10-17 18:58:40 +02007944 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007945}
7946
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007947/* This function is an LUA binding that register LUA function to be
7948 * executed after the HAProxy configuration parsing and before the
7949 * HAProxy scheduler starts. This function expect only one LUA
7950 * argument that is a function. This function returns nothing, but
7951 * throws if an error is encountered.
7952 */
7953__LJMP static int hlua_register_init(lua_State *L)
7954{
7955 struct hlua_init_function *init;
7956 int ref;
7957
7958 MAY_LJMP(check_args(L, 1, "register_init"));
7959
7960 ref = MAY_LJMP(hlua_checkfunction(L, 1));
7961
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007962 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007963 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007964 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007965
7966 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02007967 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007968 return 0;
7969}
7970
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007971/* This functio is an LUA binding. It permits to register a task
7972 * executed in parallel of the main HAroxy activity. The task is
7973 * created and it is set in the HAProxy scheduler. It can be called
7974 * from the "init" section, "post init" or during the runtime.
7975 *
7976 * Lua prototype:
7977 *
7978 * <none> core.register_task(<function>)
7979 */
7980static int hlua_register_task(lua_State *L)
7981{
Christopher Faulet5294ec02021-04-12 12:24:47 +02007982 struct hlua *hlua = NULL;
7983 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007984 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01007985 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007986
7987 MAY_LJMP(check_args(L, 1, "register_task"));
7988
7989 ref = MAY_LJMP(hlua_checkfunction(L, 1));
7990
Thierry Fournier75fc0292020-11-28 13:18:56 +01007991 /* Get the reference state. If the reference is NULL, L is the master
7992 * state, otherwise hlua->T is.
7993 */
7994 hlua = hlua_gethlua(L);
7995 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01007996 /* we are in runtime processing */
7997 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01007998 else
Thierry Fournier021d9862020-11-28 23:42:03 +01007999 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008000 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008001
Willy Tarreaubafbe012017-11-24 17:34:44 +01008002 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008003 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008004 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008005 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008006
Thierry Fournier59f11be2020-11-29 00:37:41 +01008007 /* We are in the common lua state, execute the task anywhere,
8008 * otherwise, inherit the current thread identifier
8009 */
8010 if (state_id == 0)
8011 task = task_new(MAX_THREADS_MASK);
8012 else
8013 task = task_new(tid_bit);
Willy Tarreaue09101e2018-10-16 17:37:12 +02008014 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008015 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008016
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008017 task->context = hlua;
8018 task->process = hlua_process_task;
8019
Thierry Fournier021d9862020-11-28 23:42:03 +01008020 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008021 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008022
8023 /* Restore the function in the stack. */
8024 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8025 hlua->nargs = 0;
8026
8027 /* Schedule task. */
8028 task_schedule(task, now_ms);
8029
8030 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008031
8032 alloc_error:
8033 task_destroy(task);
8034 hlua_ctx_destroy(hlua);
8035 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8036 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008037}
8038
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008039/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8040 * doesn't allow "yield" functions because the HAProxy engine cannot
8041 * resume converters.
8042 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008043static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008044{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008045 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008046 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008047 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008048
Willy Tarreaube508f12016-03-10 11:47:01 +01008049 if (!stream)
8050 return 0;
8051
Willy Tarreau87b09662015-04-03 00:22:06 +02008052 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008053 * Lua context can be not initialized. This behavior
8054 * permits to save performances because a systematic
8055 * Lua initialization cause 5% performances loss.
8056 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008057 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008058 struct hlua *hlua;
8059
8060 hlua = pool_alloc(pool_head_hlua);
8061 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008062 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8063 return 0;
8064 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008065 HLUA_INIT(hlua);
8066 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008067 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008068 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8069 return 0;
8070 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008071 }
8072
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008073 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008074 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008075
8076 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008077 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008078 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8079 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008080 else
8081 error = "critical error";
8082 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008083 return 0;
8084 }
8085
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008086 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008087 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008088 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008089 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008090 return 0;
8091 }
8092
8093 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008094 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008095
8096 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008097 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008098 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008099 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008100 return 0;
8101 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008102 hlua_smp2lua(stream->hlua->T, smp);
8103 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008104
8105 /* push keywords in the stack. */
8106 if (arg_p) {
8107 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008108 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008109 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008110 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008111 return 0;
8112 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008113 hlua_arg2lua(stream->hlua->T, arg_p);
8114 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008115 }
8116 }
8117
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008118 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008119 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008120
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008121 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008122 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008123 }
8124
8125 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008126 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008127 /* finished. */
8128 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008129 /* If the stack is empty, the function fails. */
8130 if (lua_gettop(stream->hlua->T) <= 0)
8131 return 0;
8132
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008133 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008134 hlua_lua2smp(stream->hlua->T, -1, smp);
8135 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008136 return 1;
8137
8138 /* yield. */
8139 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008140 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008141 return 0;
8142
8143 /* finished with error. */
8144 case HLUA_E_ERRMSG:
8145 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008146 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008147 fcn->name, lua_tostring(stream->hlua->T, -1));
8148 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008149 return 0;
8150
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008151 case HLUA_E_ETMOUT:
8152 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8153 return 0;
8154
8155 case HLUA_E_NOMEM:
8156 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8157 return 0;
8158
8159 case HLUA_E_YIELD:
8160 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8161 return 0;
8162
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008163 case HLUA_E_ERR:
8164 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008165 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008166 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008167
8168 default:
8169 return 0;
8170 }
8171}
8172
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008173/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8174 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008175 * resume sample-fetches. This function will be called by the sample
8176 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008177 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008178static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8179 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008180{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008181 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008182 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008183 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008184 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008185
Willy Tarreaube508f12016-03-10 11:47:01 +01008186 if (!stream)
8187 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008188
Willy Tarreau87b09662015-04-03 00:22:06 +02008189 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008190 * Lua context can be not initialized. This behavior
8191 * permits to save performances because a systematic
8192 * Lua initialization cause 5% performances loss.
8193 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008194 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008195 struct hlua *hlua;
8196
8197 hlua = pool_alloc(pool_head_hlua);
8198 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008199 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8200 return 0;
8201 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008202 hlua->T = NULL;
8203 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008204 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008205 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8206 return 0;
8207 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008208 }
8209
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008210 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008211 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008212
8213 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008214 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008215 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8216 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008217 else
8218 error = "critical error";
8219 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008220 return 0;
8221 }
8222
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008223 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008224 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008225 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008226 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008227 return 0;
8228 }
8229
8230 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008231 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008232
8233 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008234 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008235 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008236 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008237 return 0;
8238 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008239 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008240
8241 /* push keywords in the stack. */
8242 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8243 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008244 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008245 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008246 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008247 return 0;
8248 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008249 hlua_arg2lua(stream->hlua->T, arg_p);
8250 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008251 }
8252
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008253 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008254 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008255
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008256 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008257 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008258 }
8259
8260 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008261 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008262 /* finished. */
8263 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008264 /* If the stack is empty, the function fails. */
8265 if (lua_gettop(stream->hlua->T) <= 0)
8266 return 0;
8267
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008268 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008269 hlua_lua2smp(stream->hlua->T, -1, smp);
8270 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008271
8272 /* Set the end of execution flag. */
8273 smp->flags &= ~SMP_F_MAY_CHANGE;
8274 return 1;
8275
8276 /* yield. */
8277 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008278 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008279 return 0;
8280
8281 /* finished with error. */
8282 case HLUA_E_ERRMSG:
8283 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008284 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008285 fcn->name, lua_tostring(stream->hlua->T, -1));
8286 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008287 return 0;
8288
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008289 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008290 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8291 return 0;
8292
8293 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008294 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8295 return 0;
8296
8297 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008298 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8299 return 0;
8300
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008301 case HLUA_E_ERR:
8302 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008303 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008304 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008305
8306 default:
8307 return 0;
8308 }
8309}
8310
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008311/* This function is an LUA binding used for registering
8312 * "sample-conv" functions. It expects a converter name used
8313 * in the haproxy configuration file, and an LUA function.
8314 */
8315__LJMP static int hlua_register_converters(lua_State *L)
8316{
8317 struct sample_conv_kw_list *sck;
8318 const char *name;
8319 int ref;
8320 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008321 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008322 struct sample_conv *sc;
8323 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008324
8325 MAY_LJMP(check_args(L, 2, "register_converters"));
8326
8327 /* First argument : converter name. */
8328 name = MAY_LJMP(luaL_checkstring(L, 1));
8329
8330 /* Second argument : lua function. */
8331 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8332
Thierry Fournierf67442e2020-11-28 20:41:07 +01008333 /* Check if the converter is already registered */
8334 trash = get_trash_chunk();
8335 chunk_printf(trash, "lua.%s", name);
8336 sc = find_sample_conv(trash->area, trash->data);
8337 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008338 fcn = sc->private;
8339 if (fcn->function_ref[hlua_state_id] != -1) {
8340 ha_warning("Trying to register converter 'lua.%s' more than once. "
8341 "This will become a hard error in version 2.5.\n", name);
8342 }
8343 fcn->function_ref[hlua_state_id] = ref;
8344 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008345 }
8346
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008347 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008348 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008349 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008350 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008351 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008352 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008353 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008354
8355 /* Fill fcn. */
8356 fcn->name = strdup(name);
8357 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008358 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008359 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008360
8361 /* List head */
8362 sck->list.n = sck->list.p = NULL;
8363
8364 /* converter keyword. */
8365 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008366 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008367 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008368 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008369
8370 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8371 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008372 sck->kw[0].arg_mask = ARG12(0,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008373 sck->kw[0].val_args = NULL;
8374 sck->kw[0].in_type = SMP_T_STR;
8375 sck->kw[0].out_type = SMP_T_STR;
8376 sck->kw[0].private = fcn;
8377
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008378 /* Register this new converter */
8379 sample_register_convs(sck);
8380
8381 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008382
8383 alloc_error:
8384 release_hlua_function(fcn);
8385 ha_free(&sck);
8386 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8387 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008388}
8389
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008390/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008391 * "sample-fetch" functions. It expects a converter name used
8392 * in the haproxy configuration file, and an LUA function.
8393 */
8394__LJMP static int hlua_register_fetches(lua_State *L)
8395{
8396 const char *name;
8397 int ref;
8398 int len;
8399 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008400 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008401 struct sample_fetch *sf;
8402 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008403
8404 MAY_LJMP(check_args(L, 2, "register_fetches"));
8405
8406 /* First argument : sample-fetch name. */
8407 name = MAY_LJMP(luaL_checkstring(L, 1));
8408
8409 /* Second argument : lua function. */
8410 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8411
Thierry Fournierf67442e2020-11-28 20:41:07 +01008412 /* Check if the sample-fetch is already registered */
8413 trash = get_trash_chunk();
8414 chunk_printf(trash, "lua.%s", name);
8415 sf = find_sample_fetch(trash->area, trash->data);
8416 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008417 fcn = sf->private;
8418 if (fcn->function_ref[hlua_state_id] != -1) {
8419 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8420 "This will become a hard error in version 2.5.\n", name);
8421 }
8422 fcn->function_ref[hlua_state_id] = ref;
8423 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008424 }
8425
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008426 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008427 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008428 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008429 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008430 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008431 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008432 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008433
8434 /* Fill fcn. */
8435 fcn->name = strdup(name);
8436 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008437 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008438 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008439
8440 /* List head */
8441 sfk->list.n = sfk->list.p = NULL;
8442
8443 /* sample-fetch keyword. */
8444 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008445 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008446 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008447 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008448
8449 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8450 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008451 sfk->kw[0].arg_mask = ARG12(0,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008452 sfk->kw[0].val_args = NULL;
8453 sfk->kw[0].out_type = SMP_T_STR;
8454 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8455 sfk->kw[0].val = 0;
8456 sfk->kw[0].private = fcn;
8457
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008458 /* Register this new fetch. */
8459 sample_register_fetches(sfk);
8460
8461 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008462
8463 alloc_error:
8464 release_hlua_function(fcn);
8465 ha_free(&sfk);
8466 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8467 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008468}
8469
Christopher Faulet501465d2020-02-26 14:54:16 +01008470/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008471 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008472__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008473{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008474 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008475 unsigned int delay;
8476 unsigned int wakeup_ms;
8477
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008478 /* Get hlua struct, or NULL if we execute from main lua state */
8479 hlua = hlua_gethlua(L);
8480 if (!hlua) {
8481 return 0;
8482 }
8483
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008484 MAY_LJMP(check_args(L, 1, "wake_time"));
8485
8486 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8487 wakeup_ms = tick_add(now_ms, delay);
8488 hlua->wake_time = wakeup_ms;
8489 return 0;
8490}
8491
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008492/* This function is a wrapper to execute each LUA function declared as an action
8493 * wrapper during the initialisation period. This function may return any
8494 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8495 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8496 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008497 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008498static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02008499 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008500{
8501 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008502 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008503 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008504 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008505
8506 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008507 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
8508 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
8509 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
8510 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008511 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008512 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008513 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008514 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008515
Willy Tarreau87b09662015-04-03 00:22:06 +02008516 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008517 * Lua context can be not initialized. This behavior
8518 * permits to save performances because a systematic
8519 * Lua initialization cause 5% performances loss.
8520 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008521 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008522 struct hlua *hlua;
8523
8524 hlua = pool_alloc(pool_head_hlua);
8525 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008526 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008527 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008528 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008529 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008530 HLUA_INIT(hlua);
8531 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008532 if (!hlua_ctx_init(s->hlua, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn), s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008533 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008534 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008535 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008536 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008537 }
8538
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008539 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008540 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008541
8542 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008543 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008544 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
8545 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008546 else
8547 error = "critical error";
8548 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008549 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008550 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008551 }
8552
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008553 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008554 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008555 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008556 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008557 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008558 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008559 }
8560
8561 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008562 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008563
Willy Tarreau87b09662015-04-03 00:22:06 +02008564 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008565 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008566 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008567 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008568 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008569 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008570 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008571 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008572
8573 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008574 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008575 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008576 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008577 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008578 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008579 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008580 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008581 lua_pushstring(s->hlua->T, *arg);
8582 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008583 }
8584
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008585 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008586 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008587
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008588 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008589 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008590 }
8591
8592 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01008593 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008594 /* finished. */
8595 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008596 /* Catch the return value */
8597 if (lua_gettop(s->hlua->T) > 0)
8598 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008599
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008600 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02008601 if (act_ret == ACT_RET_YIELD) {
8602 if (flags & ACT_OPT_FINAL)
8603 goto err_yield;
8604
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008605 if (dir == SMP_OPT_DIR_REQ)
8606 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8607 s->hlua->wake_time);
8608 else
8609 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8610 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008611 }
8612 goto end;
8613
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008614 /* yield. */
8615 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008616 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008617 if (dir == SMP_OPT_DIR_REQ)
8618 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8619 s->hlua->wake_time);
8620 else
8621 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8622 s->hlua->wake_time);
8623
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008624 /* Some actions can be wake up when a "write" event
8625 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008626 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008627 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02008628 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008629 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008630 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008631 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008632 act_ret = ACT_RET_YIELD;
8633 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008634
8635 /* finished with error. */
8636 case HLUA_E_ERRMSG:
8637 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008638 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008639 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008640 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008641 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008642
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008643 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008644 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008645 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008646
8647 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008648 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008649 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008650
8651 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02008652 err_yield:
8653 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008654 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008655 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008656 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008657
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008658 case HLUA_E_ERR:
8659 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008660 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008661 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008662
8663 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008664 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008665 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008666
8667 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02008668 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008669 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008670 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008671}
8672
Willy Tarreau144f84a2021-03-02 16:09:26 +01008673struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008674{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008675 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008676
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008677 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02008678 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02008679 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008680}
8681
8682static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8683{
8684 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008685 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008686 struct task *task;
8687 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008688 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008689
Willy Tarreaubafbe012017-11-24 17:34:44 +01008690 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008691 if (!hlua) {
8692 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008693 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008694 return 0;
8695 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008696 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008697 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008698 ctx->ctx.hlua_apptcp.flags = 0;
8699
8700 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008701 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008702 if (!task) {
8703 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008704 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008705 return 0;
8706 }
8707 task->nice = 0;
8708 task->context = ctx;
8709 task->process = hlua_applet_wakeup;
8710 ctx->ctx.hlua_apptcp.task = task;
8711
8712 /* In the execution wrappers linked with a stream, the
8713 * Lua context can be not initialized. This behavior
8714 * permits to save performances because a systematic
8715 * Lua initialization cause 5% performances loss.
8716 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008717 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008718 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008719 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008720 return 0;
8721 }
8722
8723 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008724 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008725
8726 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008727 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008728 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8729 error = lua_tostring(hlua->T, -1);
8730 else
8731 error = "critical error";
8732 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008733 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008734 return 0;
8735 }
8736
8737 /* Check stack available size. */
8738 if (!lua_checkstack(hlua->T, 1)) {
8739 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008740 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008741 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008742 return 0;
8743 }
8744
8745 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008746 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008747
8748 /* Create and and push object stream in the stack. */
8749 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
8750 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008751 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008752 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008753 return 0;
8754 }
8755 hlua->nargs = 1;
8756
8757 /* push keywords in the stack. */
8758 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8759 if (!lua_checkstack(hlua->T, 1)) {
8760 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008761 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008762 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008763 return 0;
8764 }
8765 lua_pushstring(hlua->T, *arg);
8766 hlua->nargs++;
8767 }
8768
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008769 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008770
8771 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008772 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01008773 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008774
8775 return 1;
8776}
8777
Willy Tarreau60409db2019-08-21 14:14:50 +02008778void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008779{
8780 struct stream_interface *si = ctx->owner;
8781 struct stream *strm = si_strm(si);
8782 struct channel *res = si_ic(si);
8783 struct act_rule *rule = ctx->rule;
8784 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008785 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008786
8787 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02008788 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
8789 /* eat the whole request */
8790 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008791 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02008792 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008793
8794 /* If the stream is disconnect or closed, ldo nothing. */
8795 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8796 return;
8797
8798 /* Execute the function. */
8799 switch (hlua_ctx_resume(hlua, 1)) {
8800 /* finished. */
8801 case HLUA_E_OK:
8802 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8803
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008804 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02008805 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008806 res->flags |= CF_READ_NULL;
8807 si_shutr(si);
8808 return;
8809
8810 /* yield. */
8811 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01008812 if (hlua->wake_time != TICK_ETERNITY)
8813 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008814 return;
8815
8816 /* finished with error. */
8817 case HLUA_E_ERRMSG:
8818 /* Display log. */
8819 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008820 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008821 lua_pop(hlua->T, 1);
8822 goto error;
8823
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008824 case HLUA_E_ETMOUT:
8825 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008826 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008827 goto error;
8828
8829 case HLUA_E_NOMEM:
8830 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008831 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008832 goto error;
8833
8834 case HLUA_E_YIELD: /* unexpected */
8835 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008836 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008837 goto error;
8838
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008839 case HLUA_E_ERR:
8840 /* Display log. */
8841 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008842 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008843 goto error;
8844
8845 default:
8846 goto error;
8847 }
8848
8849error:
8850
8851 /* For all other cases, just close the stream. */
8852 si_shutw(si);
8853 si_shutr(si);
8854 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8855}
8856
8857static void hlua_applet_tcp_release(struct appctx *ctx)
8858{
Olivier Houchard3f795f72019-04-17 22:51:06 +02008859 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008860 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008861 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008862 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008863}
8864
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008865/* The function returns 1 if the initialisation is complete, 0 if
8866 * an errors occurs and -1 if more data are required for initializing
8867 * the applet.
8868 */
8869static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8870{
8871 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008872 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008873 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008874 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008875 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008876 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008877
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008878 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01008879 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008880 if (!hlua) {
8881 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008882 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008883 return 0;
8884 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008885 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008886 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008887 ctx->ctx.hlua_apphttp.left_bytes = -1;
8888 ctx->ctx.hlua_apphttp.flags = 0;
8889
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01008890 if (txn->req.flags & HTTP_MSGF_VER_11)
8891 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
8892
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008893 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008894 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008895 if (!task) {
8896 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008897 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008898 return 0;
8899 }
8900 task->nice = 0;
8901 task->context = ctx;
8902 task->process = hlua_applet_wakeup;
8903 ctx->ctx.hlua_apphttp.task = task;
8904
8905 /* In the execution wrappers linked with a stream, the
8906 * Lua context can be not initialized. This behavior
8907 * permits to save performances because a systematic
8908 * Lua initialization cause 5% performances loss.
8909 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008910 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008911 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008912 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008913 return 0;
8914 }
8915
8916 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008917 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008918
8919 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008920 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008921 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8922 error = lua_tostring(hlua->T, -1);
8923 else
8924 error = "critical error";
8925 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008926 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008927 return 0;
8928 }
8929
8930 /* Check stack available size. */
8931 if (!lua_checkstack(hlua->T, 1)) {
8932 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008933 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008934 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008935 return 0;
8936 }
8937
8938 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008939 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008940
8941 /* Create and and push object stream in the stack. */
8942 if (!hlua_applet_http_new(hlua->T, ctx)) {
8943 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008944 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008945 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008946 return 0;
8947 }
8948 hlua->nargs = 1;
8949
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008950 /* push keywords in the stack. */
8951 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8952 if (!lua_checkstack(hlua->T, 1)) {
8953 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008954 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008955 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008956 return 0;
8957 }
8958 lua_pushstring(hlua->T, *arg);
8959 hlua->nargs++;
8960 }
8961
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008962 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008963
8964 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008965 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008966
8967 return 1;
8968}
8969
Willy Tarreau60409db2019-08-21 14:14:50 +02008970void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008971{
8972 struct stream_interface *si = ctx->owner;
8973 struct stream *strm = si_strm(si);
8974 struct channel *req = si_oc(si);
8975 struct channel *res = si_ic(si);
8976 struct act_rule *rule = ctx->rule;
8977 struct proxy *px = strm->be;
8978 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
8979 struct htx *req_htx, *res_htx;
8980
8981 res_htx = htx_from_buf(&res->buf);
8982
8983 /* If the stream is disconnect or closed, ldo nothing. */
8984 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8985 goto out;
8986
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008987 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008988 if (!b_size(&res->buf)) {
8989 si_rx_room_blk(si);
8990 goto out;
8991 }
8992 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01008993 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008994 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
8995
8996 /* Set the currently running flag. */
8997 if (!HLUA_IS_RUNNING(hlua) &&
8998 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02008999 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009000 si_cant_get(si);
9001 goto out;
9002 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009003 }
9004
9005 /* Executes The applet if it is not done. */
9006 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9007
9008 /* Execute the function. */
9009 switch (hlua_ctx_resume(hlua, 1)) {
9010 /* finished. */
9011 case HLUA_E_OK:
9012 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9013 break;
9014
9015 /* yield. */
9016 case HLUA_E_AGAIN:
9017 if (hlua->wake_time != TICK_ETERNITY)
9018 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009019 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009020
9021 /* finished with error. */
9022 case HLUA_E_ERRMSG:
9023 /* Display log. */
9024 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009025 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009026 lua_pop(hlua->T, 1);
9027 goto error;
9028
9029 case HLUA_E_ETMOUT:
9030 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009031 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009032 goto error;
9033
9034 case HLUA_E_NOMEM:
9035 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009036 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009037 goto error;
9038
9039 case HLUA_E_YIELD: /* unexpected */
9040 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009041 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009042 goto error;
9043
9044 case HLUA_E_ERR:
9045 /* Display log. */
9046 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009047 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009048 goto error;
9049
9050 default:
9051 goto error;
9052 }
9053 }
9054
9055 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009056 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9057 goto done;
9058
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009059 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9060 goto error;
9061
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009062 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
9063 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009064 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9065 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009066 }
9067
9068 done:
9069 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009070 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009071 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009072 si_shutr(si);
9073 }
9074
9075 /* eat the whole request */
9076 if (co_data(req)) {
9077 req_htx = htx_from_buf(&req->buf);
9078 co_htx_skip(req, req_htx, co_data(req));
9079 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009080 }
9081 }
9082
9083 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009084 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009085 return;
9086
9087 error:
9088
9089 /* If we are in HTTP mode, and we are not send any
9090 * data, return a 500 server error in best effort:
9091 * if there is no room available in the buffer,
9092 * just close the connection.
9093 */
9094 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009095 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009096
9097 channel_erase(res);
9098 res->buf.data = b_data(err);
9099 memcpy(res->buf.area, b_head(err), b_data(err));
9100 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009101 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009102 }
9103 if (!(strm->flags & SF_ERR_MASK))
9104 strm->flags |= SF_ERR_RESOURCE;
9105 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9106 goto done;
9107}
9108
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009109static void hlua_applet_http_release(struct appctx *ctx)
9110{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009111 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009112 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009113 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009114 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009115}
9116
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009117/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009118 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009119 *
9120 * This function can fail with an abort() due to an Lua critical error.
9121 * We are in the configuration parsing process of HAProxy, this abort() is
9122 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009123 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009124static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9125 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009126{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009127 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009128 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009129
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009130 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009131 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009132 if (!rule->arg.hlua_rule) {
9133 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009134 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009135 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009136
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009137 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009138 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9139 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009140 if (!rule->arg.hlua_rule->args) {
9141 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009142 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009143 }
9144
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009145 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009146 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009147
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009148 /* Expect some arguments */
9149 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009150 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009151 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009152 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009153 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009154 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009155 if (!rule->arg.hlua_rule->args[i]) {
9156 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009157 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009158 }
9159 (*cur_arg)++;
9160 }
9161 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009162
Thierry FOURNIER42148732015-09-02 17:17:33 +02009163 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009164 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009165 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009166
9167 error:
9168 if (rule->arg.hlua_rule) {
9169 if (rule->arg.hlua_rule->args) {
9170 for (i = 0; i < fcn->nargs; i++)
9171 ha_free(&rule->arg.hlua_rule->args[i]);
9172 ha_free(&rule->arg.hlua_rule->args);
9173 }
9174 ha_free(&rule->arg.hlua_rule);
9175 }
9176 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009177}
9178
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009179static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9180 struct act_rule *rule, char **err)
9181{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009182 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009183
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009184 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009185 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009186 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009187 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009188 * the call of this analyzer.
9189 */
9190 if (rule->from != ACT_F_HTTP_REQ) {
9191 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9192 return ACT_RET_PRS_ERR;
9193 }
9194
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009195 /* Memory for the rule. */
9196 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9197 if (!rule->arg.hlua_rule) {
9198 memprintf(err, "out of memory error");
9199 return ACT_RET_PRS_ERR;
9200 }
9201
9202 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009203 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009204
9205 /* TODO: later accept arguments. */
9206 rule->arg.hlua_rule->args = NULL;
9207
9208 /* Add applet pointer in the rule. */
9209 rule->applet.obj_type = OBJ_TYPE_APPLET;
9210 rule->applet.name = fcn->name;
9211 rule->applet.init = hlua_applet_http_init;
9212 rule->applet.fct = hlua_applet_http_fct;
9213 rule->applet.release = hlua_applet_http_release;
9214 rule->applet.timeout = hlua_timeout_applet;
9215
9216 return ACT_RET_PRS_OK;
9217}
9218
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009219/* This function is an LUA binding used for registering
9220 * "sample-conv" functions. It expects a converter name used
9221 * in the haproxy configuration file, and an LUA function.
9222 */
9223__LJMP static int hlua_register_action(lua_State *L)
9224{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009225 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009226 const char *name;
9227 int ref;
9228 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009229 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009230 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009231 struct buffer *trash;
9232 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009233
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009234 /* Initialise the number of expected arguments at 0. */
9235 nargs = 0;
9236
9237 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9238 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009239
9240 /* First argument : converter name. */
9241 name = MAY_LJMP(luaL_checkstring(L, 1));
9242
9243 /* Second argument : environment. */
9244 if (lua_type(L, 2) != LUA_TTABLE)
9245 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9246
9247 /* Third argument : lua function. */
9248 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9249
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009250 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009251 if (lua_gettop(L) >= 4)
9252 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9253
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009254 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009255 lua_pushnil(L);
9256 while (lua_next(L, 2) != 0) {
9257 if (lua_type(L, -1) != LUA_TSTRING)
9258 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9259
Thierry Fournierf67442e2020-11-28 20:41:07 +01009260 /* Check if action exists */
9261 trash = get_trash_chunk();
9262 chunk_printf(trash, "lua.%s", name);
9263 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9264 akw = tcp_req_cont_action(trash->area);
9265 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9266 akw = tcp_res_cont_action(trash->area);
9267 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9268 akw = action_http_req_custom(trash->area);
9269 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9270 akw = action_http_res_custom(trash->area);
9271 } else {
9272 akw = NULL;
9273 }
9274 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009275 fcn = akw->private;
9276 if (fcn->function_ref[hlua_state_id] != -1) {
9277 ha_warning("Trying to register action 'lua.%s' more than once. "
9278 "This will become a hard error in version 2.5.\n", name);
9279 }
9280 fcn->function_ref[hlua_state_id] = ref;
9281
9282 /* pop the environment string. */
9283 lua_pop(L, 1);
9284 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009285 }
9286
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009287 /* Check required environment. Only accepted "http" or "tcp". */
9288 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009289 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009290 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009291 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009292 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009293 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009294 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009295
9296 /* Fill fcn. */
9297 fcn->name = strdup(name);
9298 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009299 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009300 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009301
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009302 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009303 fcn->nargs = nargs;
9304
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009305 /* List head */
9306 akl->list.n = akl->list.p = NULL;
9307
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009308 /* action keyword. */
9309 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009310 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009311 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009312 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009313
9314 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9315
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009316 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009317 akl->kw[0].private = fcn;
9318 akl->kw[0].parse = action_register_lua;
9319
9320 /* select the action registering point. */
9321 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9322 tcp_req_cont_keywords_register(akl);
9323 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9324 tcp_res_cont_keywords_register(akl);
9325 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9326 http_req_keywords_register(akl);
9327 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9328 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009329 else {
9330 release_hlua_function(fcn);
9331 if (akl)
9332 ha_free((char **)&(akl->kw[0].kw));
9333 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009334 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009335 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9336 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009337 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009338
9339 /* pop the environment string. */
9340 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009341
9342 /* reset for next loop */
9343 akl = NULL;
9344 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009345 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009346 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009347
9348 alloc_error:
9349 release_hlua_function(fcn);
9350 ha_free(&akl);
9351 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9352 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009353}
9354
9355static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9356 struct act_rule *rule, char **err)
9357{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009358 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009359
Christopher Faulet280f85b2019-07-15 15:02:04 +02009360 if (px->mode == PR_MODE_HTTP) {
9361 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009362 return ACT_RET_PRS_ERR;
9363 }
9364
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009365 /* Memory for the rule. */
9366 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9367 if (!rule->arg.hlua_rule) {
9368 memprintf(err, "out of memory error");
9369 return ACT_RET_PRS_ERR;
9370 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009371
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009372 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009373 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009374
9375 /* TODO: later accept arguments. */
9376 rule->arg.hlua_rule->args = NULL;
9377
9378 /* Add applet pointer in the rule. */
9379 rule->applet.obj_type = OBJ_TYPE_APPLET;
9380 rule->applet.name = fcn->name;
9381 rule->applet.init = hlua_applet_tcp_init;
9382 rule->applet.fct = hlua_applet_tcp_fct;
9383 rule->applet.release = hlua_applet_tcp_release;
9384 rule->applet.timeout = hlua_timeout_applet;
9385
9386 return 0;
9387}
9388
9389/* This function is an LUA binding used for registering
9390 * "sample-conv" functions. It expects a converter name used
9391 * in the haproxy configuration file, and an LUA function.
9392 */
9393__LJMP static int hlua_register_service(lua_State *L)
9394{
9395 struct action_kw_list *akl;
9396 const char *name;
9397 const char *env;
9398 int ref;
9399 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009400 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009401 struct buffer *trash;
9402 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009403
9404 MAY_LJMP(check_args(L, 3, "register_service"));
9405
9406 /* First argument : converter name. */
9407 name = MAY_LJMP(luaL_checkstring(L, 1));
9408
9409 /* Second argument : environment. */
9410 env = MAY_LJMP(luaL_checkstring(L, 2));
9411
9412 /* Third argument : lua function. */
9413 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9414
Thierry Fournierf67442e2020-11-28 20:41:07 +01009415 /* Check for service already registered */
9416 trash = get_trash_chunk();
9417 chunk_printf(trash, "lua.%s", name);
9418 akw = service_find(trash->area);
9419 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009420 fcn = akw->private;
9421 if (fcn->function_ref[hlua_state_id] != -1) {
9422 ha_warning("Trying to register service 'lua.%s' more than once. "
9423 "This will become a hard error in version 2.5.\n", name);
9424 }
9425 fcn->function_ref[hlua_state_id] = ref;
9426 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009427 }
9428
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009429 /* Allocate and fill the sample fetch keyword struct. */
9430 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9431 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009432 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009433 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009434 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009435 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009436
9437 /* Fill fcn. */
9438 len = strlen("<lua.>") + strlen(name) + 1;
9439 fcn->name = calloc(1, len);
9440 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009441 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009442 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009443 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009444
9445 /* List head */
9446 akl->list.n = akl->list.p = NULL;
9447
9448 /* converter keyword. */
9449 len = strlen("lua.") + strlen(name) + 1;
9450 akl->kw[0].kw = calloc(1, len);
9451 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009452 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009453
9454 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9455
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009456 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009457 if (strcmp(env, "tcp") == 0)
9458 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009459 else if (strcmp(env, "http") == 0)
9460 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009461 else {
9462 release_hlua_function(fcn);
9463 if (akl)
9464 ha_free((char **)&(akl->kw[0].kw));
9465 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009466 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009467 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009468 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009469
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009470 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009471 akl->kw[0].private = fcn;
9472
9473 /* End of array. */
9474 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9475
9476 /* Register this new converter */
9477 service_keywords_register(akl);
9478
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009479 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009480
9481 alloc_error:
9482 release_hlua_function(fcn);
9483 ha_free(&akl);
9484 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9485 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009486}
9487
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009488/* This function initialises Lua cli handler. It copies the
9489 * arguments in the Lua stack and create channel IO objects.
9490 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02009491static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009492{
9493 struct hlua *hlua;
9494 struct hlua_function *fcn;
9495 int i;
9496 const char *error;
9497
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009498 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009499 appctx->ctx.hlua_cli.fcn = private;
9500
Willy Tarreaubafbe012017-11-24 17:34:44 +01009501 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009502 if (!hlua) {
9503 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009504 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009505 }
9506 HLUA_INIT(hlua);
9507 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009508
9509 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05009510 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009511 * applet_http. It is absolutely compatible.
9512 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01009513 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009514 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01009515 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009516 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009517 }
9518 appctx->ctx.hlua_cli.task->nice = 0;
9519 appctx->ctx.hlua_cli.task->context = appctx;
9520 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
9521
9522 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +01009523 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009524 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009525 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009526 }
9527
9528 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009529 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009530 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9531 error = lua_tostring(hlua->T, -1);
9532 else
9533 error = "critical error";
9534 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
9535 goto error;
9536 }
9537
9538 /* Check stack available size. */
9539 if (!lua_checkstack(hlua->T, 2)) {
9540 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9541 goto error;
9542 }
9543
9544 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009545 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009546
9547 /* Once the arguments parsed, the CLI is like an AppletTCP,
9548 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009549 */
9550 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
9551 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9552 goto error;
9553 }
9554 hlua->nargs = 1;
9555
9556 /* push keywords in the stack. */
9557 for (i = 0; *args[i]; i++) {
9558 /* Check stack available size. */
9559 if (!lua_checkstack(hlua->T, 1)) {
9560 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9561 goto error;
9562 }
9563 lua_pushstring(hlua->T, args[i]);
9564 hlua->nargs++;
9565 }
9566
9567 /* We must initialize the execution timeouts. */
9568 hlua->max_time = hlua_timeout_session;
9569
9570 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009571 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009572
9573 /* It's ok */
9574 return 0;
9575
9576 /* It's not ok. */
9577error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009578 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009579 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009580 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009581 return 1;
9582}
9583
9584static int hlua_cli_io_handler_fct(struct appctx *appctx)
9585{
9586 struct hlua *hlua;
9587 struct stream_interface *si;
9588 struct hlua_function *fcn;
9589
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009590 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009591 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01009592 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009593
9594 /* If the stream is disconnect or closed, ldo nothing. */
9595 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9596 return 1;
9597
9598 /* Execute the function. */
9599 switch (hlua_ctx_resume(hlua, 1)) {
9600
9601 /* finished. */
9602 case HLUA_E_OK:
9603 return 1;
9604
9605 /* yield. */
9606 case HLUA_E_AGAIN:
9607 /* We want write. */
9608 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01009609 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009610 /* Set the timeout. */
9611 if (hlua->wake_time != TICK_ETERNITY)
9612 task_schedule(hlua->task, hlua->wake_time);
9613 return 0;
9614
9615 /* finished with error. */
9616 case HLUA_E_ERRMSG:
9617 /* Display log. */
9618 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
9619 fcn->name, lua_tostring(hlua->T, -1));
9620 lua_pop(hlua->T, 1);
9621 return 1;
9622
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009623 case HLUA_E_ETMOUT:
9624 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
9625 fcn->name);
9626 return 1;
9627
9628 case HLUA_E_NOMEM:
9629 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
9630 fcn->name);
9631 return 1;
9632
9633 case HLUA_E_YIELD: /* unexpected */
9634 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
9635 fcn->name);
9636 return 1;
9637
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009638 case HLUA_E_ERR:
9639 /* Display log. */
9640 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
9641 fcn->name);
9642 return 1;
9643
9644 default:
9645 return 1;
9646 }
9647
9648 return 1;
9649}
9650
9651static void hlua_cli_io_release_fct(struct appctx *appctx)
9652{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009653 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009654 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009655}
9656
9657/* This function is an LUA binding used for registering
9658 * new keywords in the cli. It expects a list of keywords
9659 * which are the "path". It is limited to 5 keywords. A
9660 * description of the command, a function to be executed
9661 * for the parsing and a function for io handlers.
9662 */
9663__LJMP static int hlua_register_cli(lua_State *L)
9664{
9665 struct cli_kw_list *cli_kws;
9666 const char *message;
9667 int ref_io;
9668 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009669 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009670 int index;
9671 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009672 struct buffer *trash;
9673 const char *kw[5];
9674 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009675 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009676
9677 MAY_LJMP(check_args(L, 3, "register_cli"));
9678
9679 /* First argument : an array of maximum 5 keywords. */
9680 if (!lua_istable(L, 1))
9681 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
9682
9683 /* Second argument : string with contextual message. */
9684 message = MAY_LJMP(luaL_checkstring(L, 2));
9685
9686 /* Third and fourth argument : lua function. */
9687 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
9688
Thierry Fournierf67442e2020-11-28 20:41:07 +01009689 /* Check for CLI service already registered */
9690 trash = get_trash_chunk();
9691 index = 0;
9692 lua_pushnil(L);
9693 memset(kw, 0, sizeof(kw));
9694 while (lua_next(L, 1) != 0) {
9695 if (index >= CLI_PREFIX_KW_NB)
9696 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
9697 if (lua_type(L, -1) != LUA_TSTRING)
9698 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
9699 kw[index] = lua_tostring(L, -1);
9700 if (index == 0)
9701 chunk_printf(trash, "%s", kw[index]);
9702 else
9703 chunk_appendf(trash, " %s", kw[index]);
9704 index++;
9705 lua_pop(L, 1);
9706 }
9707 cli_kw = cli_find_kw_exact((char **)kw);
9708 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009709 fcn = cli_kw->private;
9710 if (fcn->function_ref[hlua_state_id] != -1) {
9711 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
9712 "This will become a hard error in version 2.5.\n", trash->area);
9713 }
9714 fcn->function_ref[hlua_state_id] = ref_io;
9715 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009716 }
9717
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009718 /* Allocate and fill the sample fetch keyword struct. */
9719 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009720 if (!cli_kws) {
9721 errmsg = "Lua out of memory error.";
9722 goto error;
9723 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009724 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009725 if (!fcn) {
9726 errmsg = "Lua out of memory error.";
9727 goto error;
9728 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009729
9730 /* Fill path. */
9731 index = 0;
9732 lua_pushnil(L);
9733 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009734 if (index >= 5) {
9735 errmsg = "1st argument must be a table with a maximum of 5 entries";
9736 goto error;
9737 }
9738 if (lua_type(L, -1) != LUA_TSTRING) {
9739 errmsg = "1st argument must be a table filled with strings";
9740 goto error;
9741 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009742 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009743 if (!cli_kws->kw[0].str_kw[index]) {
9744 errmsg = "Lua out of memory error.";
9745 goto error;
9746 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009747 index++;
9748 lua_pop(L, 1);
9749 }
9750
9751 /* Copy help message. */
9752 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009753 if (!cli_kws->kw[0].usage) {
9754 errmsg = "Lua out of memory error.";
9755 goto error;
9756 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009757
9758 /* Fill fcn io handler. */
9759 len = strlen("<lua.cli>") + 1;
9760 for (i = 0; i < index; i++)
9761 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
9762 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009763 if (!fcn->name) {
9764 errmsg = "Lua out of memory error.";
9765 goto error;
9766 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009767 strncat((char *)fcn->name, "<lua.cli", len);
9768 for (i = 0; i < index; i++) {
9769 strncat((char *)fcn->name, ".", len);
9770 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
9771 }
9772 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +01009773 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009774
9775 /* Fill last entries. */
9776 cli_kws->kw[0].private = fcn;
9777 cli_kws->kw[0].parse = hlua_cli_parse_fct;
9778 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
9779 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
9780
9781 /* Register this new converter */
9782 cli_register_kw(cli_kws);
9783
9784 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009785
9786 error:
9787 release_hlua_function(fcn);
9788 if (cli_kws) {
9789 for (i = 0; i < index; i++)
9790 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
9791 ha_free((char **)&(cli_kws->kw[0].usage));
9792 }
9793 ha_free(&cli_kws);
9794 WILL_LJMP(luaL_error(L, errmsg));
9795 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009796}
9797
Christopher Faulet69c581a2021-05-31 08:54:04 +02009798static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
9799{
9800 struct hlua_flt_config *conf = fconf->conf;
9801 lua_State *L;
9802 int error, pos, state_id, flt_ref;
9803
9804 state_id = reg_flt_to_stack_id(conf->reg);
9805 L = hlua_states[state_id];
9806 pos = lua_gettop(L);
9807
9808 /* The filter parsing function */
9809 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
9810
9811 /* Push the filter class on the stack and resolve all callbacks */
9812 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
9813
9814 /* Duplicate the filter class so each filter will have its own copy */
9815 lua_newtable(L);
9816 lua_pushnil(L);
9817
9818 while (lua_next(L, pos+2)) {
9819 lua_pushvalue(L, -2);
9820 lua_insert(L, -2);
9821 lua_settable(L, -4);
9822 }
9823 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
9824
9825 /* Remove the original lua filter class from the stack */
9826 lua_pop(L, 1);
9827
9828 /* Push the copy on the stack */
9829 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
9830
9831 /* extra args are pushed in a table */
9832 lua_newtable(L);
9833 for (pos = 0; conf->args[pos]; pos++) {
9834 /* Check stack available size. */
9835 if (!lua_checkstack(L, 1)) {
9836 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
9837 goto error;
9838 }
9839 lua_pushstring(L, conf->args[pos]);
9840 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
9841 }
9842
9843 error = lua_pcall(L, 2, LUA_MULTRET, 0);
9844 switch (error) {
9845 case LUA_OK:
9846 /* replace the filter ref */
9847 conf->ref[state_id] = flt_ref;
9848 break;
9849 case LUA_ERRRUN:
9850 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
9851 goto error;
9852 case LUA_ERRMEM:
9853 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
9854 goto error;
9855 case LUA_ERRERR:
9856 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
9857 goto error;
9858#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
9859 case LUA_ERRGCMM:
9860 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
9861 goto error;
9862#endif
9863 default:
9864 ha_alert("Lua filter '%s' : unknonwn error : %s", conf->reg->name, lua_tostring(L, -1));
9865 goto error;
9866 }
9867
9868 lua_settop(L, 0);
9869 return 0;
9870
9871 error:
9872 lua_settop(L, 0);
9873 return -1;
9874}
9875
9876static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
9877{
9878 struct hlua_flt_config *conf = fconf->conf;
9879 lua_State *L;
9880 int state_id;
9881
9882 if (!conf)
9883 return;
9884
9885 state_id = reg_flt_to_stack_id(conf->reg);
9886 L = hlua_states[state_id];
9887 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
9888}
9889
9890static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
9891{
9892 struct hlua_flt_config *conf = fconf->conf;
9893 int state_id = reg_flt_to_stack_id(conf->reg);
9894
9895 /* Rely on per-thread init for global scripts */
9896 if (!state_id)
9897 return hlua_filter_init_per_thread(px, fconf);
9898 return 0;
9899}
9900
9901static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
9902{
9903
9904 if (fconf->conf) {
9905 struct hlua_flt_config *conf = fconf->conf;
9906 int state_id = reg_flt_to_stack_id(conf->reg);
9907 int pos;
9908
9909 /* Rely on per-thread deinit for global scripts */
9910 if (!state_id)
9911 hlua_filter_deinit_per_thread(px, fconf);
9912
9913 for (pos = 0; conf->args[pos]; pos++)
9914 free(conf->args[pos]);
9915 free(conf->args);
9916 }
9917 ha_free(&fconf->conf);
9918 ha_free((char **)&fconf->id);
9919 ha_free(&fconf->ops);
9920}
9921
9922static int hlua_filter_new(struct stream *s, struct filter *filter)
9923{
9924 struct hlua_flt_config *conf = FLT_CONF(filter);
9925 struct hlua_flt_ctx *flt_ctx = NULL;
9926 int ret = 1;
9927
9928 /* In the execution wrappers linked with a stream, the
9929 * Lua context can be not initialized. This behavior
9930 * permits to save performances because a systematic
9931 * Lua initialization cause 5% performances loss.
9932 */
9933 if (!s->hlua) {
9934 struct hlua *hlua;
9935
9936 hlua = pool_alloc(pool_head_hlua);
9937 if (!hlua) {
9938 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9939 conf->reg->name);
9940 ret = 0;
9941 goto end;
9942 }
9943 HLUA_INIT(hlua);
9944 s->hlua = hlua;
9945 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9946 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9947 conf->reg->name);
9948 ret = 0;
9949 goto end;
9950 }
9951 }
9952
9953 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
9954 if (!flt_ctx) {
9955 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9956 conf->reg->name);
9957 ret = 0;
9958 goto end;
9959 }
9960 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
9961 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
9962 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
9963 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9964 conf->reg->name);
9965 ret = 0;
9966 goto end;
9967 }
9968 HLUA_INIT(flt_ctx->hlua[0]);
9969 HLUA_INIT(flt_ctx->hlua[1]);
9970 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
9971 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9972 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9973 conf->reg->name);
9974 ret = 0;
9975 goto end;
9976 }
9977
9978 if (!HLUA_IS_RUNNING(s->hlua)) {
9979 /* The following Lua calls can fail. */
9980 if (!SET_SAFE_LJMP(s->hlua)) {
9981 const char *error;
9982
9983 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9984 error = lua_tostring(s->hlua->T, -1);
9985 else
9986 error = "critical error";
9987 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
9988 ret = 0;
9989 goto end;
9990 }
9991
9992 /* Check stack size. */
9993 if (!lua_checkstack(s->hlua->T, 1)) {
9994 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
9995 ret = 0;
9996 goto end;
9997 }
9998
9999 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10000 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10001 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10002 conf->reg->name);
10003 RESET_SAFE_LJMP(s->hlua);
10004 ret = 0;
10005 goto end;
10006 }
10007 lua_insert(s->hlua->T, -2);
10008
10009 /* Push the copy on the stack */
10010 s->hlua->nargs = 1;
10011
10012 /* We must initialize the execution timeouts. */
10013 s->hlua->max_time = hlua_timeout_session;
10014
10015 /* At this point the execution is safe. */
10016 RESET_SAFE_LJMP(s->hlua);
10017 }
10018
10019 switch (hlua_ctx_resume(s->hlua, 0)) {
10020 case HLUA_E_OK:
10021 /* Nothing returned or not a table, ignore the filter for current stream */
10022 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10023 ret = 0;
10024 goto end;
10025 }
10026
10027 /* Attached the filter pointer to the ctx */
10028 lua_pushstring(s->hlua->T, "__filter");
10029 lua_pushlightuserdata(s->hlua->T, filter);
10030 lua_settable(s->hlua->T, -3);
10031
10032 /* Save a ref on the filter ctx */
10033 lua_pushvalue(s->hlua->T, 1);
10034 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10035 filter->ctx = flt_ctx;
10036 break;
10037 case HLUA_E_ERRMSG:
10038 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10039 ret = -1;
10040 goto end;
10041 case HLUA_E_ETMOUT:
10042 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10043 ret = 0;
10044 goto end;
10045 case HLUA_E_NOMEM:
10046 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10047 ret = 0;
10048 goto end;
10049 case HLUA_E_AGAIN:
10050 case HLUA_E_YIELD:
10051 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10052 " are not allowed from 'new' function.\n", conf->reg->name);
10053 ret = 0;
10054 goto end;
10055 case HLUA_E_ERR:
10056 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10057 ret = 0;
10058 goto end;
10059 default:
10060 ret = 0;
10061 goto end;
10062 }
10063
10064 end:
10065 if (s->hlua)
10066 lua_settop(s->hlua->T, 0);
10067 if (ret <= 0) {
10068 if (flt_ctx) {
10069 hlua_ctx_destroy(flt_ctx->hlua[0]);
10070 hlua_ctx_destroy(flt_ctx->hlua[1]);
10071 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10072 }
10073 }
10074 return ret;
10075}
10076
10077static void hlua_filter_delete(struct stream *s, struct filter *filter)
10078{
10079 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10080
10081 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10082 hlua_ctx_destroy(flt_ctx->hlua[0]);
10083 hlua_ctx_destroy(flt_ctx->hlua[1]);
10084 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10085 filter->ctx = NULL;
10086}
10087
Christopher Faulet9f55a502020-02-25 15:21:02 +010010088static int hlua_filter_from_payload(struct filter *filter)
10089{
10090 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10091
10092 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10093}
10094
Christopher Fauletc404f112020-02-26 15:03:09 +010010095static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10096 int dir, unsigned int flags)
10097{
10098 struct hlua *flt_hlua;
10099 struct hlua_flt_config *conf = FLT_CONF(filter);
10100 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10101 unsigned int hflags = HLUA_TXN_FLT_CTX;
10102 int ret = 1;
10103
10104 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10105 if (!flt_hlua)
10106 goto end;
10107
10108 if (!HLUA_IS_RUNNING(flt_hlua)) {
10109 int extra_idx = lua_gettop(flt_hlua->T);
10110
10111 /* The following Lua calls can fail. */
10112 if (!SET_SAFE_LJMP(flt_hlua)) {
10113 const char *error;
10114
10115 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10116 error = lua_tostring(flt_hlua->T, -1);
10117 else
10118 error = "critical error";
10119 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10120 goto end;
10121 }
10122
10123 /* Check stack size. */
10124 if (!lua_checkstack(flt_hlua->T, 3)) {
10125 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10126 RESET_SAFE_LJMP(flt_hlua);
10127 goto end;
10128 }
10129
10130 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10131 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10132 RESET_SAFE_LJMP(flt_hlua);
10133 goto end;
10134 }
10135 lua_insert(flt_hlua->T, -2);
10136
10137 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10138 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10139 RESET_SAFE_LJMP(flt_hlua);
10140 goto end;
10141 }
10142 flt_hlua->nargs = 2;
10143
10144 if (flags & HLUA_FLT_CB_ARG_CHN) {
10145 if (dir == SMP_OPT_DIR_REQ)
10146 lua_getfield(flt_hlua->T, -1, "req");
10147 else
10148 lua_getfield(flt_hlua->T, -1, "res");
10149 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10150 lua_pushstring(flt_hlua->T, "__filter");
10151 lua_pushlightuserdata(flt_hlua->T, filter);
10152 lua_settable(flt_hlua->T, -3);
10153 }
10154 flt_hlua->nargs++;
10155 }
10156 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010157 if (dir == SMP_OPT_DIR_REQ)
10158 lua_getfield(flt_hlua->T, -1, "http_req");
10159 else
10160 lua_getfield(flt_hlua->T, -1, "http_res");
10161 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10162 lua_pushstring(flt_hlua->T, "__filter");
10163 lua_pushlightuserdata(flt_hlua->T, filter);
10164 lua_settable(flt_hlua->T, -3);
10165 }
10166 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010167 }
10168
10169 /* Check stack size. */
10170 if (!lua_checkstack(flt_hlua->T, 1)) {
10171 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10172 RESET_SAFE_LJMP(flt_hlua);
10173 goto end;
10174 }
10175
10176 while (extra_idx--) {
10177 lua_pushvalue(flt_hlua->T, 1);
10178 lua_remove(flt_hlua->T, 1);
10179 flt_hlua->nargs++;
10180 }
10181
10182 /* We must initialize the execution timeouts. */
10183 flt_hlua->max_time = hlua_timeout_session;
10184
10185 /* At this point the execution is safe. */
10186 RESET_SAFE_LJMP(flt_hlua);
10187 }
10188
10189 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10190 case HLUA_E_OK:
10191 /* Catch the return value if it required */
10192 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10193 ret = lua_tointeger(flt_hlua->T, -1);
10194 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10195 }
10196
10197 /* Set timeout in the required channel. */
10198 if (flt_hlua->wake_time != TICK_ETERNITY) {
10199 if (dir == SMP_OPT_DIR_REQ)
10200 s->req.analyse_exp = flt_hlua->wake_time;
10201 else
10202 s->res.analyse_exp = flt_hlua->wake_time;
10203 }
10204 break;
10205 case HLUA_E_AGAIN:
10206 /* Set timeout in the required channel. */
10207 if (flt_hlua->wake_time != TICK_ETERNITY) {
10208 if (dir == SMP_OPT_DIR_REQ)
10209 s->req.analyse_exp = flt_hlua->wake_time;
10210 else
10211 s->res.analyse_exp = flt_hlua->wake_time;
10212 }
10213 /* Some actions can be wake up when a "write" event
10214 * is detected on a response channel. This is useful
10215 * only for actions targeted on the requests.
10216 */
10217 if (HLUA_IS_WAKERESWR(flt_hlua))
10218 s->res.flags |= CF_WAKE_WRITE;
10219 if (HLUA_IS_WAKEREQWR(flt_hlua))
10220 s->req.flags |= CF_WAKE_WRITE;
10221 ret = 0;
10222 goto end;
10223 case HLUA_E_ERRMSG:
10224 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10225 ret = -1;
10226 goto end;
10227 case HLUA_E_ETMOUT:
10228 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10229 goto end;
10230 case HLUA_E_NOMEM:
10231 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10232 goto end;
10233 case HLUA_E_YIELD:
10234 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10235 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10236 goto end;
10237 case HLUA_E_ERR:
10238 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10239 goto end;
10240 default:
10241 goto end;
10242 }
10243
10244
10245 end:
10246 return ret;
10247}
10248
10249static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10250{
10251 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10252
10253 flt_ctx->flags = 0;
10254 return hlua_filter_callback(s, filter, "start_analyze",
10255 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10256 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10257}
10258
10259static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10260{
10261 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10262
10263 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10264 return hlua_filter_callback(s, filter, "end_analyze",
10265 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10266 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10267}
10268
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010269static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10270{
10271 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10272
10273 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10274 return hlua_filter_callback(s, filter, "http_headers",
10275 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10276 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10277}
10278
10279static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10280 unsigned int offset, unsigned int len)
10281{
10282 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10283 struct hlua *flt_hlua;
10284 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10285 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10286 int ret;
10287
10288 flt_hlua = flt_ctx->hlua[idx];
10289 flt_ctx->cur_off[idx] = offset;
10290 flt_ctx->cur_len[idx] = len;
10291 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10292 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10293 if (ret != -1) {
10294 ret = flt_ctx->cur_len[idx];
10295 if (lua_gettop(flt_hlua->T) > 0) {
10296 ret = lua_tointeger(flt_hlua->T, -1);
10297 if (ret > flt_ctx->cur_len[idx])
10298 ret = flt_ctx->cur_len[idx];
10299 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10300 }
10301 }
10302 return ret;
10303}
10304
10305static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10306{
10307 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10308
10309 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10310 return hlua_filter_callback(s, filter, "http_end",
10311 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10312 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10313}
10314
Christopher Fauletc404f112020-02-26 15:03:09 +010010315static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10316 unsigned int offset, unsigned int len)
10317{
10318 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10319 struct hlua *flt_hlua;
10320 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10321 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10322 int ret;
10323
10324 flt_hlua = flt_ctx->hlua[idx];
10325 flt_ctx->cur_off[idx] = offset;
10326 flt_ctx->cur_len[idx] = len;
10327 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10328 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10329 if (ret != -1) {
10330 ret = flt_ctx->cur_len[idx];
10331 if (lua_gettop(flt_hlua->T) > 0) {
10332 ret = lua_tointeger(flt_hlua->T, -1);
10333 if (ret > flt_ctx->cur_len[idx])
10334 ret = flt_ctx->cur_len[idx];
10335 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10336 }
10337 }
10338 return ret;
10339}
10340
Christopher Faulet69c581a2021-05-31 08:54:04 +020010341static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10342 struct flt_conf *fconf, char **err, void *private)
10343{
10344 struct hlua_reg_filter *reg_flt = private;
10345 lua_State *L;
10346 struct hlua_flt_config *conf = NULL;
10347 const char *flt_id = NULL;
10348 int state_id, pos, flt_flags = 0;
10349 struct flt_ops *hlua_flt_ops = NULL;
10350
10351 state_id = reg_flt_to_stack_id(reg_flt);
10352 L = hlua_states[state_id];
10353
10354 /* Initialize the filter ops with default callbacks */
10355 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
10356 if (!hlua_flt_ops) {
10357 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
10358 return -1;
10359 }
10360 hlua_flt_ops->init = hlua_filter_init;
10361 hlua_flt_ops->deinit = hlua_filter_deinit;
10362 if (state_id) {
10363 /* Set per-thread callback if script is loaded per-thread */
10364 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10365 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10366 }
10367 hlua_flt_ops->attach = hlua_filter_new;
10368 hlua_flt_ops->detach = hlua_filter_delete;
10369
10370 /* Push the filter class on the stack and resolve all callbacks */
10371 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10372
Christopher Fauletc404f112020-02-26 15:03:09 +010010373 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10374 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10375 lua_pop(L, 1);
10376 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10377 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10378 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010379 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10380 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10381 lua_pop(L, 1);
10382 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10383 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10384 lua_pop(L, 1);
10385 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10386 hlua_flt_ops->http_end = hlua_filter_http_end;
10387 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010388 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10389 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10390 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010391
10392 /* Get id and flags of the filter class */
10393 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10394 flt_id = lua_tostring(L, -1);
10395 lua_pop(L, 1);
10396 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10397 flt_flags = lua_tointeger(L, -1);
10398 lua_pop(L, 1);
10399
10400 /* Create the filter config */
10401 conf = calloc(1, sizeof(*conf));
10402 if (!conf) {
10403 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
10404 goto error;
10405 }
10406 conf->reg = reg_flt;
10407
10408 /* duplicate args */
10409 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10410 conf->args = calloc(pos + 1, sizeof(*conf->args));
10411 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++)
10412 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
10413 conf->args[pos] = NULL;
10414 *cur_arg += pos + 1;
10415
10416 fconf->id = strdup(flt_id);
10417 fconf->flags = flt_flags;
10418 fconf->conf = conf;
10419 fconf->ops = hlua_flt_ops;
10420
10421 lua_settop(L, 0);
10422 return 0;
10423
10424 error:
10425 free(hlua_flt_ops);
10426 free(conf);
10427 lua_settop(L, 0);
10428 return -1;
10429}
10430
Christopher Fauletc404f112020-02-26 15:03:09 +010010431__LJMP static int hlua_register_data_filter(lua_State *L)
10432{
10433 struct filter *filter;
10434 struct channel *chn;
10435
10436 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10437 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10438 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10439
10440 lua_getfield(L, 1, "__filter");
10441 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10442 filter = lua_touserdata (L, -1);
10443 lua_pop(L, 1);
10444
10445 register_data_filter(chn_strm(chn), chn, filter);
10446 return 1;
10447}
10448
10449__LJMP static int hlua_unregister_data_filter(lua_State *L)
10450{
10451 struct filter *filter;
10452 struct channel *chn;
10453
10454 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10455 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10456 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10457
10458 lua_getfield(L, 1, "__filter");
10459 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10460 filter = lua_touserdata (L, -1);
10461 lua_pop(L, 1);
10462
10463 unregister_data_filter(chn_strm(chn), chn, filter);
10464 return 1;
10465}
10466
Christopher Faulet69c581a2021-05-31 08:54:04 +020010467/* This function is an LUA binding used for registering a filter. It expects a
10468 * fileter name used in the haproxy configuration file and a LUA function to
10469 * parse configuration arguments.
10470 */
10471__LJMP static int hlua_register_filter(lua_State *L)
10472{
10473 struct buffer *trash;
10474 struct flt_kw_list *fkl;
10475 struct flt_kw *fkw;
10476 const char *name;
10477 struct hlua_reg_filter *reg_flt= NULL;
10478 int flt_ref, fun_ref;
10479 int len;
10480
10481 MAY_LJMP(check_args(L, 3, "register_filter"));
10482
10483 /* First argument : filter name. */
10484 name = MAY_LJMP(luaL_checkstring(L, 1));
10485
10486 /* Second argument : The filter class */
10487 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
10488
10489 /* Third argument : lua function. */
10490 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
10491
10492 trash = get_trash_chunk();
10493 chunk_printf(trash, "lua.%s", name);
10494 fkw = flt_find_kw(trash->area);
10495 if (fkw != NULL) {
10496 reg_flt = fkw->private;
10497 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
10498 ha_warning("Trying to register filter 'lua.%s' more than once. "
10499 "This will become a hard error in version 2.5.\n", name);
10500 }
10501 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10502 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10503 return 0;
10504 }
10505
10506 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
10507 if (!fkl)
10508 goto alloc_error;
10509 fkl->scope = "HLUA";
10510
10511 reg_flt = new_hlua_reg_filter(name);
10512 if (!reg_flt)
10513 goto alloc_error;
10514
10515 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10516 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10517
10518 /* The filter keyword */
10519 len = strlen("lua.") + strlen(name) + 1;
10520 fkl->kw[0].kw = calloc(1, len);
10521 if (!fkl->kw[0].kw)
10522 goto alloc_error;
10523
10524 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
10525
10526 fkl->kw[0].parse = hlua_filter_parse_fct;
10527 fkl->kw[0].private = reg_flt;
10528 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
10529
10530 /* Register this new filter */
10531 flt_register_keywords(fkl);
10532
10533 return 0;
10534
10535 alloc_error:
10536 release_hlua_reg_filter(reg_flt);
10537 ha_free(&fkl);
10538 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10539 return 0; /* Never reached */
10540}
10541
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010542static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010543 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010544 char **err, unsigned int *timeout)
10545{
10546 const char *error;
10547
10548 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020010549 if (error == PARSE_TIME_OVER) {
10550 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
10551 args[1], args[0]);
10552 return -1;
10553 }
10554 else if (error == PARSE_TIME_UNDER) {
10555 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
10556 args[1], args[0]);
10557 return -1;
10558 }
10559 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010560 memprintf(err, "%s: invalid timeout", args[0]);
10561 return -1;
10562 }
10563 return 0;
10564}
10565
10566static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010567 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010568 char **err)
10569{
10570 return hlua_read_timeout(args, section_type, curpx, defpx,
10571 file, line, err, &hlua_timeout_session);
10572}
10573
10574static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010575 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010576 char **err)
10577{
10578 return hlua_read_timeout(args, section_type, curpx, defpx,
10579 file, line, err, &hlua_timeout_task);
10580}
10581
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010582static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010583 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010584 char **err)
10585{
10586 return hlua_read_timeout(args, section_type, curpx, defpx,
10587 file, line, err, &hlua_timeout_applet);
10588}
10589
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010590static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010591 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010592 char **err)
10593{
10594 char *error;
10595
10596 hlua_nb_instruction = strtoll(args[1], &error, 10);
10597 if (*error != '\0') {
10598 memprintf(err, "%s: invalid number", args[0]);
10599 return -1;
10600 }
10601 return 0;
10602}
10603
Willy Tarreau32f61e22015-03-18 17:54:59 +010010604static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010605 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010010606 char **err)
10607{
10608 char *error;
10609
10610 if (*(args[1]) == 0) {
10611 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
10612 return -1;
10613 }
10614 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
10615 if (*error != '\0') {
10616 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
10617 return -1;
10618 }
10619 return 0;
10620}
10621
10622
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010623/* This function is called by the main configuration key "lua-load". It loads and
10624 * execute an lua file during the parsing of the HAProxy configuration file. It is
10625 * the main lua entry point.
10626 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010627 * This function runs with the HAProxy keywords API. It returns -1 if an error
10628 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010629 *
10630 * In some error case, LUA set an error message in top of the stack. This function
10631 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010632 *
10633 * This function can fail with an abort() due to an Lua critical error.
10634 * We are in the configuration parsing process of HAProxy, this abort() is
10635 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010636 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010637static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010638{
10639 int error;
10640
10641 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010642 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010643 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010644 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
10645 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010646 return -1;
10647 }
10648
10649 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010650 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010651 switch (error) {
10652 case LUA_OK:
10653 break;
10654 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010655 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
10656 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010657 return -1;
10658 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010010659 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010660 return -1;
10661 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010662 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
10663 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010664 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010665#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010666 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010667 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
10668 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010669 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010670#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010671 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010672 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
10673 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010674 return -1;
10675 }
10676
10677 return 0;
10678}
10679
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010680static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010681 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010682 char **err)
10683{
10684 if (*(args[1]) == 0) {
10685 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
10686 return -1;
10687 }
10688
Thierry Fournier59f11be2020-11-29 00:37:41 +010010689 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010010690 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010691 ha_set_tid(0);
Thierry Fournierafc63e22020-11-28 17:06:51 +010010692 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010693}
10694
Thierry Fournier59f11be2020-11-29 00:37:41 +010010695static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010696 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010010697 char **err)
10698{
10699 int len;
10700
10701 if (*(args[1]) == 0) {
10702 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
10703 return -1;
10704 }
10705
10706 if (per_thread_load == NULL) {
10707 /* allocate the first entry large enough to store the final NULL */
10708 per_thread_load = calloc(1, sizeof(*per_thread_load));
10709 if (per_thread_load == NULL) {
10710 memprintf(err, "out of memory error");
10711 return -1;
10712 }
10713 }
10714
10715 /* count used entries */
10716 for (len = 0; per_thread_load[len] != NULL; len++)
10717 ;
10718
10719 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
10720 if (per_thread_load == NULL) {
10721 memprintf(err, "out of memory error");
10722 return -1;
10723 }
10724
10725 per_thread_load[len] = strdup(args[1]);
10726 per_thread_load[len + 1] = NULL;
10727
10728 if (per_thread_load[len] == NULL) {
10729 memprintf(err, "out of memory error");
10730 return -1;
10731 }
10732
10733 /* loading for thread 1 only */
10734 hlua_state_id = 1;
10735 ha_set_tid(0);
10736 return hlua_load_state(args[1], hlua_states[1], err);
10737}
10738
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010739/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
10740 * in the given <ctx>.
10741 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010742static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010743{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010744 lua_getglobal(L, "package"); /* push package variable */
10745 lua_pushstring(L, path); /* push given path */
10746 lua_pushstring(L, ";"); /* push semicolon */
10747 lua_getfield(L, -3, type); /* push old path */
10748 lua_concat(L, 3); /* concatenate to new path */
10749 lua_setfield(L, -2, type); /* store new path */
10750 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010751
10752 return 0;
10753}
10754
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010755static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010756 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010757 char **err)
10758{
10759 char *path;
10760 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010761 struct prepend_path *p = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010762
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010763 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010764 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010765 }
10766
10767 if (!(*args[1])) {
10768 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010769 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010770 }
10771 path = args[1];
10772
10773 if (*args[2]) {
10774 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
10775 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010776 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010777 }
10778 type = args[2];
10779 }
10780
Thierry Fournier59f11be2020-11-29 00:37:41 +010010781 p = calloc(1, sizeof(*p));
10782 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010783 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010784 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010785 }
10786 p->path = strdup(path);
10787 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010788 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010789 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010790 }
10791 p->type = strdup(type);
10792 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010793 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010794 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010795 }
Willy Tarreau2b718102021-04-21 07:32:39 +020010796 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010797
10798 hlua_prepend_path(hlua_states[0], type, path);
10799 hlua_prepend_path(hlua_states[1], type, path);
10800 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010801
10802err2:
10803 free(p->type);
10804 free(p->path);
10805err:
10806 free(p);
10807 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010808}
10809
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010810/* configuration keywords declaration */
10811static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010812 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010813 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010010814 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010815 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
10816 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020010817 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010818 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010010819 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010820 { 0, NULL, NULL },
10821}};
10822
Willy Tarreau0108d902018-11-25 19:14:37 +010010823INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
10824
Christopher Fauletafd8f102018-11-08 11:34:21 +010010825
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010826/* This function can fail with an abort() due to an Lua critical error.
10827 * We are in the initialisation process of HAProxy, this abort() is
10828 * tolerated.
10829 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010010830int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010831{
10832 struct hlua_init_function *init;
10833 const char *msg;
10834 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010835 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010010836 const char *kind;
10837 const char *trace;
10838 int return_status = 1;
10839#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
10840 int nres;
10841#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010842
Willy Tarreaucdb53462020-12-02 12:12:00 +010010843 /* disable memory limit checks if limit is not set */
10844 if (!hlua_global_allocator.limit)
10845 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
10846
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010847 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010010848 if (setjmp(safe_ljmp_env) != 0) {
10849 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010010850 if (lua_type(L, -1) == LUA_TSTRING)
10851 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010852 else
10853 error = "critical error";
10854 fprintf(stderr, "Lua post-init: %s.\n", error);
10855 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010010856 } else {
10857 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010858 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020010859
Thierry Fournierb8cef172020-11-28 15:37:17 +010010860 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010861
Thierry Fournierc7492592020-11-28 23:57:24 +010010862 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010010863 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010010864
10865#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010010866 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010010867#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010010868 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010010869#endif
10870 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010871 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010010872
10873 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010010874 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010010875 break;
Thierry Fournier670db242020-11-28 10:49:59 +010010876
10877 case LUA_ERRERR:
10878 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010879 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010880 case LUA_ERRRUN:
10881 if (!kind)
10882 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010010883 msg = lua_tostring(L, -1);
10884 lua_settop(L, 0); /* Empty the stack. */
10885 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010010886 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010010887 if (msg)
10888 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
10889 else
10890 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
10891 return_status = 0;
10892 break;
10893
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010894 default:
Thierry Fournier670db242020-11-28 10:49:59 +010010895 /* Unknown error */
10896 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010897 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010898 case LUA_YIELD:
10899 /* yield is not configured at this step, this state doesn't happen */
10900 if (!kind)
10901 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010902 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010903 case LUA_ERRMEM:
10904 if (!kind)
10905 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010010906 lua_settop(L, 0);
10907 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010010908 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010010909 ha_alert("Lua init: %s: %s\n", kind, trace);
10910 return_status = 0;
10911 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010912 }
Thierry Fournier670db242020-11-28 10:49:59 +010010913 if (!return_status)
10914 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010915 }
Thierry Fournier3c539322020-11-28 16:05:05 +010010916
10917 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010010918 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010919}
10920
Thierry Fournierb8cef172020-11-28 15:37:17 +010010921int hlua_post_init()
10922{
Thierry Fournier59f11be2020-11-29 00:37:41 +010010923 int ret;
10924 int i;
10925 int errors;
10926 char *err = NULL;
10927 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010928 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010929
Thierry Fournierb8cef172020-11-28 15:37:17 +010010930#if USE_OPENSSL
10931 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010010932 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010010933 int saved_used_backed = global.ssl_used_backend;
10934 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010010935 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010010936 global.ssl_used_backend = saved_used_backed;
10937 }
10938#endif
10939
Thierry Fournierc7492592020-11-28 23:57:24 +010010940 /* Perform post init of common thread */
10941 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010942 ha_set_tid(0);
10943 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
10944 if (ret == 0)
10945 return 0;
10946
10947 /* init remaining lua states and load files */
10948 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
10949
10950 /* set thread context */
10951 ha_set_tid(hlua_state_id - 1);
10952
10953 /* Init lua state */
10954 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
10955
10956 /* Load lua files */
10957 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
10958 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
10959 if (ret != 0) {
10960 ha_alert("Lua init: %s\n", err);
10961 return 0;
10962 }
10963 }
10964 }
10965
10966 /* Reset thread context */
10967 ha_set_tid(0);
10968
10969 /* Execute post init for all states */
10970 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
10971
10972 /* set thread context */
10973 ha_set_tid(hlua_state_id - 1);
10974
10975 /* run post init */
10976 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
10977 if (ret == 0)
10978 return 0;
10979 }
10980
10981 /* Reset thread context */
10982 ha_set_tid(0);
10983
10984 /* control functions registering. Each function must have:
10985 * - only the function_ref[0] set positive and all other to -1
10986 * - only the function_ref[0] set to -1 and all other positive
10987 * This ensure a same reference is not used both in shared
10988 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050010989 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010010990 * complicated to found for the end user.
10991 */
10992 errors = 0;
10993 list_for_each_entry(fcn, &referenced_functions, l) {
10994 ret = 0;
10995 for (i = 1; i < global.nbthread + 1; i++) {
10996 if (fcn->function_ref[i] == -1)
10997 ret--;
10998 else
10999 ret++;
11000 }
11001 if (abs(ret) != global.nbthread) {
11002 ha_alert("Lua function '%s' is not referenced in all thread. "
11003 "Expect function in all thread or in none thread.\n", fcn->name);
11004 errors++;
11005 continue;
11006 }
11007
11008 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011009 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11010 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011011 "exclusive.\n", fcn->name);
11012 errors++;
11013 }
11014 }
11015
Christopher Faulet69c581a2021-05-31 08:54:04 +020011016 /* Do the same with registered filters */
11017 list_for_each_entry(reg_flt, &referenced_filters, l) {
11018 ret = 0;
11019 for (i = 1; i < global.nbthread + 1; i++) {
11020 if (reg_flt->flt_ref[i] == -1)
11021 ret--;
11022 else
11023 ret++;
11024 }
11025 if (abs(ret) != global.nbthread) {
11026 ha_alert("Lua filter '%s' is not referenced in all thread. "
11027 "Expect function in all thread or in none thread.\n", reg_flt->name);
11028 errors++;
11029 continue;
11030 }
11031
11032 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11033 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11034 "and per-thread Lua context (through lua-load-per-thread). these two context "
11035 "exclusive.\n", fcn->name);
11036 errors++;
11037 }
11038 }
11039
11040
Thierry Fournier59f11be2020-11-29 00:37:41 +010011041 if (errors > 0)
11042 return 0;
11043
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011044 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011045 * -1 in order to have probably a segfault if someone use it
11046 */
11047 hlua_state_id = -1;
11048
11049 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011050}
11051
Willy Tarreau32f61e22015-03-18 17:54:59 +010011052/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11053 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11054 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011055 * allocation. <nsize> is the requested new size. A new allocation is
11056 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011057 * zero. This one verifies that the limits are respected but is optimized
11058 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011059 */
11060static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11061{
11062 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011063 size_t limit, old, new;
11064
Tim Duesterhus22586522021-01-08 10:35:33 +010011065 if (unlikely(!ptr && !nsize))
11066 return NULL;
11067
Willy Tarreaucdb53462020-12-02 12:12:00 +010011068 /* a limit of ~0 means unlimited and boot complete, so there's no need
11069 * for accounting anymore.
11070 */
Christopher Fauletcc2c4f82021-03-24 14:52:24 +010011071 if (likely(~zone->limit == 0))
11072 return realloc(ptr, nsize);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011073
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011074 if (!ptr)
11075 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011076
Willy Tarreaucdb53462020-12-02 12:12:00 +010011077 /* enforce strict limits across all threads */
11078 limit = zone->limit;
11079 old = _HA_ATOMIC_LOAD(&zone->allocated);
11080 do {
11081 new = old + nsize - osize;
11082 if (unlikely(nsize && limit && new > limit))
11083 return NULL;
11084 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011085
11086 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011087
11088 if (unlikely(!ptr && nsize)) // failed
11089 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11090
11091 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011092 return ptr;
11093}
11094
Thierry Fournierecb83c22020-11-28 15:49:44 +010011095/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011096 * We are in the initialisation process of HAProxy, this abort() is
11097 * tolerated.
11098 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011099lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011100{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011101 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011102 int idx;
11103 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011104 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011105 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011106 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011107 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011108 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011109 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011110
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011111 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011112 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011113
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011114 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011115 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011116 *context = NULL;
11117
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011118 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011119 * the Lua function can fail with an abort. We are in the initialisation
11120 * process of HAProxy, this abort() is tolerated.
11121 */
11122
Thierry Fournier3c539322020-11-28 16:05:05 +010011123 /* Call post initialisation function in safe environment. */
11124 if (setjmp(safe_ljmp_env) != 0) {
11125 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011126 if (lua_type(L, -1) == LUA_TSTRING)
11127 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011128 else
11129 error_msg = "critical error";
11130 fprintf(stderr, "Lua init: %s.\n", error_msg);
11131 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011132 } else {
11133 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011134 }
11135
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011136 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011137 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011138#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11139#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11140#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011141 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011142#endif
11143#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011144 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011145#endif
11146#undef HLUA_PREPEND_PATH_TOSTRING
11147#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011148
Thierry Fournier59f11be2020-11-29 00:37:41 +010011149 /* Apply configured prepend path */
11150 list_for_each_entry(pp, &prepend_path_list, l)
11151 hlua_prepend_path(L, pp->type, pp->path);
11152
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011153 /*
11154 *
11155 * Create "core" object.
11156 *
11157 */
11158
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011159 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011160 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011161
Thierry Fournierecb83c22020-11-28 15:49:44 +010011162 /* set the thread id */
11163 hlua_class_const_int(L, "thread", thread_num);
11164
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011165 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011166 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011167 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011168
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011169 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011170 hlua_class_function(L, "register_init", hlua_register_init);
11171 hlua_class_function(L, "register_task", hlua_register_task);
11172 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11173 hlua_class_function(L, "register_converters", hlua_register_converters);
11174 hlua_class_function(L, "register_action", hlua_register_action);
11175 hlua_class_function(L, "register_service", hlua_register_service);
11176 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011177 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011178 hlua_class_function(L, "yield", hlua_yield);
11179 hlua_class_function(L, "set_nice", hlua_set_nice);
11180 hlua_class_function(L, "sleep", hlua_sleep);
11181 hlua_class_function(L, "msleep", hlua_msleep);
11182 hlua_class_function(L, "add_acl", hlua_add_acl);
11183 hlua_class_function(L, "del_acl", hlua_del_acl);
11184 hlua_class_function(L, "set_map", hlua_set_map);
11185 hlua_class_function(L, "del_map", hlua_del_map);
11186 hlua_class_function(L, "tcp", hlua_socket_new);
11187 hlua_class_function(L, "log", hlua_log);
11188 hlua_class_function(L, "Debug", hlua_log_debug);
11189 hlua_class_function(L, "Info", hlua_log_info);
11190 hlua_class_function(L, "Warning", hlua_log_warning);
11191 hlua_class_function(L, "Alert", hlua_log_alert);
11192 hlua_class_function(L, "done", hlua_done);
11193 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011194
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011195 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011196
11197 /*
11198 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011199 * Create "act" object.
11200 *
11201 */
11202
11203 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011204 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011205
11206 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011207 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11208 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11209 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11210 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11211 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11212 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11213 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11214 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011215
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011216 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011217
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011218 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011219
11220 /*
11221 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011222 * Create "Filter" object.
11223 *
11224 */
11225
11226 /* This table entry is the object "filter" base. */
11227 lua_newtable(L);
11228
11229 /* push flags and constants */
11230 hlua_class_const_int(L, "CONTINUE", 1);
11231 hlua_class_const_int(L, "WAIT", 0);
11232 hlua_class_const_int(L, "ERROR", -1);
11233
11234 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
11235
Christopher Fauletc404f112020-02-26 15:03:09 +010011236 hlua_class_function(L, "wake_time", hlua_set_wake_time);
11237 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
11238 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
11239
Christopher Faulet69c581a2021-05-31 08:54:04 +020011240 lua_setglobal(L, "filter");
11241
11242 /*
11243 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011244 * Register class Map
11245 *
11246 */
11247
11248 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011249 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011250
11251 /* register pattern types. */
11252 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011253 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011254 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011255 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011256 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011257 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011258
11259 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011260 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011261
11262 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011263 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011264
Ilya Shipitsind4259502020-04-08 01:07:56 +050011265 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011266 lua_pushstring(L, "__index");
11267 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011268
11269 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011270 hlua_class_function(L, "lookup", hlua_map_lookup);
11271 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011272
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011273 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011274
Thierry Fournier45e78d72016-02-19 18:34:46 +010011275 /* Register previous table in the registry with reference and named entry.
11276 * The function hlua_register_metatable() pops the stack, so we
11277 * previously create a copy of the table.
11278 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011279 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
11280 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011281
11282 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011283 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011284
11285 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011286 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011287
11288 /*
11289 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011290 * Register class Channel
11291 *
11292 */
11293
11294 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011295 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011296
Ilya Shipitsind4259502020-04-08 01:07:56 +050011297 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011298 lua_pushstring(L, "__index");
11299 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011300
11301 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011302 hlua_class_function(L, "data", hlua_channel_get_data);
11303 hlua_class_function(L, "line", hlua_channel_get_line);
11304 hlua_class_function(L, "set", hlua_channel_set_data);
11305 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011306 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011307 hlua_class_function(L, "prepend", hlua_channel_prepend);
11308 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011309 hlua_class_function(L, "send", hlua_channel_send);
11310 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011311 hlua_class_function(L, "input", hlua_channel_get_in_len);
11312 hlua_class_function(L, "output", hlua_channel_get_out_len);
11313 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011314 hlua_class_function(L, "is_full", hlua_channel_is_full);
11315 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011316
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011317 /* Deprecated API */
11318 hlua_class_function(L, "get", hlua_channel_get);
11319 hlua_class_function(L, "dup", hlua_channel_dup);
11320 hlua_class_function(L, "getline", hlua_channel_getline);
11321 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
11322 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
11323
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011324 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011325
11326 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011327 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011328
11329 /*
11330 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011331 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011332 *
11333 */
11334
11335 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011336 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011337
Ilya Shipitsind4259502020-04-08 01:07:56 +050011338 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011339 lua_pushstring(L, "__index");
11340 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011341
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011342 /* Browse existing fetches and create the associated
11343 * object method.
11344 */
11345 sf = NULL;
11346 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011347 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11348 * by an underscore.
11349 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011350 strncpy(trash.area, sf->kw, trash.size);
11351 trash.area[trash.size - 1] = '\0';
11352 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011353 if (*p == '.' || *p == '-' || *p == '+')
11354 *p = '_';
11355
11356 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011357 lua_pushstring(L, trash.area);
11358 lua_pushlightuserdata(L, sf);
11359 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
11360 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011361 }
11362
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011363 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011364
11365 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011366 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011367
11368 /*
11369 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011370 * Register class Converters
11371 *
11372 */
11373
11374 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011375 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011376
11377 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011378 lua_pushstring(L, "__index");
11379 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011380
11381 /* Browse existing converters and create the associated
11382 * object method.
11383 */
11384 sc = NULL;
11385 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011386 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11387 * by an underscore.
11388 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011389 strncpy(trash.area, sc->kw, trash.size);
11390 trash.area[trash.size - 1] = '\0';
11391 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011392 if (*p == '.' || *p == '-' || *p == '+')
11393 *p = '_';
11394
11395 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011396 lua_pushstring(L, trash.area);
11397 lua_pushlightuserdata(L, sc);
11398 lua_pushcclosure(L, hlua_run_sample_conv, 1);
11399 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011400 }
11401
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011402 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011403
11404 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011405 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011406
11407 /*
11408 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011409 * Register class HTTP
11410 *
11411 */
11412
11413 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011414 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011415
Ilya Shipitsind4259502020-04-08 01:07:56 +050011416 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011417 lua_pushstring(L, "__index");
11418 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011419
11420 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011421 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
11422 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
11423 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
11424 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
11425 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
11426 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
11427 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
11428 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
11429 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
11430 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011431
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011432 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
11433 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
11434 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
11435 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
11436 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
11437 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
11438 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011439
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011440 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011441
11442 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011443 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011444
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011445 /*
11446 *
11447 * Register class HTTPMessage
11448 *
11449 */
11450
11451 /* Create and fill the metatable. */
11452 lua_newtable(L);
11453
11454 /* Create and fille the __index entry. */
11455 lua_pushstring(L, "__index");
11456 lua_newtable(L);
11457
11458 /* Register Lua functions. */
11459 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
11460 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
11461 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
11462 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
11463 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
11464 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
11465 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
11466 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
11467 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
11468 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
11469 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
11470 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
11471 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
11472 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
11473 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
11474 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
11475 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
11476 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
11477
11478 hlua_class_function(L, "body", hlua_http_msg_get_body);
11479 hlua_class_function(L, "set", hlua_http_msg_set_data);
11480 hlua_class_function(L, "remove", hlua_http_msg_del_data);
11481 hlua_class_function(L, "append", hlua_http_msg_append);
11482 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
11483 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
11484 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
11485 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
11486
11487 hlua_class_function(L, "send", hlua_http_msg_send);
11488 hlua_class_function(L, "forward", hlua_http_msg_forward);
11489
11490 lua_rawset(L, -3);
11491
11492 /* Register previous table in the registry with reference and named entry. */
11493 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011494 /*
11495 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011496 * Register class AppletTCP
11497 *
11498 */
11499
11500 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011501 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011502
Ilya Shipitsind4259502020-04-08 01:07:56 +050011503 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011504 lua_pushstring(L, "__index");
11505 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011506
11507 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011508 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
11509 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
11510 hlua_class_function(L, "send", hlua_applet_tcp_send);
11511 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
11512 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
11513 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
11514 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
11515 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011516
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011517 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011518
11519 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011520 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011521
11522 /*
11523 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011524 * Register class AppletHTTP
11525 *
11526 */
11527
11528 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011529 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011530
Ilya Shipitsind4259502020-04-08 01:07:56 +050011531 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011532 lua_pushstring(L, "__index");
11533 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011534
11535 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011536 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
11537 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
11538 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
11539 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
11540 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
11541 hlua_class_function(L, "getline", hlua_applet_http_getline);
11542 hlua_class_function(L, "receive", hlua_applet_http_recv);
11543 hlua_class_function(L, "send", hlua_applet_http_send);
11544 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
11545 hlua_class_function(L, "set_status", hlua_applet_http_status);
11546 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011547
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011548 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011549
11550 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011551 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011552
11553 /*
11554 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011555 * Register class TXN
11556 *
11557 */
11558
11559 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011560 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011561
Ilya Shipitsind4259502020-04-08 01:07:56 +050011562 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011563 lua_pushstring(L, "__index");
11564 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011565
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011566 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011567 hlua_class_function(L, "set_priv", hlua_set_priv);
11568 hlua_class_function(L, "get_priv", hlua_get_priv);
11569 hlua_class_function(L, "set_var", hlua_set_var);
11570 hlua_class_function(L, "unset_var", hlua_unset_var);
11571 hlua_class_function(L, "get_var", hlua_get_var);
11572 hlua_class_function(L, "done", hlua_txn_done);
11573 hlua_class_function(L, "reply", hlua_txn_reply_new);
11574 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
11575 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
11576 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
11577 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
11578 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
11579 hlua_class_function(L, "deflog", hlua_txn_deflog);
11580 hlua_class_function(L, "log", hlua_txn_log);
11581 hlua_class_function(L, "Debug", hlua_txn_log_debug);
11582 hlua_class_function(L, "Info", hlua_txn_log_info);
11583 hlua_class_function(L, "Warning", hlua_txn_log_warning);
11584 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011585
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011586 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011587
11588 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011589 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011590
11591 /*
11592 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010011593 * Register class reply
11594 *
11595 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011596 lua_newtable(L);
11597 lua_pushstring(L, "__index");
11598 lua_newtable(L);
11599 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
11600 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
11601 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
11602 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
11603 lua_settable(L, -3); /* Sets the __index entry. */
11604 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010011605
11606
11607 /*
11608 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011609 * Register class Socket
11610 *
11611 */
11612
11613 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011614 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011615
Ilya Shipitsind4259502020-04-08 01:07:56 +050011616 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011617 lua_pushstring(L, "__index");
11618 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011619
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011620#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011621 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011622#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011623 hlua_class_function(L, "connect", hlua_socket_connect);
11624 hlua_class_function(L, "send", hlua_socket_send);
11625 hlua_class_function(L, "receive", hlua_socket_receive);
11626 hlua_class_function(L, "close", hlua_socket_close);
11627 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
11628 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
11629 hlua_class_function(L, "setoption", hlua_socket_setoption);
11630 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011631
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011632 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011633
11634 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011635 lua_pushstring(L, "__gc");
11636 lua_pushcclosure(L, hlua_socket_gc, 0);
11637 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011638
11639 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011640 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011641
Thierry Fournieraafc7772020-12-04 11:47:47 +010011642 lua_atpanic(L, hlua_panic_safe);
11643
11644 return L;
11645}
11646
11647void hlua_init(void) {
11648 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011649 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010011650#ifdef USE_OPENSSL
11651 struct srv_kw *kw;
11652 int tmp_error;
11653 char *error;
11654 char *args[] = { /* SSL client configuration. */
11655 "ssl",
11656 "verify",
11657 "none",
11658 NULL
11659 };
11660#endif
11661
11662 /* Init post init function list head */
11663 for (i = 0; i < MAX_THREADS + 1; i++)
11664 LIST_INIT(&hlua_init_functions[i]);
11665
11666 /* Init state for common/shared lua parts */
11667 hlua_state_id = 0;
11668 ha_set_tid(0);
11669 hlua_states[0] = hlua_init_state(0);
11670
11671 /* Init state 1 for thread 0. We have at least one thread. */
11672 hlua_state_id = 1;
11673 ha_set_tid(0);
11674 hlua_states[1] = hlua_init_state(1);
11675
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011676 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020011677 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011678 if (!socket_proxy) {
11679 fprintf(stderr, "Lua init: %s\n", errmsg);
11680 exit(1);
11681 }
11682 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011683
11684 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011685 socket_tcp = new_server(socket_proxy);
11686 if (!socket_tcp) {
11687 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
11688 exit(1);
11689 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011690
11691#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011692 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011693 socket_ssl = new_server(socket_proxy);
11694 if (!socket_ssl) {
11695 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
11696 exit(1);
11697 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011698
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011699 socket_ssl->use_ssl = 1;
11700 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011701
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011702 for (i = 0; args[i] != NULL; i++) {
11703 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011704 /*
11705 *
11706 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011707 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011708 * features like client certificates and ssl_verify.
11709 *
11710 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011711 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011712 if (tmp_error != 0) {
11713 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
11714 abort(); /* This must be never arrives because the command line
11715 not editable by the user. */
11716 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011717 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011718 }
11719 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011720#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010011721
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011722}
Willy Tarreaubb57d942016-12-21 19:04:56 +010011723
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011724static void hlua_deinit()
11725{
Willy Tarreau186f3762020-12-04 11:48:12 +010011726 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011727 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
11728
11729 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
11730 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010011731
11732 for (thr = 0; thr < MAX_THREADS+1; thr++) {
11733 if (hlua_states[thr])
11734 lua_close(hlua_states[thr]);
11735 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011736
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011737 free_server(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011738
Willy Tarreau0f143af2021-03-05 10:41:48 +010011739#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011740 free_server(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010011741#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011742
11743 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011744}
11745
11746REGISTER_POST_DEINIT(hlua_deinit);
11747
Willy Tarreau80713382018-11-26 10:19:54 +010011748static void hlua_register_build_options(void)
11749{
Willy Tarreaubb57d942016-12-21 19:04:56 +010011750 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010011751
Willy Tarreaubb57d942016-12-21 19:04:56 +010011752 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
11753 hap_register_build_opts(ptr, 1);
11754}
Willy Tarreau80713382018-11-26 10:19:54 +010011755
11756INITCALL0(STG_REGISTER, hlua_register_build_options);