blob: 039ebeca7741610ba787e415d2f2467eefaa5059 [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
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200147/* This function takes the Lua global lock. Keep this function's visibility
148 * global so that it can appear in stack dumps and performance profiles!
149 */
150void lua_take_global_lock()
151{
152 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
153}
154
155static inline void lua_drop_global_lock()
156{
157 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
158}
159
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100160#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200161 ({ \
162 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100163 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200164 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200165 if (setjmp(safe_ljmp_env) != 0) { \
166 lua_atpanic(__L, hlua_panic_safe); \
167 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 } else { \
171 lua_atpanic(__L, hlua_panic_ljmp); \
172 ret = 1; \
173 } \
174 ret; \
175 })
176
177/* If we are the last function catching Lua errors, we
178 * must reset the panic function.
179 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100180#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200181 do { \
182 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100183 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200184 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200185 } while(0)
186
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100187#define SET_SAFE_LJMP(__HLUA) \
188 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
189
190#define RESET_SAFE_LJMP(__HLUA) \
191 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
192
193#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100194 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100195
196#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100197 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100198
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200199/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200200#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100201/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200202#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200203/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100204#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100205#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200206
Thierry Fournierafc63e22020-11-28 17:06:51 +0100207/* The main Lua execution context. The 0 index is the
208 * common state shared by all threads.
209 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100210static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100211
Christopher Fauletc404f112020-02-26 15:03:09 +0100212#define HLUA_FLT_CB_FINAL 0x00000001
213#define HLUA_FLT_CB_RETVAL 0x00000002
214#define HLUA_FLT_CB_ARG_CHN 0x00000004
215#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
216
Christopher Faulet9f55a502020-02-25 15:21:02 +0100217#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
218
Christopher Faulet69c581a2021-05-31 08:54:04 +0200219struct hlua_reg_filter {
220 char *name;
221 int flt_ref[MAX_THREADS + 1];
222 int fun_ref[MAX_THREADS + 1];
223 struct list l;
224};
225
226struct hlua_flt_config {
227 struct hlua_reg_filter *reg;
228 int ref[MAX_THREADS + 1];
229 char **args;
230};
231
232struct hlua_flt_ctx {
233 int ref; /* ref to the filter lua object */
234 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
235 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
236 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
237 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
238};
239
240DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
241
Christopher Faulet9f55a502020-02-25 15:21:02 +0100242static int hlua_filter_from_payload(struct filter *filter);
243
Christopher Faulet69c581a2021-05-31 08:54:04 +0200244/* This is the chained list of struct hlua_flt referenced
245 * for haproxy filters. It is used for a post-initialisation control.
246 */
247static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
248
249
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100250/* This is the memory pool containing struct lua for applets
251 * (including cli).
252 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100253DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100254
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100255/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100256static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100257static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100258#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100259static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100260#endif
261
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100262/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100263struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100264
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100265/* The following variables contains the reference of the different
266 * Lua classes. These references are useful for identify metadata
267 * associated with an object.
268 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100269static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100270static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100271static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100272static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100273static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100274static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100275static int class_http_msg_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200276static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200277static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200278static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100279static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100280
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100281/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200282 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100283 * short timeout. Lua linked with tasks doesn't have a timeout
284 * because a task may remain alive during all the haproxy execution.
285 */
286static unsigned int hlua_timeout_session = 4000; /* session timeout. */
287static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200288static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100289
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100290/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
291 * it is used for preventing infinite loops.
292 *
293 * I test the scheer with an infinite loop containing one incrementation
294 * and one test. I run this loop between 10 seconds, I raise a ceil of
295 * 710M loops from one interrupt each 9000 instructions, so I fix the value
296 * to one interrupt each 10 000 instructions.
297 *
298 * configured | Number of
299 * instructions | loops executed
300 * between two | in milions
301 * forced yields |
302 * ---------------+---------------
303 * 10 | 160
304 * 500 | 670
305 * 1000 | 680
306 * 5000 | 700
307 * 7000 | 700
308 * 8000 | 700
309 * 9000 | 710 <- ceil
310 * 10000 | 710
311 * 100000 | 710
312 * 1000000 | 710
313 *
314 */
315static unsigned int hlua_nb_instruction = 10000;
316
Willy Tarreaucdb53462020-12-02 12:12:00 +0100317/* Descriptor for the memory allocation state. The limit is pre-initialised to
318 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
319 * is replaced with ~0 during post_init after everything was loaded. This way
320 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
321 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100322 */
323struct hlua_mem_allocator {
324 size_t allocated;
325 size_t limit;
326};
327
Willy Tarreaucdb53462020-12-02 12:12:00 +0100328static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100329
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100330/* These functions converts types between HAProxy internal args or
331 * sample and LUA types. Another function permits to check if the
332 * LUA stack contains arguments according with an required ARG_T
333 * format.
334 */
335static int hlua_arg2lua(lua_State *L, const struct arg *arg);
336static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100337__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100338 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100339static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100340static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100341static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
342
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100343__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200344
Thierry Fournier59f11be2020-11-29 00:37:41 +0100345struct prepend_path {
346 struct list l;
347 char *type;
348 char *path;
349};
350
351static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
352
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200353#define SEND_ERR(__be, __fmt, __args...) \
354 do { \
355 send_log(__be, LOG_ERR, __fmt, ## __args); \
356 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100357 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200358 } while (0)
359
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100360static inline struct hlua_function *new_hlua_function()
361{
362 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100363 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100364
365 fcn = calloc(1, sizeof(*fcn));
366 if (!fcn)
367 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200368 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100369 for (i = 0; i < MAX_THREADS + 1; i++)
370 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100371 return fcn;
372}
373
Christopher Fauletdda44442021-04-12 14:05:43 +0200374static inline void release_hlua_function(struct hlua_function *fcn)
375{
376 if (!fcn)
377 return;
378 if (fcn->name)
379 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200380 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200381 ha_free(&fcn);
382}
383
Thierry Fournierc7492592020-11-28 23:57:24 +0100384/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
385static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
386{
387 if (fcn->function_ref[0] == -1)
388 return tid + 1;
389 return 0;
390}
391
Christopher Faulet69c581a2021-05-31 08:54:04 +0200392/* Create a new registered filter. Only its name is filled */
393static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
394{
395 struct hlua_reg_filter *reg_flt;
396 int i;
397
398 reg_flt = calloc(1, sizeof(*reg_flt));
399 if (!reg_flt)
400 return NULL;
401 reg_flt->name = strdup(name);
402 if (!reg_flt->name) {
403 free(reg_flt);
404 return NULL;
405 }
406 LIST_APPEND(&referenced_filters, &reg_flt->l);
407 for (i = 0; i < MAX_THREADS + 1; i++) {
408 reg_flt->flt_ref[i] = -1;
409 reg_flt->fun_ref[i] = -1;
410 }
411 return reg_flt;
412}
413
414/* Release a registered filter */
415static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
416{
417 if (!reg_flt)
418 return;
419 if (reg_flt->name)
420 ha_free(&reg_flt->name);
421 LIST_DELETE(&reg_flt->l);
422 ha_free(&reg_flt);
423}
424
425/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
426static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
427{
428 if (reg_flt->fun_ref[0] == -1)
429 return tid + 1;
430 return 0;
431}
432
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100433/* Used to check an Lua function type in the stack. It creates and
434 * returns a reference of the function. This function throws an
435 * error if the rgument is not a "function".
436 */
437__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
438{
439 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100440 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100441 WILL_LJMP(luaL_argerror(L, argno, msg));
442 }
443 lua_pushvalue(L, argno);
444 return luaL_ref(L, LUA_REGISTRYINDEX);
445}
446
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100447/* Used to check an Lua table type in the stack. It creates and
448 * returns a reference of the table. This function throws an
449 * error if the rgument is not a "table".
450 */
451__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
452{
453 if (!lua_istable(L, argno)) {
454 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
455 WILL_LJMP(luaL_argerror(L, argno, msg));
456 }
457 lua_pushvalue(L, argno);
458 return luaL_ref(L, LUA_REGISTRYINDEX);
459}
460
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200461/* Return the string that is of the top of the stack. */
462const char *hlua_get_top_error_string(lua_State *L)
463{
464 if (lua_gettop(L) < 1)
465 return "unknown error";
466 if (lua_type(L, -1) != LUA_TSTRING)
467 return "unknown error";
468 return lua_tostring(L, -1);
469}
470
Christopher Fauletd09cc512021-03-24 14:48:45 +0100471__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200472{
473 lua_Debug ar;
474 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200475 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200476
477 while (lua_getstack(L, level++, &ar)) {
478
479 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100480 if (b_data(msg))
481 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200482
483 /* Fill fields:
484 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
485 * 'l': fills in the field currentline;
486 * 'n': fills in the field name and namewhat;
487 * 't': fills in the field istailcall;
488 */
489 lua_getinfo(L, "Slnt", &ar);
490
491 /* Append code localisation */
492 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100493 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200494 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100495 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200496
497 /*
498 * Get function name
499 *
500 * if namewhat is no empty, name is defined.
501 * what contains "Lua" for Lua function, "C" for C function,
502 * or "main" for main code.
503 */
504 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100505 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200506
507 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100508 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200509
510 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100511 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200512
513 else /* nothing left... */
514 chunk_appendf(msg, "?");
515
516
517 /* Display tailed call */
518 if (ar.istailcall)
519 chunk_appendf(msg, " ...");
520 }
521
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200522 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200523}
524
525
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100526/* This function check the number of arguments available in the
527 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500528 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100529 */
530__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
531{
532 if (lua_gettop(L) == nb)
533 return;
534 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
535}
536
Mark Lakes22154b42018-01-29 14:38:40 -0800537/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100538 * and the line number where the error is encountered.
539 */
540static int hlua_pusherror(lua_State *L, const char *fmt, ...)
541{
542 va_list argp;
543 va_start(argp, fmt);
544 luaL_where(L, 1);
545 lua_pushvfstring(L, fmt, argp);
546 va_end(argp);
547 lua_concat(L, 2);
548 return 1;
549}
550
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100551/* This functions is used with sample fetch and converters. It
552 * converts the HAProxy configuration argument in a lua stack
553 * values.
554 *
555 * It takes an array of "arg", and each entry of the array is
556 * converted and pushed in the LUA stack.
557 */
558static int hlua_arg2lua(lua_State *L, const struct arg *arg)
559{
560 switch (arg->type) {
561 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100562 case ARGT_TIME:
563 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100564 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100565 break;
566
567 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200568 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100569 break;
570
571 case ARGT_IPV4:
572 case ARGT_IPV6:
573 case ARGT_MSK4:
574 case ARGT_MSK6:
575 case ARGT_FE:
576 case ARGT_BE:
577 case ARGT_TAB:
578 case ARGT_SRV:
579 case ARGT_USR:
580 case ARGT_MAP:
581 default:
582 lua_pushnil(L);
583 break;
584 }
585 return 1;
586}
587
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500588/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100589 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500590 * with sample fetch wrappers. The input arguments are given to the
591 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 */
593static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
594{
595 switch (lua_type(L, ud)) {
596
597 case LUA_TNUMBER:
598 case LUA_TBOOLEAN:
599 arg->type = ARGT_SINT;
600 arg->data.sint = lua_tointeger(L, ud);
601 break;
602
603 case LUA_TSTRING:
604 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200605 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200606 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200607 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200608 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100609 break;
610
611 case LUA_TUSERDATA:
612 case LUA_TNIL:
613 case LUA_TTABLE:
614 case LUA_TFUNCTION:
615 case LUA_TTHREAD:
616 case LUA_TLIGHTUSERDATA:
617 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200618 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100619 break;
620 }
621 return 1;
622}
623
624/* the following functions are used to convert a struct sample
625 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500626 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100627 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100628static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100629{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200630 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100631 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100632 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200633 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100634 break;
635
636 case SMP_T_BIN:
637 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200638 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100639 break;
640
641 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200642 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100643 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
644 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
645 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
646 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
647 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
648 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
649 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
650 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
651 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200652 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100653 break;
654 default:
655 lua_pushnil(L);
656 break;
657 }
658 break;
659
660 case SMP_T_IPV4:
661 case SMP_T_IPV6:
662 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200663 if (sample_casts[smp->data.type][SMP_T_STR] &&
664 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200665 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100666 else
667 lua_pushnil(L);
668 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100669 default:
670 lua_pushnil(L);
671 break;
672 }
673 return 1;
674}
675
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100676/* the following functions are used to convert a struct sample
677 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500678 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100679 */
680static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
681{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200682 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100683
684 case SMP_T_BIN:
685 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200686 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100687 break;
688
689 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200690 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100691 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
692 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
693 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
694 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
695 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
696 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
697 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
698 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
699 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200700 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100701 break;
702 default:
703 lua_pushstring(L, "");
704 break;
705 }
706 break;
707
708 case SMP_T_SINT:
709 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100710 case SMP_T_IPV4:
711 case SMP_T_IPV6:
712 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200713 if (sample_casts[smp->data.type][SMP_T_STR] &&
714 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200715 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100716 else
717 lua_pushstring(L, "");
718 break;
719 default:
720 lua_pushstring(L, "");
721 break;
722 }
723 return 1;
724}
725
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100726/* the following functions are used to convert an Lua type in a
727 * struct sample. This is useful to provide data from a converter
728 * to the LUA code.
729 */
730static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
731{
732 switch (lua_type(L, ud)) {
733
734 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200735 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200736 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100737 break;
738
739
740 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200741 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200742 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100743 break;
744
745 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200746 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100747 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200748 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200749 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200750 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200751 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100752 break;
753
754 case LUA_TUSERDATA:
755 case LUA_TNIL:
756 case LUA_TTABLE:
757 case LUA_TFUNCTION:
758 case LUA_TTHREAD:
759 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200760 case LUA_TNONE:
761 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200762 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200763 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100764 break;
765 }
766 return 1;
767}
768
Ilya Shipitsind4259502020-04-08 01:07:56 +0500769/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800770 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100771 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100772 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500773 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200774 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100775 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100776__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100777 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100778{
779 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200780 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100781 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200782 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200783 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200784 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200785 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100786
787 idx = 0;
788 min_arg = ARGM(mask);
789 mask >>= ARGM_BITS;
790
791 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200792 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100793
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100794 /* Check for mandatory arguments. */
795 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100796 if (idx < min_arg) {
797
798 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200799 if (idx > 0) {
800 msg = "Mandatory argument expected";
801 goto error;
802 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100803
804 /* If first argument have a certain type, some default values
805 * may be used. See the function smp_resolve_args().
806 */
807 switch (mask & ARGT_MASK) {
808
809 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200810 if (!(p->cap & PR_CAP_FE)) {
811 msg = "Mandatory argument expected";
812 goto error;
813 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100814 argp[idx].data.prx = p;
815 argp[idx].type = ARGT_FE;
816 argp[idx+1].type = ARGT_STOP;
817 break;
818
819 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200820 if (!(p->cap & PR_CAP_BE)) {
821 msg = "Mandatory argument expected";
822 goto error;
823 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100824 argp[idx].data.prx = p;
825 argp[idx].type = ARGT_BE;
826 argp[idx+1].type = ARGT_STOP;
827 break;
828
829 case ARGT_TAB:
830 argp[idx].data.prx = p;
831 argp[idx].type = ARGT_TAB;
832 argp[idx+1].type = ARGT_STOP;
833 break;
834
835 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200836 msg = "Mandatory argument expected";
837 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100838 break;
839 }
840 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200841 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100842 }
843
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500844 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100845 if ((mask & ARGT_MASK) == ARGT_STOP &&
846 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200847 msg = "Last argument expected";
848 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100849 }
850
851 if ((mask & ARGT_MASK) == ARGT_STOP &&
852 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200853 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100854 }
855
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200856 /* Convert some argument types. All string in argp[] are for not
857 * duplicated yet.
858 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100859 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100860 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200861 if (argp[idx].type != ARGT_SINT) {
862 msg = "integer expected";
863 goto error;
864 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100865 argp[idx].type = ARGT_SINT;
866 break;
867
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100868 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200869 if (argp[idx].type != ARGT_SINT) {
870 msg = "integer expected";
871 goto error;
872 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200873 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100874 break;
875
876 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200877 if (argp[idx].type != ARGT_SINT) {
878 msg = "integer expected";
879 goto error;
880 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200881 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100882 break;
883
884 case ARGT_FE:
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_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200890 if (!argp[idx].data.prx) {
891 msg = "frontend doesn't exist";
892 goto error;
893 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100894 argp[idx].type = ARGT_FE;
895 break;
896
897 case ARGT_BE:
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.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200903 if (!argp[idx].data.prx) {
904 msg = "backend doesn't exist";
905 goto error;
906 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100907 argp[idx].type = ARGT_BE;
908 break;
909
910 case ARGT_TAB:
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 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200916 if (!argp[idx].data.t) {
917 msg = "table doesn't exist";
918 goto error;
919 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100920 argp[idx].type = ARGT_TAB;
921 break;
922
923 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200924 if (argp[idx].type != ARGT_STR) {
925 msg = "string expected";
926 goto error;
927 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200928 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100929 if (sname) {
930 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200931 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200932 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200933 if (!px) {
934 msg = "backend doesn't exist";
935 goto error;
936 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100937 }
938 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200939 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100940 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100941 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100942 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200943 if (!argp[idx].data.srv) {
944 msg = "server doesn't exist";
945 goto error;
946 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100947 argp[idx].type = ARGT_SRV;
948 break;
949
950 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200951 if (argp[idx].type != ARGT_STR) {
952 msg = "string expected";
953 goto error;
954 }
955 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
956 msg = "invalid IPv4 address";
957 goto error;
958 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100959 argp[idx].type = ARGT_IPV4;
960 break;
961
962 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200963 if (argp[idx].type == ARGT_SINT)
964 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
965 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200966 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
967 msg = "invalid IPv4 mask";
968 goto error;
969 }
970 }
971 else {
972 msg = "integer or string expected";
973 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200974 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100975 argp[idx].type = ARGT_MSK4;
976 break;
977
978 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200979 if (argp[idx].type != ARGT_STR) {
980 msg = "string expected";
981 goto error;
982 }
983 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
984 msg = "invalid IPv6 address";
985 goto error;
986 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100987 argp[idx].type = ARGT_IPV6;
988 break;
989
990 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200991 if (argp[idx].type == ARGT_SINT)
992 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
993 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200994 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
995 msg = "invalid IPv6 mask";
996 goto error;
997 }
998 }
999 else {
1000 msg = "integer or string expected";
1001 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001002 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001003 argp[idx].type = ARGT_MSK6;
1004 break;
1005
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001006 case ARGT_REG:
1007 if (argp[idx].type != ARGT_STR) {
1008 msg = "string expected";
1009 goto error;
1010 }
1011 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1012 if (!reg) {
1013 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1014 argp[idx].data.str.area, err);
1015 free(err);
1016 goto error;
1017 }
1018 argp[idx].type = ARGT_REG;
1019 argp[idx].data.reg = reg;
1020 break;
1021
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001022 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001023 if (argp[idx].type != ARGT_STR) {
1024 msg = "string expected";
1025 goto error;
1026 }
1027 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001028 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001029 ul = p->uri_auth->userlist;
1030 else
1031 ul = auth_find_userlist(argp[idx].data.str.area);
1032
1033 if (!ul) {
1034 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1035 goto error;
1036 }
1037 argp[idx].type = ARGT_USR;
1038 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001039 break;
1040
1041 case ARGT_STR:
1042 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1043 msg = "unable to duplicate string arg";
1044 goto error;
1045 }
1046 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001047 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001048
Christopher Fauletd25d9262020-08-06 11:04:46 +02001049 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001050 msg = "type not yet supported";
1051 goto error;
1052 break;
1053
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001054 }
1055
1056 /* Check for type of argument. */
1057 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001058 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1059 arg_type_names[(mask & ARGT_MASK)],
1060 arg_type_names[argp[idx].type & ARGT_MASK]);
1061 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001062 }
1063
1064 /* Next argument. */
1065 mask >>= ARGT_BITS;
1066 idx++;
1067 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001068 return 0;
1069
1070 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001071 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001072 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1073 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001074}
1075
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001076/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001077 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001078 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001079 *
1080 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001081 * - hlua_sethlua : create the association between hlua context and lua_state.
1082 */
1083static inline struct hlua *hlua_gethlua(lua_State *L)
1084{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001085 struct hlua **hlua = lua_getextraspace(L);
1086 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001087}
1088static inline void hlua_sethlua(struct hlua *hlua)
1089{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001090 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1091 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001092}
1093
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001094/* This function is used to send logs. It try to send on screen (stderr)
1095 * and on the default syslog server.
1096 */
1097static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1098{
1099 struct tm tm;
1100 char *p;
1101
1102 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001103 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001104 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001105 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001106 /* Break the message if exceed the buffer size. */
1107 *(p-4) = ' ';
1108 *(p-3) = '.';
1109 *(p-2) = '.';
1110 *(p-1) = '.';
1111 break;
1112 }
Willy Tarreau90807112020-02-25 08:16:33 +01001113 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001114 *p = *msg;
1115 else
1116 *p = '.';
1117 }
1118 *p = '\0';
1119
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001120 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001121 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001122 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1123 return;
1124
Willy Tarreaua678b432015-08-28 10:14:59 +02001125 get_localtime(date.tv_sec, &tm);
1126 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001127 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001128 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001129 fflush(stderr);
1130 }
1131}
1132
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001133/* This function just ensure that the yield will be always
1134 * returned with a timeout and permit to set some flags
1135 */
1136__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001137 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001138{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001139 struct hlua *hlua;
1140
1141 /* Get hlua struct, or NULL if we execute from main lua state */
1142 hlua = hlua_gethlua(L);
1143 if (!hlua) {
1144 return;
1145 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001146
1147 /* Set the wake timeout. If timeout is required, we set
1148 * the expiration time.
1149 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001150 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001151
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001152 hlua->flags |= flags;
1153
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001154 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001155 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001156}
1157
Willy Tarreau87b09662015-04-03 00:22:06 +02001158/* This function initialises the Lua environment stored in the stream.
1159 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001160 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001161 *
1162 * This function is particular. it initialises a new Lua thread. If the
1163 * initialisation fails (example: out of memory error), the lua function
1164 * throws an error (longjmp).
1165 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001166 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001167 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001168 * threads appear, the safe environment set a lock to ensure only one
1169 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001170 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001171 *
1172 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001173 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001174 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001175 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001176 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001177 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001178 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001179 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001180int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001181{
1182 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001183 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001184 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001185 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001186 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001187 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001188 if (!already_safe) {
1189 if (!SET_SAFE_LJMP_PARENT(lua)) {
1190 lua->Tref = LUA_REFNIL;
1191 return 0;
1192 }
1193 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001194 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001195 if (!lua->T) {
1196 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001197 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001198 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001199 return 0;
1200 }
1201 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001202 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001203 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001204 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001205 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001206 return 1;
1207}
1208
Willy Tarreau87b09662015-04-03 00:22:06 +02001209/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001210 * is destroyed. The destroy also the memory context. The struct "lua"
1211 * is not freed.
1212 */
1213void hlua_ctx_destroy(struct hlua *lua)
1214{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001215 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001216 return;
1217
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001218 if (!lua->T)
1219 goto end;
1220
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001221 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001222 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001223
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001224 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001225 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001226 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001227 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001228
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001229 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001230 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001231 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001232 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001233 /* Forces a garbage collecting process. If the Lua program is finished
1234 * without error, we run the GC on the thread pointer. Its freed all
1235 * the unused memory.
1236 * If the thread is finnish with an error or is currently yielded,
1237 * it seems that the GC applied on the thread doesn't clean anything,
1238 * so e run the GC on the main thread.
1239 * NOTE: maybe this action locks all the Lua threads untiml the en of
1240 * the garbage collection.
1241 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001242 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001243 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001244 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001245 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001246 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001247 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001248
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001249 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001250
1251end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001252 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001253}
1254
1255/* This function is used to restore the Lua context when a coroutine
1256 * fails. This function copy the common memory between old coroutine
1257 * and the new coroutine. The old coroutine is destroyed, and its
1258 * replaced by the new coroutine.
1259 * If the flag "keep_msg" is set, the last entry of the old is assumed
1260 * as string error message and it is copied in the new stack.
1261 */
1262static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1263{
1264 lua_State *T;
1265 int new_ref;
1266
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001267 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001268 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001269 if (!T)
1270 return 0;
1271
1272 /* Copy last error message. */
1273 if (keep_msg)
1274 lua_xmove(lua->T, T, 1);
1275
1276 /* Copy data between the coroutines. */
1277 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1278 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001279 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001280
1281 /* Destroy old data. */
1282 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1283
1284 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001285 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001286
1287 /* Fill the struct with the new coroutine values. */
1288 lua->Mref = new_ref;
1289 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001290 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001291
1292 /* Set context. */
1293 hlua_sethlua(lua);
1294
1295 return 1;
1296}
1297
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001298void hlua_hook(lua_State *L, lua_Debug *ar)
1299{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001300 struct hlua *hlua;
1301
1302 /* Get hlua struct, or NULL if we execute from main lua state */
1303 hlua = hlua_gethlua(L);
1304 if (!hlua)
1305 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001306
1307 /* Lua cannot yield when its returning from a function,
1308 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001309 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001310 */
1311 if (lua_gethookmask(L) & LUA_MASKRET) {
1312 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1313 return;
1314 }
1315
1316 /* restore the interrupt condition. */
1317 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1318
1319 /* If we interrupt the Lua processing in yieldable state, we yield.
1320 * If the state is not yieldable, trying yield causes an error.
1321 */
1322 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001323 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001324
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001325 /* If we cannot yield, update the clock and check the timeout. */
1326 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001327 hlua->run_time += now_ms - hlua->start_time;
1328 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001329 lua_pushfstring(L, "execution timeout");
1330 WILL_LJMP(lua_error(L));
1331 }
1332
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001333 /* Update the start time. */
1334 hlua->start_time = now_ms;
1335
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001336 /* Try to interrupt the process at the end of the current
1337 * unyieldable function.
1338 */
1339 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001340}
1341
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001342/* This function start or resumes the Lua stack execution. If the flag
1343 * "yield_allowed" if no set and the LUA stack execution returns a yield
1344 * The function return an error.
1345 *
1346 * The function can returns 4 values:
1347 * - HLUA_E_OK : The execution is terminated without any errors.
1348 * - HLUA_E_AGAIN : The execution must continue at the next associated
1349 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001350 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001351 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001352 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001353 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001354 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001355 * LUA code.
1356 */
1357static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1358{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001359#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1360 int nres;
1361#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001362 int ret;
1363 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001364 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001365
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001366 /* Initialise run time counter. */
1367 if (!HLUA_IS_RUNNING(lua))
1368 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001369
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001370 /* Lock the whole Lua execution. This lock must be before the
1371 * label "resume_execution".
1372 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001373 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001374 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001375
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001376resume_execution:
1377
1378 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1379 * instructions. it is used for preventing infinite loops.
1380 */
1381 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1382
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001383 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001384 HLUA_SET_RUN(lua);
1385 HLUA_CLR_CTRLYIELD(lua);
1386 HLUA_CLR_WAKERESWR(lua);
1387 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001388 HLUA_CLR_NOYIELD(lua);
1389 if (!yield_allowed)
1390 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001391
Christopher Fauletbc275a92020-02-26 14:55:16 +01001392 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001393 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001394 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001395
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001396 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001397#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001398 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001399#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001400 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001401#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001402 switch (ret) {
1403
1404 case LUA_OK:
1405 ret = HLUA_E_OK;
1406 break;
1407
1408 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001409 /* Check if the execution timeout is expired. It it is the case, we
1410 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001411 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001412 tv_update_date(0, 1);
1413 lua->run_time += now_ms - lua->start_time;
1414 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001415 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001416 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001417 break;
1418 }
1419 /* Process the forced yield. if the general yield is not allowed or
1420 * if no task were associated this the current Lua execution
1421 * coroutine, we resume the execution. Else we want to return in the
1422 * scheduler and we want to be waked up again, to continue the
1423 * current Lua execution. So we schedule our own task.
1424 */
1425 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001426 if (!yield_allowed || !lua->task)
1427 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001428 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001429 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001430 if (!yield_allowed) {
1431 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001432 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001433 break;
1434 }
1435 ret = HLUA_E_AGAIN;
1436 break;
1437
1438 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001439
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001440 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001441 * because the errors ares the only one mean to return immediately
1442 * from and lua execution.
1443 */
1444 if (lua->flags & HLUA_EXIT) {
1445 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001446 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001447 break;
1448 }
1449
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001450 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001451 if (!lua_checkstack(lua->T, 1)) {
1452 ret = HLUA_E_ERR;
1453 break;
1454 }
1455 msg = lua_tostring(lua->T, -1);
1456 lua_settop(lua->T, 0); /* Empty the stack. */
1457 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001458 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001459 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001460 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001461 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001462 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001463 ret = HLUA_E_ERRMSG;
1464 break;
1465
1466 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001467 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001468 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001469 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001470 break;
1471
1472 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001473 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001474 if (!lua_checkstack(lua->T, 1)) {
1475 ret = HLUA_E_ERR;
1476 break;
1477 }
1478 msg = lua_tostring(lua->T, -1);
1479 lua_settop(lua->T, 0); /* Empty the stack. */
1480 lua_pop(lua->T, 1);
1481 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001482 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001483 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001484 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001485 ret = HLUA_E_ERRMSG;
1486 break;
1487
1488 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001489 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001490 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001491 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001492 break;
1493 }
1494
1495 switch (ret) {
1496 case HLUA_E_AGAIN:
1497 break;
1498
1499 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001500 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001501 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001502 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001503 break;
1504
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001505 case HLUA_E_ETMOUT:
1506 case HLUA_E_NOMEM:
1507 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001508 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001509 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001510 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001511 hlua_ctx_renew(lua, 0);
1512 break;
1513
1514 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001515 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001516 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001517 break;
1518 }
1519
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001520 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001521 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001522 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001523
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001524 return ret;
1525}
1526
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001527/* This function exit the current code. */
1528__LJMP static int hlua_done(lua_State *L)
1529{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001530 struct hlua *hlua;
1531
1532 /* Get hlua struct, or NULL if we execute from main lua state */
1533 hlua = hlua_gethlua(L);
1534 if (!hlua)
1535 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001536
1537 hlua->flags |= HLUA_EXIT;
1538 WILL_LJMP(lua_error(L));
1539
1540 return 0;
1541}
1542
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001543/* This function is an LUA binding. It provides a function
1544 * for deleting ACL from a referenced ACL file.
1545 */
1546__LJMP static int hlua_del_acl(lua_State *L)
1547{
1548 const char *name;
1549 const char *key;
1550 struct pat_ref *ref;
1551
1552 MAY_LJMP(check_args(L, 2, "del_acl"));
1553
1554 name = MAY_LJMP(luaL_checkstring(L, 1));
1555 key = MAY_LJMP(luaL_checkstring(L, 2));
1556
1557 ref = pat_ref_lookup(name);
1558 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001559 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001560
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001561 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001562 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001563 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001564 return 0;
1565}
1566
1567/* This function is an LUA binding. It provides a function
1568 * for deleting map entry from a referenced map file.
1569 */
1570static int hlua_del_map(lua_State *L)
1571{
1572 const char *name;
1573 const char *key;
1574 struct pat_ref *ref;
1575
1576 MAY_LJMP(check_args(L, 2, "del_map"));
1577
1578 name = MAY_LJMP(luaL_checkstring(L, 1));
1579 key = MAY_LJMP(luaL_checkstring(L, 2));
1580
1581 ref = pat_ref_lookup(name);
1582 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001583 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001584
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001585 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001586 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001587 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001588 return 0;
1589}
1590
1591/* This function is an LUA binding. It provides a function
1592 * for adding ACL pattern from a referenced ACL file.
1593 */
1594static int hlua_add_acl(lua_State *L)
1595{
1596 const char *name;
1597 const char *key;
1598 struct pat_ref *ref;
1599
1600 MAY_LJMP(check_args(L, 2, "add_acl"));
1601
1602 name = MAY_LJMP(luaL_checkstring(L, 1));
1603 key = MAY_LJMP(luaL_checkstring(L, 2));
1604
1605 ref = pat_ref_lookup(name);
1606 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001607 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001608
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001609 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001610 if (pat_ref_find_elt(ref, key) == NULL)
1611 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001612 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001613 return 0;
1614}
1615
1616/* This function is an LUA binding. It provides a function
1617 * for setting map pattern and sample from a referenced map
1618 * file.
1619 */
1620static int hlua_set_map(lua_State *L)
1621{
1622 const char *name;
1623 const char *key;
1624 const char *value;
1625 struct pat_ref *ref;
1626
1627 MAY_LJMP(check_args(L, 3, "set_map"));
1628
1629 name = MAY_LJMP(luaL_checkstring(L, 1));
1630 key = MAY_LJMP(luaL_checkstring(L, 2));
1631 value = MAY_LJMP(luaL_checkstring(L, 3));
1632
1633 ref = pat_ref_lookup(name);
1634 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001635 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001636
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001637 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001638 if (pat_ref_find_elt(ref, key) != NULL)
1639 pat_ref_set(ref, key, value, NULL);
1640 else
1641 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001642 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001643 return 0;
1644}
1645
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001646/* A class is a lot of memory that contain data. This data can be a table,
1647 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001648 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001649 * the name of the object (_G[<name>] = <metable> ).
1650 *
1651 * A metable is a table that modify the standard behavior of a standard
1652 * access to the associated data. The entries of this new metatable are
1653 * defined as is:
1654 *
1655 * http://lua-users.org/wiki/MetatableEvents
1656 *
1657 * __index
1658 *
1659 * we access an absent field in a table, the result is nil. This is
1660 * true, but it is not the whole truth. Actually, such access triggers
1661 * the interpreter to look for an __index metamethod: If there is no
1662 * such method, as usually happens, then the access results in nil;
1663 * otherwise, the metamethod will provide the result.
1664 *
1665 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1666 * the key does not appear in the table, but the metatable has an __index
1667 * property:
1668 *
1669 * - if the value is a function, the function is called, passing in the
1670 * table and the key; the return value of that function is returned as
1671 * the result.
1672 *
1673 * - if the value is another table, the value of the key in that table is
1674 * asked for and returned (and if it doesn't exist in that table, but that
1675 * table's metatable has an __index property, then it continues on up)
1676 *
1677 * - Use "rawget(myTable,key)" to skip this metamethod.
1678 *
1679 * http://www.lua.org/pil/13.4.1.html
1680 *
1681 * __newindex
1682 *
1683 * Like __index, but control property assignment.
1684 *
1685 * __mode - Control weak references. A string value with one or both
1686 * of the characters 'k' and 'v' which specifies that the the
1687 * keys and/or values in the table are weak references.
1688 *
1689 * __call - Treat a table like a function. When a table is followed by
1690 * parenthesis such as "myTable( 'foo' )" and the metatable has
1691 * a __call key pointing to a function, that function is invoked
1692 * (passing any specified arguments) and the return value is
1693 * returned.
1694 *
1695 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1696 * called, if the metatable for myTable has a __metatable
1697 * key, the value of that key is returned instead of the
1698 * actual metatable.
1699 *
1700 * __tostring - Control string representation. When the builtin
1701 * "tostring( myTable )" function is called, if the metatable
1702 * for myTable has a __tostring property set to a function,
1703 * that function is invoked (passing myTable to it) and the
1704 * return value is used as the string representation.
1705 *
1706 * __len - Control table length. When the table length is requested using
1707 * the length operator ( '#' ), if the metatable for myTable has
1708 * a __len key pointing to a function, that function is invoked
1709 * (passing myTable to it) and the return value used as the value
1710 * of "#myTable".
1711 *
1712 * __gc - Userdata finalizer code. When userdata is set to be garbage
1713 * collected, if the metatable has a __gc field pointing to a
1714 * function, that function is first invoked, passing the userdata
1715 * to it. The __gc metamethod is not called for tables.
1716 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1717 *
1718 * Special metamethods for redefining standard operators:
1719 * http://www.lua.org/pil/13.1.html
1720 *
1721 * __add "+"
1722 * __sub "-"
1723 * __mul "*"
1724 * __div "/"
1725 * __unm "!"
1726 * __pow "^"
1727 * __concat ".."
1728 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001729 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001730 * http://www.lua.org/pil/13.2.html
1731 *
1732 * __eq "=="
1733 * __lt "<"
1734 * __le "<="
1735 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001736
1737/*
1738 *
1739 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001740 * Class Map
1741 *
1742 *
1743 */
1744
1745/* Returns a struct hlua_map if the stack entry "ud" is
1746 * a class session, otherwise it throws an error.
1747 */
1748__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1749{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001750 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001751}
1752
1753/* This function is the map constructor. It don't need
1754 * the class Map object. It creates and return a new Map
1755 * object. It must be called only during "body" or "init"
1756 * context because it process some filesystem accesses.
1757 */
1758__LJMP static int hlua_map_new(struct lua_State *L)
1759{
1760 const char *fn;
1761 int match = PAT_MATCH_STR;
1762 struct sample_conv conv;
1763 const char *file = "";
1764 int line = 0;
1765 lua_Debug ar;
1766 char *err = NULL;
1767 struct arg args[2];
1768
1769 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1770 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1771
1772 fn = MAY_LJMP(luaL_checkstring(L, 1));
1773
1774 if (lua_gettop(L) >= 2) {
1775 match = MAY_LJMP(luaL_checkinteger(L, 2));
1776 if (match < 0 || match >= PAT_MATCH_NUM)
1777 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1778 }
1779
1780 /* Get Lua filename and line number. */
1781 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1782 lua_getinfo(L, "Sl", &ar); /* get info about it */
1783 if (ar.currentline > 0) { /* is there info? */
1784 file = ar.short_src;
1785 line = ar.currentline;
1786 }
1787 }
1788
1789 /* fill fake sample_conv struct. */
1790 conv.kw = ""; /* unused. */
1791 conv.process = NULL; /* unused. */
1792 conv.arg_mask = 0; /* unused. */
1793 conv.val_args = NULL; /* unused. */
1794 conv.out_type = SMP_T_STR;
1795 conv.private = (void *)(long)match;
1796 switch (match) {
1797 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1798 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1799 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1800 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1801 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1802 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1803 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001804 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001805 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1806 default:
1807 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1808 }
1809
1810 /* fill fake args. */
1811 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001812 args[0].data.str.area = strdup(fn);
1813 args[0].data.str.data = strlen(fn);
1814 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001815 args[1].type = ARGT_STOP;
1816
1817 /* load the map. */
1818 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001819 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001820 * free the err variable.
1821 */
1822 luaL_where(L, 1);
1823 lua_pushfstring(L, "'new': %s.", err);
1824 lua_concat(L, 2);
1825 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001826 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001827 WILL_LJMP(lua_error(L));
1828 }
1829
1830 /* create the lua object. */
1831 lua_newtable(L);
1832 lua_pushlightuserdata(L, args[0].data.map);
1833 lua_rawseti(L, -2, 0);
1834
1835 /* Pop a class Map metatable and affect it to the userdata. */
1836 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1837 lua_setmetatable(L, -2);
1838
1839
1840 return 1;
1841}
1842
1843__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1844{
1845 struct map_descriptor *desc;
1846 struct pattern *pat;
1847 struct sample smp;
1848
1849 MAY_LJMP(check_args(L, 2, "lookup"));
1850 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001851 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001852 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001853 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001854 }
1855 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001856 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001857 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001858 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 +01001859 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001860 }
1861
1862 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001863 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001864 if (str)
1865 lua_pushstring(L, "");
1866 else
1867 lua_pushnil(L);
1868 return 1;
1869 }
1870
1871 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001872 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001873 return 1;
1874}
1875
1876__LJMP static int hlua_map_lookup(struct lua_State *L)
1877{
1878 return _hlua_map_lookup(L, 0);
1879}
1880
1881__LJMP static int hlua_map_slookup(struct lua_State *L)
1882{
1883 return _hlua_map_lookup(L, 1);
1884}
1885
1886/*
1887 *
1888 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001889 * Class Socket
1890 *
1891 *
1892 */
1893
1894__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1895{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001896 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001897}
1898
1899/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001900 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001901 * received.
1902 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001903static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001904{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001905 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001906
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001907 if (appctx->ctx.hlua_cosocket.die) {
1908 si_shutw(si);
1909 si_shutr(si);
1910 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001911 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1912 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001913 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1914 }
1915
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001916 /* If we can't write, wakeup the pending write signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001917 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001918 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001919
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001920 /* If we can't read, wakeup the pending read signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001921 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001922 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001923
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001924 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001925 * to be notified whenever the connection completes.
1926 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001927 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001928 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001929 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001930 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001931 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001932 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001933
1934 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001935 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001936
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001937 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001938 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001939 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001940
1941 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001942 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001943 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001944
1945 /* Some data were injected in the buffer, notify the stream
1946 * interface.
1947 */
1948 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001949 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001950
1951 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001952 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001953 */
1954 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001955 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001956}
1957
Willy Tarreau87b09662015-04-03 00:22:06 +02001958/* This function is called when the "struct stream" is destroyed.
1959 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001960 * Wake all the pending signals.
1961 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001962static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001963{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001964 struct xref *peer;
1965
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001966 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001967 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1968 if (peer)
1969 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970
1971 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001972 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1973 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974}
1975
1976/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001977 * uses this object. If the stream does not exists, just quit.
1978 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001979 * pending signal can rest in the read and write lists. destroy
1980 * it.
1981 */
1982__LJMP static int hlua_socket_gc(lua_State *L)
1983{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001984 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001986 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001987
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001988 MAY_LJMP(check_args(L, 1, "__gc"));
1989
1990 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001991 peer = xref_get_peer_and_lock(&socket->xref);
1992 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001993 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001994 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001996 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001997 appctx->ctx.hlua_cosocket.die = 1;
1998 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001999
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002000 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002001 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002002 return 0;
2003}
2004
2005/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002006 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002007 */
sada05ed3302018-05-11 11:48:18 -07002008__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002009{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002010 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002011 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002012 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002013 struct hlua *hlua;
2014
2015 /* Get hlua struct, or NULL if we execute from main lua state */
2016 hlua = hlua_gethlua(L);
2017 if (!hlua)
2018 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002019
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002020 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002021
2022 /* Check if we run on the same thread than the xreator thread.
2023 * We cannot access to the socket if the thread is different.
2024 */
2025 if (socket->tid != tid)
2026 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2027
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002028 peer = xref_get_peer_and_lock(&socket->xref);
2029 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002030 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002031
2032 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002033 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002034
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002035 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002036 appctx->ctx.hlua_cosocket.die = 1;
2037 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002038
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002039 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002040 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002041 return 0;
2042}
2043
sada05ed3302018-05-11 11:48:18 -07002044/* The close function calls close_helper.
2045 */
2046__LJMP static int hlua_socket_close(lua_State *L)
2047{
2048 MAY_LJMP(check_args(L, 1, "close"));
2049 return hlua_socket_close_helper(L);
2050}
2051
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052/* This Lua function assumes that the stack contain three parameters.
2053 * 1 - USERDATA containing a struct socket
2054 * 2 - INTEGER with values of the macro defined below
2055 * If the integer is -1, we must read at most one line.
2056 * If the integer is -2, we ust read all the data until the
2057 * end of the stream.
2058 * If the integer is positive value, we must read a number of
2059 * bytes corresponding to this value.
2060 */
2061#define HLSR_READ_LINE (-1)
2062#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002063__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002064{
2065 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2066 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002067 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002068 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002069 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002070 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002071 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002072 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002073 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002074 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002075 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002076 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002077 struct stream_interface *si;
2078 struct stream *s;
2079 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002080 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002081
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002082 /* Get hlua struct, or NULL if we execute from main lua state */
2083 hlua = hlua_gethlua(L);
2084
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085 /* Check if this lua stack is schedulable. */
2086 if (!hlua || !hlua->task)
2087 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2088 "'frontend', 'backend' or 'task'"));
2089
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002090 /* Check if we run on the same thread than the xreator thread.
2091 * We cannot access to the socket if the thread is different.
2092 */
2093 if (socket->tid != tid)
2094 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2095
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002096 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002097 peer = xref_get_peer_and_lock(&socket->xref);
2098 if (!peer)
2099 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002100 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2101 si = appctx->owner;
2102 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002103
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002104 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002105 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002106 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002107 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002108 if (nblk < 0) /* Connection close. */
2109 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002110 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002112
2113 /* remove final \r\n. */
2114 if (nblk == 1) {
2115 if (blk1[len1-1] == '\n') {
2116 len1--;
2117 skip_at_end++;
2118 if (blk1[len1-1] == '\r') {
2119 len1--;
2120 skip_at_end++;
2121 }
2122 }
2123 }
2124 else {
2125 if (blk2[len2-1] == '\n') {
2126 len2--;
2127 skip_at_end++;
2128 if (blk2[len2-1] == '\r') {
2129 len2--;
2130 skip_at_end++;
2131 }
2132 }
2133 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134 }
2135
2136 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002137 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002138 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002139 if (nblk < 0) /* Connection close. */
2140 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002141 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 goto connection_empty;
2143 }
2144
2145 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002147 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148 if (nblk < 0) /* Connection close. */
2149 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002150 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151 goto connection_empty;
2152
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002153 missing_bytes = wanted - socket->b.n;
2154 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002155 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002156 len1 = missing_bytes;
2157 } if (nblk == 2 && len1 + len2 > missing_bytes)
2158 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002159 }
2160
2161 len = len1;
2162
2163 luaL_addlstring(&socket->b, blk1, len1);
2164 if (nblk == 2) {
2165 len += len2;
2166 luaL_addlstring(&socket->b, blk2, len2);
2167 }
2168
2169 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002170 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002171
2172 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002173 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174
2175 /* If the pattern reclaim to read all the data
2176 * in the connection, got out.
2177 */
2178 if (wanted == HLSR_READ_ALL)
2179 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002180 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181 goto connection_empty;
2182
2183 /* Return result. */
2184 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002185 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 return 1;
2187
2188connection_closed:
2189
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002190 xref_unlock(&socket->xref, peer);
2191
2192no_peer:
2193
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 /* If the buffer containds data. */
2195 if (socket->b.n > 0) {
2196 luaL_pushresult(&socket->b);
2197 return 1;
2198 }
2199 lua_pushnil(L);
2200 lua_pushstring(L, "connection closed.");
2201 return 2;
2202
2203connection_empty:
2204
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002205 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
2206 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002207 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002208 }
2209 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002210 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211 return 0;
2212}
2213
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002214/* This Lua function gets two parameters. The first one can be string
2215 * or a number. If the string is "*l", the user requires one line. If
2216 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217 * If the value is a number, the user require a number of bytes equal
2218 * to the value. The default value is "*l" (a line).
2219 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002220 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221 * integer takes this values:
2222 * -1 : read a line
2223 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002224 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002225 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002226 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227 * concatenated with the read data.
2228 */
2229__LJMP static int hlua_socket_receive(struct lua_State *L)
2230{
2231 int wanted = HLSR_READ_LINE;
2232 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002233 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002234 char *error;
2235 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002236 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237
2238 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2239 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2240
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002241 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002243 /* Check if we run on the same thread than the xreator thread.
2244 * We cannot access to the socket if the thread is different.
2245 */
2246 if (socket->tid != tid)
2247 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2248
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249 /* check for pattern. */
2250 if (lua_gettop(L) >= 2) {
2251 type = lua_type(L, 2);
2252 if (type == LUA_TSTRING) {
2253 pattern = lua_tostring(L, 2);
2254 if (strcmp(pattern, "*a") == 0)
2255 wanted = HLSR_READ_ALL;
2256 else if (strcmp(pattern, "*l") == 0)
2257 wanted = HLSR_READ_LINE;
2258 else {
2259 wanted = strtoll(pattern, &error, 10);
2260 if (*error != '\0')
2261 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2262 }
2263 }
2264 else if (type == LUA_TNUMBER) {
2265 wanted = lua_tointeger(L, 2);
2266 if (wanted < 0)
2267 WILL_LJMP(luaL_error(L, "Unsupported size."));
2268 }
2269 }
2270
2271 /* Set pattern. */
2272 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002273
2274 /* Check if we would replace the top by itself. */
2275 if (lua_gettop(L) != 2)
2276 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002277
Christopher Fauletc31b2002021-05-03 10:11:13 +02002278 /* Save index of the top of the stack because since buffers are used, it
2279 * may change
2280 */
2281 lastarg = lua_gettop(L);
2282
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002283 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002284 luaL_buffinit(L, &socket->b);
2285
2286 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002287 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 if (lua_type(L, 3) != LUA_TSTRING)
2289 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2290 pattern = lua_tolstring(L, 3, &len);
2291 luaL_addlstring(&socket->b, pattern, len);
2292 }
2293
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002294 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295}
2296
2297/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002298 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002299 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002300static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301{
2302 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002303 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304 struct appctx *appctx;
2305 size_t buf_len;
2306 const char *buf;
2307 int len;
2308 int send_len;
2309 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002310 struct xref *peer;
2311 struct stream_interface *si;
2312 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002314 /* Get hlua struct, or NULL if we execute from main lua state */
2315 hlua = hlua_gethlua(L);
2316
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317 /* Check if this lua stack is schedulable. */
2318 if (!hlua || !hlua->task)
2319 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2320 "'frontend', 'backend' or 'task'"));
2321
2322 /* Get object */
2323 socket = MAY_LJMP(hlua_checksocket(L, 1));
2324 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002325 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002327 /* Check if we run on the same thread than the xreator thread.
2328 * We cannot access to the socket if the thread is different.
2329 */
2330 if (socket->tid != tid)
2331 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2332
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002333 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002334 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002335 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002336 lua_pushinteger(L, -1);
2337 return 1;
2338 }
2339 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2340 si = appctx->owner;
2341 s = si_strm(si);
2342
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002344 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002345 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 lua_pushinteger(L, -1);
2347 return 1;
2348 }
2349
2350 /* Update the input buffer data. */
2351 buf += sent;
2352 send_len = buf_len - sent;
2353
2354 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002355 if (sent >= buf_len) {
2356 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002358 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002360 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002361 * the request buffer if its not required.
2362 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002363 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002364 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002365 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002366 }
2367
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002368 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002369 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002370 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002372 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373
2374 /* send data */
2375 if (len < send_len)
2376 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002377 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378
2379 /* "Not enough space" (-1), "Buffer too little to contain
2380 * the data" (-2) are not expected because the available length
2381 * is tested.
2382 * Other unknown error are also not expected.
2383 */
2384 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002385 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002386 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002387
sada05ed3302018-05-11 11:48:18 -07002388 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002390 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002391 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002392 return 1;
2393 }
2394
2395 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002396 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002397
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002398 s->req.rex = TICK_ETERNITY;
2399 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400
2401 /* Update length sent. */
2402 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002403 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002404
2405 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002406 if (sent + len >= buf_len) {
2407 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002408 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002409 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002410
2411hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002412 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2413 xref_unlock(&socket->xref, peer);
2414 WILL_LJMP(luaL_error(L, "out of memory"));
2415 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002416 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002417 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002418 return 0;
2419}
2420
2421/* This function initiate the send of data. It just check the input
2422 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002423 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002424 * "hlua_socket_write_yield" that can yield.
2425 *
2426 * The Lua function gets between 3 and 4 parameters. The first one is
2427 * the associated object. The second is a string buffer. The third is
2428 * a facultative integer that represents where is the buffer position
2429 * of the start of the data that can send. The first byte is the
2430 * position "1". The default value is "1". The fourth argument is a
2431 * facultative integer that represents where is the buffer position
2432 * of the end of the data that can send. The default is the last byte.
2433 */
2434static int hlua_socket_send(struct lua_State *L)
2435{
2436 int i;
2437 int j;
2438 const char *buf;
2439 size_t buf_len;
2440
2441 /* Check number of arguments. */
2442 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2443 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2444
2445 /* Get the string. */
2446 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2447
2448 /* Get and check j. */
2449 if (lua_gettop(L) == 4) {
2450 j = MAY_LJMP(luaL_checkinteger(L, 4));
2451 if (j < 0)
2452 j = buf_len + j + 1;
2453 if (j > buf_len)
2454 j = buf_len + 1;
2455 lua_pop(L, 1);
2456 }
2457 else
2458 j = buf_len;
2459
2460 /* Get and check i. */
2461 if (lua_gettop(L) == 3) {
2462 i = MAY_LJMP(luaL_checkinteger(L, 3));
2463 if (i < 0)
2464 i = buf_len + i + 1;
2465 if (i > buf_len)
2466 i = buf_len + 1;
2467 lua_pop(L, 1);
2468 } else
2469 i = 1;
2470
2471 /* Check bth i and j. */
2472 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002473 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474 return 1;
2475 }
2476 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002477 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002478 return 1;
2479 }
2480 if (i == 0)
2481 i = 1;
2482 if (j == 0)
2483 j = 1;
2484
2485 /* Pop the string. */
2486 lua_pop(L, 1);
2487
2488 /* Update the buffer length. */
2489 buf += i - 1;
2490 buf_len = j - i + 1;
2491 lua_pushlstring(L, buf, buf_len);
2492
2493 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002494 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002495
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002496 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002497}
2498
Willy Tarreau22b0a682015-06-17 19:43:49 +02002499#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2501{
2502 static char buffer[SOCKET_INFO_MAX_LEN];
2503 int ret;
2504 int len;
2505 char *p;
2506
2507 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2508 if (ret <= 0) {
2509 lua_pushnil(L);
2510 return 1;
2511 }
2512
2513 if (ret == AF_UNIX) {
2514 lua_pushstring(L, buffer+1);
2515 return 1;
2516 }
2517 else if (ret == AF_INET6) {
2518 buffer[0] = '[';
2519 len = strlen(buffer);
2520 buffer[len] = ']';
2521 len++;
2522 buffer[len] = ':';
2523 len++;
2524 p = buffer;
2525 }
2526 else if (ret == AF_INET) {
2527 p = buffer + 1;
2528 len = strlen(p);
2529 p[len] = ':';
2530 len++;
2531 }
2532 else {
2533 lua_pushnil(L);
2534 return 1;
2535 }
2536
2537 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2538 lua_pushnil(L);
2539 return 1;
2540 }
2541
2542 lua_pushstring(L, p);
2543 return 1;
2544}
2545
2546/* Returns information about the peer of the connection. */
2547__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2548{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002549 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002550 struct xref *peer;
2551 struct appctx *appctx;
2552 struct stream_interface *si;
2553 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002554 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002555
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002556 MAY_LJMP(check_args(L, 1, "getpeername"));
2557
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002558 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002559
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002560 /* Check if we run on the same thread than the xreator thread.
2561 * We cannot access to the socket if the thread is different.
2562 */
2563 if (socket->tid != tid)
2564 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2565
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002566 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002567 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002568 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002569 lua_pushnil(L);
2570 return 1;
2571 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002572 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2573 si = appctx->owner;
2574 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002576 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002577 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002578 lua_pushnil(L);
2579 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002580 }
2581
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002582 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002583 xref_unlock(&socket->xref, peer);
2584 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585}
2586
2587/* Returns information about my connection side. */
2588static int hlua_socket_getsockname(struct lua_State *L)
2589{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002590 struct hlua_socket *socket;
2591 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002592 struct appctx *appctx;
2593 struct xref *peer;
2594 struct stream_interface *si;
2595 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002596 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002597
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002598 MAY_LJMP(check_args(L, 1, "getsockname"));
2599
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002600 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002601
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002602 /* Check if we run on the same thread than the xreator thread.
2603 * We cannot access to the socket if the thread is different.
2604 */
2605 if (socket->tid != tid)
2606 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2607
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002608 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002609 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002610 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002611 lua_pushnil(L);
2612 return 1;
2613 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002614 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2615 si = appctx->owner;
2616 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002617
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002618 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002619 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002620 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002621 lua_pushnil(L);
2622 return 1;
2623 }
2624
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002625 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002626 xref_unlock(&socket->xref, peer);
2627 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002628}
2629
2630/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002631static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632 .obj_type = OBJ_TYPE_APPLET,
2633 .name = "<LUA_TCP>",
2634 .fct = hlua_socket_handler,
2635 .release = hlua_socket_release,
2636};
2637
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002638__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002639{
2640 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002641 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002642 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002643 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002644 struct stream_interface *si;
2645 struct stream *s;
2646
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002647 /* Get hlua struct, or NULL if we execute from main lua state */
2648 hlua = hlua_gethlua(L);
2649 if (!hlua)
2650 return 0;
2651
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002652 /* Check if we run on the same thread than the xreator thread.
2653 * We cannot access to the socket if the thread is different.
2654 */
2655 if (socket->tid != tid)
2656 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2657
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002658 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002659 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002660 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002661 lua_pushnil(L);
2662 lua_pushstring(L, "Can't connect");
2663 return 2;
2664 }
2665 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2666 si = appctx->owner;
2667 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002668
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002669 /* Check if we run on the same thread than the xreator thread.
2670 * We cannot access to the socket if the thread is different.
2671 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002672 if (socket->tid != tid) {
2673 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002674 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002675 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002676
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002678 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002679 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002680 lua_pushnil(L);
2681 lua_pushstring(L, "Can't connect");
2682 return 2;
2683 }
2684
Willy Tarreaue09101e2018-10-16 17:37:12 +02002685 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002686
2687 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002688 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002689 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002690 lua_pushinteger(L, 1);
2691 return 1;
2692 }
2693
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002694 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2695 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002696 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002697 }
2698 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002699 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002700 return 0;
2701}
2702
2703/* This function fail or initite the connection. */
2704__LJMP static int hlua_socket_connect(struct lua_State *L)
2705{
2706 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002707 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002708 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002709 struct hlua *hlua;
2710 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002711 int low, high;
2712 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002713 struct xref *peer;
2714 struct stream_interface *si;
2715 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002716
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002717 if (lua_gettop(L) < 2)
2718 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002719
2720 /* Get args. */
2721 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002722
2723 /* Check if we run on the same thread than the xreator thread.
2724 * We cannot access to the socket if the thread is different.
2725 */
2726 if (socket->tid != tid)
2727 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2728
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002729 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002730 if (lua_gettop(L) >= 3) {
2731 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002732 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733
Tim Duesterhus6edab862018-01-06 19:04:45 +01002734 /* Force the ip to end with a colon, to support IPv6 addresses
2735 * that are not enclosed within square brackets.
2736 */
2737 if (port > 0) {
2738 luaL_buffinit(L, &b);
2739 luaL_addstring(&b, ip);
2740 luaL_addchar(&b, ':');
2741 luaL_pushresult(&b);
2742 ip = lua_tolstring(L, lua_gettop(L), NULL);
2743 }
2744 }
2745
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002746 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002747 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002748 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002749 lua_pushnil(L);
2750 return 1;
2751 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002752
2753 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002754 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 +02002755 if (!addr) {
2756 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002757 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002758 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002759
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002760 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002761 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002762 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002763 if (port == -1) {
2764 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002765 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002766 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002767 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2768 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002769 if (port == -1) {
2770 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002771 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002772 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002773 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002774 }
2775 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002776
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002777 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2778 si = appctx->owner;
2779 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002780
Willy Tarreau9b7587a2020-10-15 07:32:10 +02002781 if (!sockaddr_alloc(&s->target_addr, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002782 xref_unlock(&socket->xref, peer);
2783 WILL_LJMP(luaL_error(L, "connect: internal error"));
2784 }
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002785 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002786
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002787 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002788 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002789 if (!hlua)
2790 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002791
2792 /* inform the stream that we want to be notified whenever the
2793 * connection completes.
2794 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002795 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002796 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002797 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002798
Willy Tarreauf31af932020-01-14 09:59:38 +01002799 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002800
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002801 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2802 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002803 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002804 }
2805 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002806
2807 task_wakeup(s->task, TASK_WOKEN_INIT);
2808 /* Return yield waiting for connection. */
2809
Willy Tarreau9635e032018-10-16 17:52:55 +02002810 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002811
2812 return 0;
2813}
2814
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002815#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002816__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2817{
2818 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002819 struct xref *peer;
2820 struct appctx *appctx;
2821 struct stream_interface *si;
2822 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002823
2824 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2825 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002826
2827 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002828 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002829 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002830 lua_pushnil(L);
2831 return 1;
2832 }
2833 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2834 si = appctx->owner;
2835 s = si_strm(si);
2836
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002837 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002838 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002839 return MAY_LJMP(hlua_socket_connect(L));
2840}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002841#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002842
2843__LJMP static int hlua_socket_setoption(struct lua_State *L)
2844{
2845 return 0;
2846}
2847
2848__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2849{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002850 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002851 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002852 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002853 struct xref *peer;
2854 struct appctx *appctx;
2855 struct stream_interface *si;
2856 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002857
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002858 MAY_LJMP(check_args(L, 2, "settimeout"));
2859
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002860 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002861
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002862 /* convert the timeout to millis */
2863 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002864
Thierry Fournier17a921b2018-03-08 09:59:02 +01002865 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002866 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002867 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2868
Mark Lakes56cc1252018-03-27 09:48:06 +02002869 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002870 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002871
2872 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002873 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002874 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002875
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002876 /* Check if we run on the same thread than the xreator thread.
2877 * We cannot access to the socket if the thread is different.
2878 */
2879 if (socket->tid != tid)
2880 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2881
Mark Lakes56cc1252018-03-27 09:48:06 +02002882 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002883 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002884 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002885 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2886 WILL_LJMP(lua_error(L));
2887 return 0;
2888 }
2889 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2890 si = appctx->owner;
2891 s = si_strm(si);
2892
Cyril Bonté7bb63452018-08-17 23:51:02 +02002893 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002894 s->req.rto = tmout;
2895 s->req.wto = tmout;
2896 s->res.rto = tmout;
2897 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002898 s->req.rex = tick_add_ifset(now_ms, tmout);
2899 s->req.wex = tick_add_ifset(now_ms, tmout);
2900 s->res.rex = tick_add_ifset(now_ms, tmout);
2901 s->res.wex = tick_add_ifset(now_ms, tmout);
2902
2903 s->task->expire = tick_add_ifset(now_ms, tmout);
2904 task_queue(s->task);
2905
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002906 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002907
Thierry Fourniere9636f12018-03-08 09:54:32 +01002908 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002909 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002910}
2911
2912__LJMP static int hlua_socket_new(lua_State *L)
2913{
2914 struct hlua_socket *socket;
2915 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002916 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002917 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002918
2919 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002920 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002921 hlua_pusherror(L, "socket: full stack");
2922 goto out_fail_conf;
2923 }
2924
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002925 /* Create the object: obj[0] = userdata. */
2926 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002927 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002928 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002929 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002930 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002931
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002932 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002933 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002934 hlua_pusherror(L, "socket: uninitialized pools.");
2935 goto out_fail_conf;
2936 }
2937
Willy Tarreau87b09662015-04-03 00:22:06 +02002938 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002939 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2940 lua_setmetatable(L, -2);
2941
Willy Tarreaud420a972015-04-06 00:39:18 +02002942 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002943 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002944 if (!appctx) {
2945 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002946 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002947 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002948
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002949 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002950 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002951 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2952 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002953
Willy Tarreaud420a972015-04-06 00:39:18 +02002954 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002955 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002956 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002957 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002958 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002959 }
2960
Christopher Faulet26256f82020-09-14 11:40:13 +02002961 strm = stream_new(sess, &appctx->obj_type, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002962 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002963 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002964 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002965 }
2966
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002967 /* Initialise cross reference between stream and Lua socket object. */
2968 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002969
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970 /* Configure "right" stream interface. this "si" is used to connect
2971 * and retrieve data from the server. The connection is initialized
2972 * with the "struct server".
2973 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002974 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002975
2976 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002977 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002978 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002979
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002980 return 1;
2981
Willy Tarreaud420a972015-04-06 00:39:18 +02002982 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002983 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002984 out_fail_sess:
2985 appctx_free(appctx);
2986 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002987 WILL_LJMP(lua_error(L));
2988 return 0;
2989}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002990
2991/*
2992 *
2993 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002994 * Class Channel
2995 *
2996 *
2997 */
2998
2999/* Returns the struct hlua_channel join to the class channel in the
3000 * stack entry "ud" or throws an argument error.
3001 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003002__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003003{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003004 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003005}
3006
Willy Tarreau47860ed2015-03-10 14:07:50 +01003007/* Pushes the channel onto the top of the stack. If the stask does not have a
3008 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003009 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003010static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003011{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003012 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003013 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003014 return 0;
3015
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003016 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003017 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003018 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003019
3020 /* Pop a class sesison metatable and affect it to the userdata. */
3021 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3022 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003023 return 1;
3024}
3025
Christopher Faulet9f55a502020-02-25 15:21:02 +01003026/* Helper function returning a filter attached to a channel at the position <ud>
3027 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003028 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003029 * initialized.
3030 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003031static 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 +01003032{
3033 struct filter *filter = NULL;
3034
3035 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3036 struct hlua_flt_ctx *flt_ctx;
3037
3038 filter = lua_touserdata (L, -1);
3039 flt_ctx = filter->ctx;
3040 if (hlua_filter_from_payload(filter)) {
3041 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3042 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3043 }
3044 }
3045
3046 lua_pop(L, 1);
3047 return filter;
3048}
3049
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003050/* Copies <len> bytes of data present in the channel's buffer, starting at the
3051* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003052* responsibility to ensure <len> and <offset> are valid. It always return the
3053* length of the built string. <len> may be 0, in this case, an empty string is
3054* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003055*/
3056static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003058 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003059 luaL_Buffer b;
3060
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003061 block1 = len;
3062 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3063 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3064 block2 = len - block1;
3065
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003066 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003067 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3068 if (block2)
3069 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003070 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003071 return len;
3072}
3073
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003074/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3075 * function returns -1 if data cannot be copied. Otherwise, it returns the
3076 * number of bytes copied.
3077 */
3078static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3079{
3080 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003081
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003082 /* Nothing to do, just return */
3083 if (unlikely(istlen(str) == 0))
3084 goto end;
3085
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003086 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003087 ret = -1;
3088 goto end;
3089 }
3090 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3091
3092 end:
3093 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003094}
3095
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003096/* Removes <len> bytes of data at the absolute position <offset>.
3097 */
3098static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3099{
3100 size_t end = offset + len;
3101
3102 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3103 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3104 b_data(&chn->buf) - end, -len);
3105 b_sub(&chn->buf, len);
3106}
3107
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003108/* Copies input data in the channel's buffer. It is possible to set a specific
3109 * offset (0 by default) and a length (all remaining input data starting for the
3110 * offset by default). If there is not enough input data and more data can be
3111 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003112 *
3113 * From an action, All input data are considered. For a filter, the offset and
3114 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003115 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003116__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003117{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003118 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003119 struct filter *filter;
3120 size_t input, output;
3121 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003122
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003123 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003124
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003125 output = co_data(chn);
3126 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003127
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003128 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3129 if (filter && !hlua_filter_from_payload(filter))
3130 WILL_LJMP(lua_error(L));
3131
3132 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003133 if (lua_gettop(L) > 1) {
3134 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3135 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003136 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003137 offset += output;
3138 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003139 lua_pushfstring(L, "offset out of range.");
3140 WILL_LJMP(lua_error(L));
3141 }
3142 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003143 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003144 if (lua_gettop(L) == 3) {
3145 len = MAY_LJMP(luaL_checkinteger(L, 3));
3146 if (!len)
3147 goto dup;
3148 if (len == -1)
3149 len = global.tune.bufsize;
3150 if (len < 0) {
3151 lua_pushfstring(L, "length out of range.");
3152 WILL_LJMP(lua_error(L));
3153 }
3154 }
3155
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003156 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003157 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3158 /* Yield waiting for more data, as requested */
3159 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3160 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003161 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003162 }
3163
3164 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003165 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003166 return 1;
3167}
3168
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003169/* Copies the first line (including the trailing LF) of input data in the
3170 * channel's buffer. It is possible to set a specific offset (0 by default) and
3171 * a length (all remaining input data starting for the offset by default). If
3172 * there is not enough input data and more data can be received, the function
3173 * yields. If a length is explicitly specified, no more data are
3174 * copied. Otherwise, if no LF is found and more data can be received, this
3175 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003176 *
3177 * From an action, All input data are considered. For a filter, the offset and
3178 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003179 */
3180__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003181{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003182 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003183 struct filter *filter;
3184 size_t l, input, output;
3185 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003186
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003187 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003188 output = co_data(chn);
3189 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003190
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003191 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3192 if (filter && !hlua_filter_from_payload(filter))
3193 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003194
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003195 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003196 if (lua_gettop(L) > 1) {
3197 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3198 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003199 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003200 offset += output;
3201 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003202 lua_pushfstring(L, "offset out of range.");
3203 WILL_LJMP(lua_error(L));
3204 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003205 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003206
3207 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003208 if (lua_gettop(L) == 3) {
3209 len = MAY_LJMP(luaL_checkinteger(L, 3));
3210 if (!len)
3211 goto dup;
3212 if (len == -1)
3213 len = global.tune.bufsize;
3214 if (len < 0) {
3215 lua_pushfstring(L, "length out of range.");
3216 WILL_LJMP(lua_error(L));
3217 }
3218 }
3219
3220 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003221 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003222 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003223 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003224 len = l+1;
3225 goto dup;
3226 }
3227 }
3228
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003229 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003230 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3231 /* Yield waiting for more data */
3232 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3233 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003234 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003235 }
3236
3237 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003238 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003239 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003240}
3241
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003242/* [ DEPRECATED ]
3243 *
3244 * Duplicate all input data foud in the channel's buffer. The data are not
3245 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003246 *
3247 * From an action, All input data are considered. For a filter, the offset and
3248 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003249 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003250__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003251{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003252 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003253 struct filter *filter;
3254 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003255
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003256 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003257 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003258 if (IS_HTX_STRM(chn_strm(chn))) {
3259 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3260 WILL_LJMP(lua_error(L));
3261 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003262
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003263 offset = co_data(chn);
3264 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003265
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003266 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3267 if (filter && !hlua_filter_from_payload(filter))
3268 WILL_LJMP(lua_error(L));
3269
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003270 if (!ci_data(chn) && channel_input_closed(chn)) {
3271 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003272 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003273 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003274
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003275 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003276 return 1;
3277}
3278
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003279/* [ DEPRECATED ]
3280 *
3281 * Get all input data foud in the channel's buffer. The data are removed from
3282 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3283 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003284 *
3285 * From an action, All input data are considered. For a filter, the offset and
3286 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003287 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003288__LJMP static int hlua_channel_get(lua_State *L)
3289{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003290 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003291 struct filter *filter;
3292 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003293 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003294
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003295 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003296 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3297 if (IS_HTX_STRM(chn_strm(chn))) {
3298 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3299 WILL_LJMP(lua_error(L));
3300 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003301
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003302 offset = co_data(chn);
3303 len = ci_data(chn);
3304
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003305 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3306 if (filter && !hlua_filter_from_payload(filter))
3307 WILL_LJMP(lua_error(L));
3308
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003309 if (!ci_data(chn) && channel_input_closed(chn)) {
3310 lua_pushnil(L);
3311 return 1;
3312 }
3313
3314 ret = _hlua_channel_dup(chn, L, offset, len);
3315 _hlua_channel_delete(chn, offset, ret);
3316 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003317}
3318
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003319/* This functions consumes and returns one line. If the channel is closed,
3320 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003321 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003322 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003323 *
3324 * From an action, All input data are considered. For a filter, the offset and
3325 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003326 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003327__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003328{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003329 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003330 struct filter *filter;
3331 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003332 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003333
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003334 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003335
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003336 offset = co_data(chn);
3337 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003338
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003339 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3340 if (filter && !hlua_filter_from_payload(filter))
3341 WILL_LJMP(lua_error(L));
3342
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003343 if (!ci_data(chn) && channel_input_closed(chn)) {
3344 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003345 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003346 }
3347
3348 for (l = 0; l < len; l++) {
3349 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3350 len = l+1;
3351 goto dup;
3352 }
3353 }
3354
3355 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3356 /* Yield waiting for more data */
3357 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3358 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003359
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003360 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003361 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003362 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003363 return 1;
3364}
3365
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003366/* [ DEPRECATED ]
3367 *
3368 * Check arguments for the function "hlua_channel_getline_yield".
3369 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003370__LJMP static int hlua_channel_getline(lua_State *L)
3371{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003372 struct channel *chn;
3373
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003374 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003375 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3376 if (IS_HTX_STRM(chn_strm(chn))) {
3377 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3378 WILL_LJMP(lua_error(L));
3379 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003380 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3381}
3382
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003383/* Retrieves a given amount of input data at the given offset. By default all
3384 * available input data are returned. The offset may be negactive to start from
3385 * the end of input data. The length may be -1 to set it to the maximum buffer
3386 * size.
3387 */
3388__LJMP static int hlua_channel_get_data(lua_State *L)
3389{
3390 struct channel *chn;
3391
3392 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3393 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3394 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3395 if (IS_HTX_STRM(chn_strm(chn))) {
3396 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3397 WILL_LJMP(lua_error(L));
3398 }
3399 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3400}
3401
3402/* Retrieves a given amount of input data at the given offset. By default all
3403 * available input data are returned. The offset may be negactive to start from
3404 * the end of input data. The length may be -1 to set it to the maximum buffer
3405 * size.
3406 */
3407__LJMP static int hlua_channel_get_line(lua_State *L)
3408{
3409 struct channel *chn;
3410
3411 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3412 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3413 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3414 if (IS_HTX_STRM(chn_strm(chn))) {
3415 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3416 WILL_LJMP(lua_error(L));
3417 }
3418 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3419}
3420
3421/* Appends a string into the input side of channel. It returns the length of the
3422 * written string, or -1 if the channel is closed or if the buffer size is too
3423 * little for the data. 0 may be returned if nothing is copied. This function
3424 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003425 *
3426 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003427 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003428__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003429{
Christopher Faulet23976d92021-08-06 09:59:49 +02003430 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003431 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003432 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003433 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003434 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003435
3436 MAY_LJMP(check_args(L, 2, "append"));
3437 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003438 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003439 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003440 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003441 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003442 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003443
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003444 offset = co_data(chn);
3445 len = ci_data(chn);
3446
3447 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3448 if (filter && !hlua_filter_from_payload(filter))
3449 WILL_LJMP(lua_error(L));
3450
3451 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3452 if (ret > 0 && filter) {
3453 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3454
3455 flt_update_offsets(filter, chn, ret);
3456 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3457 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003458 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003459 return 1;
3460}
3461
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003462/* Prepends a string into the input side of channel. It returns the length of the
3463 * written string, or -1 if the channel is closed or if the buffer size is too
3464 * little for the data. 0 may be returned if nothing is copied. This function
3465 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003466 *
3467 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003468 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003469__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003470{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003471 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003472 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003473 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003474 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003475 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003476
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003477 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003478 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003479 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3480 if (IS_HTX_STRM(chn_strm(chn))) {
3481 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3482 WILL_LJMP(lua_error(L));
3483 }
3484
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003485 offset = co_data(chn);
3486 len = ci_data(chn);
3487
3488 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3489 if (filter && !hlua_filter_from_payload(filter))
3490 WILL_LJMP(lua_error(L));
3491
3492 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3493 if (ret > 0 && filter) {
3494 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3495
3496 flt_update_offsets(filter, chn, ret);
3497 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3498 }
3499
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003500 lua_pushinteger(L, ret);
3501 return 1;
3502}
3503
3504/* Inserts a given amount of input data at the given offset by a string
3505 * content. By default the string is appended at the end of input data. It
3506 * returns the length of the written string, or -1 if the channel is closed or
3507 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003508 *
3509 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003510 */
3511__LJMP static int hlua_channel_insert_data(lua_State *L)
3512{
3513 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003514 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003515 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003516 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003517 int ret, offset;
3518
3519 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3520 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3521 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3522 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003523
3524 output = co_data(chn);
3525 input = ci_data(chn);
3526
3527 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3528 if (filter && !hlua_filter_from_payload(filter))
3529 WILL_LJMP(lua_error(L));
3530
3531 offset = input + output;
3532 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003533 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003534 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003535 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003536 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003537 if (offset < output || offset > output + input) {
3538 lua_pushfstring(L, "offset out of range.");
3539 WILL_LJMP(lua_error(L));
3540 }
3541 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003542 if (IS_HTX_STRM(chn_strm(chn))) {
3543 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3544 WILL_LJMP(lua_error(L));
3545 }
3546
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003547 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3548 if (ret > 0 && filter) {
3549 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003550
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003551 flt_update_offsets(filter, chn, ret);
3552 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003553 }
3554
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003555 lua_pushinteger(L, ret);
3556 return 1;
3557}
3558/* Replaces a given amount of input data at the given offset by a string
3559 * content. By default all remaining data are removed (offset = 0 and len =
3560 * -1). It returns the length of the written string, or -1 if the channel is
3561 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003562 *
3563 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003564 */
3565__LJMP static int hlua_channel_set_data(lua_State *L)
3566{
3567 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003568 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003569 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003570 size_t sz, input, output;
3571 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003572
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003573 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3574 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3575 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3576 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003577
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003578 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003579 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003580 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003581 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003582
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003583 output = co_data(chn);
3584 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003585
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003586 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3587 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003588 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003589
3590 offset = output;
3591 if (lua_gettop(L) > 2) {
3592 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3593 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003594 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003595 offset += output;
3596 if (offset < output || offset > input + output) {
3597 lua_pushfstring(L, "offset out of range.");
3598 WILL_LJMP(lua_error(L));
3599 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003600 }
3601
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003602 len = output + input - offset;
3603 if (lua_gettop(L) == 4) {
3604 len = MAY_LJMP(luaL_checkinteger(L, 4));
3605 if (!len)
3606 goto set;
3607 if (len == -1)
3608 len = output + input - offset;
3609 if (len < 0 || offset + len > output + input) {
3610 lua_pushfstring(L, "length out of range.");
3611 WILL_LJMP(lua_error(L));
3612 }
3613 }
3614
3615 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003616 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003617 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003618 lua_pushinteger(L, -1);
3619 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003620 _hlua_channel_delete(chn, offset, len);
3621 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3622 if (filter) {
3623 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3624
3625 len -= (ret > 0 ? ret : 0);
3626 flt_update_offsets(filter, chn, -len);
3627 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3628 }
3629
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003630 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003631 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003632 return 1;
3633}
3634
3635/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003636 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003637 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003638 *
3639 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003640 */
3641__LJMP static int hlua_channel_del_data(lua_State *L)
3642{
3643 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003644 struct filter *filter;
3645 size_t input, output;
3646 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003647
3648 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3649 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3650 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003651
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003652 if (IS_HTX_STRM(chn_strm(chn))) {
3653 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3654 WILL_LJMP(lua_error(L));
3655 }
3656
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003657 output = co_data(chn);
3658 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003659
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003660 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3661 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003662 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003663
3664 offset = output;
3665 if (lua_gettop(L) > 2) {
3666 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3667 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003668 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003669 offset += output;
3670 if (offset < output || offset > input + output) {
3671 lua_pushfstring(L, "offset out of range.");
3672 WILL_LJMP(lua_error(L));
3673 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003674 }
3675
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003676 len = output + input - offset;
3677 if (lua_gettop(L) == 4) {
3678 len = MAY_LJMP(luaL_checkinteger(L, 4));
3679 if (!len)
3680 goto end;
3681 if (len == -1)
3682 len = output + input - offset;
3683 if (len < 0 || offset + len > output + input) {
3684 lua_pushfstring(L, "length out of range.");
3685 WILL_LJMP(lua_error(L));
3686 }
3687 }
3688
3689 _hlua_channel_delete(chn, offset, len);
3690 if (filter) {
3691 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3692
3693 flt_update_offsets(filter, chn, -len);
3694 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3695 }
3696
3697 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003698 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003699 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003700}
3701
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003702/* Append data in the output side of the buffer. This data is immediately
3703 * sent. The function returns the amount of data written. If the buffer
3704 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003705 * if the channel is closed.
3706 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003707__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003708{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003709 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003710 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003711 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003712 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003713 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003714 struct hlua *hlua;
3715
3716 /* Get hlua struct, or NULL if we execute from main lua state */
3717 hlua = hlua_gethlua(L);
3718 if (!hlua) {
3719 lua_pushnil(L);
3720 return 1;
3721 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003722
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003723 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3724 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3725 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003726
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003727 offset = co_data(chn);
3728 len = ci_data(chn);
3729
3730 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3731 if (filter && !hlua_filter_from_payload(filter))
3732 WILL_LJMP(lua_error(L));
3733
3734
Willy Tarreau47860ed2015-03-10 14:07:50 +01003735 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003736 lua_pushinteger(L, -1);
3737 return 1;
3738 }
3739
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003740 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003741 if (len > sz -l) {
3742 if (filter) {
3743 lua_pushinteger(L, -1);
3744 return 1;
3745 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003746 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003747 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003748
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003749 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003750 if (ret == -1) {
3751 lua_pop(L, 1);
3752 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003753 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003754 }
3755 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003756 if (filter) {
3757 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3758
3759
3760 flt_update_offsets(filter, chn, ret);
3761 FLT_OFF(filter, chn) += ret;
3762 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3763 }
3764 else
3765 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003766
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003767 l += ret;
3768 lua_pop(L, 1);
3769 lua_pushinteger(L, l);
3770 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003771
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003772 if (l < sz) {
3773 /* Yield only if the channel's output is not empty.
3774 * Otherwise it means we cannot add more data. */
3775 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003776 return 1;
3777
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003778 /* If we are waiting for space in the response buffer, we
3779 * must set the flag WAKERESWR. This flag required the task
3780 * wake up if any activity is detected on the response buffer.
3781 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003782 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003783 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003784 else
3785 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003786 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003787 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003788
3789 return 1;
3790}
3791
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003792/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003793 * yield the LUA process, and resume it without checking the
3794 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003795 *
3796 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003797 */
3798__LJMP static int hlua_channel_send(lua_State *L)
3799{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003800 struct channel *chn;
3801
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003802 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003803 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3804 if (IS_HTX_STRM(chn_strm(chn))) {
3805 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3806 WILL_LJMP(lua_error(L));
3807 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003808 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003809 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003810}
3811
3812/* This function forward and amount of butes. The data pass from
3813 * the input side of the buffer to the output side, and can be
3814 * forwarded. This function never fails.
3815 *
3816 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003817 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003818 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003819__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003820{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003821 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003822 struct filter *filter;
3823 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003824 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003825 struct hlua *hlua;
3826
3827 /* Get hlua struct, or NULL if we execute from main lua state */
3828 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003829 if (!hlua) {
3830 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003831 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003832 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003833
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003834 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003835 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003836 l = MAY_LJMP(luaL_checkinteger(L, -1));
3837
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 offset = co_data(chn);
3839 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003840
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003841 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3842 if (filter && !hlua_filter_from_payload(filter))
3843 WILL_LJMP(lua_error(L));
3844
3845 max = fwd - l;
3846 if (max > len)
3847 max = len;
3848
3849 if (filter) {
3850 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3851
3852 FLT_OFF(filter, chn) += max;
3853 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3854 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3855 }
3856 else
3857 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003858
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003859 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003860 lua_pop(L, 1);
3861 lua_pushinteger(L, l);
3862
3863 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003864 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003865 /* The the input channel or the output channel are closed, we
3866 * must return the amount of data forwarded.
3867 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003868 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003869 return 1;
3870
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003871 /* If we are waiting for space data in the response buffer, we
3872 * must set the flag WAKERESWR. This flag required the task
3873 * wake up if any activity is detected on the response buffer.
3874 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003875 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003876 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003877 else
3878 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003879
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003880 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003881 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003882 }
3883
3884 return 1;
3885}
3886
3887/* Just check the input and prepare the stack for the previous
3888 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003889 *
3890 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003891 */
3892__LJMP static int hlua_channel_forward(lua_State *L)
3893{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003894 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003895
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003896 MAY_LJMP(check_args(L, 2, "forward"));
3897 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3898 if (IS_HTX_STRM(chn_strm(chn))) {
3899 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3900 WILL_LJMP(lua_error(L));
3901 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003902 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003903 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003904}
3905
3906/* Just returns the number of bytes available in the input
3907 * side of the buffer. This function never fails.
3908 */
3909__LJMP static int hlua_channel_get_in_len(lua_State *L)
3910{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003911 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003912 struct filter *filter;
3913 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003914
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003915 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003916 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003917
3918 output = co_data(chn);
3919 input = ci_data(chn);
3920 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3921 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3922 lua_pushinteger(L, input);
3923 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003924 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003925
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003926 lua_pushinteger(L, htx->data - co_data(chn));
3927 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003928 return 1;
3929}
3930
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003931/* Returns true if the channel is full. */
3932__LJMP static int hlua_channel_is_full(lua_State *L)
3933{
3934 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003935
3936 MAY_LJMP(check_args(L, 1, "is_full"));
3937 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003938 /* ignore the reserve, we are not on a producer side (ie in an
3939 * applet).
3940 */
3941 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003942 return 1;
3943}
3944
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003945/* Returns true if the channel may still receive data. */
3946__LJMP static int hlua_channel_may_recv(lua_State *L)
3947{
3948 struct channel *chn;
3949
3950 MAY_LJMP(check_args(L, 1, "may_recv"));
3951 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3952 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3953 return 1;
3954}
3955
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003956/* Returns true if the channel is the response channel. */
3957__LJMP static int hlua_channel_is_resp(lua_State *L)
3958{
3959 struct channel *chn;
3960
3961 MAY_LJMP(check_args(L, 1, "is_resp"));
3962 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3963
3964 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3965 return 1;
3966}
3967
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003968/* Just returns the number of bytes available in the output
3969 * side of the buffer. This function never fails.
3970 */
3971__LJMP static int hlua_channel_get_out_len(lua_State *L)
3972{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003973 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003974 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003975
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003976 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003977 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003978
3979 output = co_data(chn);
3980 input = ci_data(chn);
3981 hlua_channel_filter(L, 1, chn, &output, &input);
3982
3983 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003984 return 1;
3985}
3986
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003987/*
3988 *
3989 *
3990 * Class Fetches
3991 *
3992 *
3993 */
3994
3995/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003996 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003997 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003998__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003999{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004000 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004001}
4002
4003/* This function creates and push in the stack a fetch object according
4004 * with a current TXN.
4005 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004006static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004007{
Willy Tarreau7073c472015-04-06 11:15:40 +02004008 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004009
4010 /* Check stack size. */
4011 if (!lua_checkstack(L, 3))
4012 return 0;
4013
4014 /* Create the object: obj[0] = userdata.
4015 * Note that the base of the Fetches object is the
4016 * transaction object.
4017 */
4018 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004019 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004020 lua_rawseti(L, -2, 0);
4021
Willy Tarreau7073c472015-04-06 11:15:40 +02004022 hsmp->s = txn->s;
4023 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004024 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004025 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004026
4027 /* Pop a class sesison metatable and affect it to the userdata. */
4028 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4029 lua_setmetatable(L, -2);
4030
4031 return 1;
4032}
4033
4034/* This function is an LUA binding. It is called with each sample-fetch.
4035 * It uses closure argument to store the associated sample-fetch. It
4036 * returns only one argument or throws an error. An error is thrown
4037 * only if an error is encountered during the argument parsing. If
4038 * the "sample-fetch" function fails, nil is returned.
4039 */
4040__LJMP static int hlua_run_sample_fetch(lua_State *L)
4041{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004042 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004043 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004044 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004045 int i;
4046 struct sample smp;
4047
4048 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004049 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004050
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004051 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004052 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004053
Thierry FOURNIERca988662015-12-20 18:43:03 +01004054 /* Check execution authorization. */
4055 if (f->use & SMP_USE_HTTP_ANY &&
4056 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4057 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4058 "is not available in Lua services", f->kw);
4059 WILL_LJMP(lua_error(L));
4060 }
4061
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004062 /* Get extra arguments. */
4063 for (i = 0; i < lua_gettop(L) - 1; i++) {
4064 if (i >= ARGM_NBARGS)
4065 break;
4066 hlua_lua2arg(L, i + 2, &args[i]);
4067 }
4068 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004069 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004070
4071 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004072 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004073
4074 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004075 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004076 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004077 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004078 }
4079
4080 /* Initialise the sample. */
4081 memset(&smp, 0, sizeof(smp));
4082
4083 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004084 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004085 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004086 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004087 lua_pushstring(L, "");
4088 else
4089 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004090 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004091 }
4092
4093 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004094 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004095 hlua_smp2lua_str(L, &smp);
4096 else
4097 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004098
4099 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004100 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004101 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004102
4103 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004104 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004105 WILL_LJMP(lua_error(L));
4106 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004107}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004108
4109/*
4110 *
4111 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004112 * Class Converters
4113 *
4114 *
4115 */
4116
4117/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004118 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004119 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004120__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004121{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004122 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004123}
4124
4125/* This function creates and push in the stack a Converters object
4126 * according with a current TXN.
4127 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004128static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004129{
Willy Tarreau7073c472015-04-06 11:15:40 +02004130 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004131
4132 /* Check stack size. */
4133 if (!lua_checkstack(L, 3))
4134 return 0;
4135
4136 /* Create the object: obj[0] = userdata.
4137 * Note that the base of the Converters object is the
4138 * same than the TXN object.
4139 */
4140 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004141 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004142 lua_rawseti(L, -2, 0);
4143
Willy Tarreau7073c472015-04-06 11:15:40 +02004144 hsmp->s = txn->s;
4145 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004146 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004147 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004148
Willy Tarreau87b09662015-04-03 00:22:06 +02004149 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004150 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4151 lua_setmetatable(L, -2);
4152
4153 return 1;
4154}
4155
4156/* This function is an LUA binding. It is called with each converter.
4157 * It uses closure argument to store the associated converter. It
4158 * returns only one argument or throws an error. An error is thrown
4159 * only if an error is encountered during the argument parsing. If
4160 * the converter function function fails, nil is returned.
4161 */
4162__LJMP static int hlua_run_sample_conv(lua_State *L)
4163{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004164 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004165 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004166 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004167 int i;
4168 struct sample smp;
4169
4170 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004171 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004172
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004173 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004174 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004175
4176 /* Get extra arguments. */
4177 for (i = 0; i < lua_gettop(L) - 2; i++) {
4178 if (i >= ARGM_NBARGS)
4179 break;
4180 hlua_lua2arg(L, i + 3, &args[i]);
4181 }
4182 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004183 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004184
4185 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004186 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004187
4188 /* Run the special args checker. */
4189 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4190 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004191 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004192 }
4193
4194 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004195 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004196 if (!hlua_lua2smp(L, 2, &smp)) {
4197 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004198 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004199 }
4200
Willy Tarreau1777ea62016-03-10 16:15:46 +01004201 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4202
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004203 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004204 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004205 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004206 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004207 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004208 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004209 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4210 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004211 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004212 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004213 }
4214
4215 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004216 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004217 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004218 lua_pushstring(L, "");
4219 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004220 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004221 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004222 }
4223
4224 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004225 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004226 hlua_smp2lua_str(L, &smp);
4227 else
4228 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004229 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004230 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004231 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004232
4233 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004234 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004235 WILL_LJMP(lua_error(L));
4236 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004237}
4238
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004239/*
4240 *
4241 *
4242 * Class AppletTCP
4243 *
4244 *
4245 */
4246
4247/* Returns a struct hlua_txn if the stack entry "ud" is
4248 * a class stream, otherwise it throws an error.
4249 */
4250__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4251{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004252 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004253}
4254
4255/* This function creates and push in the stack an Applet object
4256 * according with a current TXN.
4257 */
4258static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4259{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004260 struct hlua_appctx *luactx;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004261 struct stream_interface *si = ctx->owner;
4262 struct stream *s = si_strm(si);
4263 struct proxy *p = s->be;
4264
4265 /* Check stack size. */
4266 if (!lua_checkstack(L, 3))
4267 return 0;
4268
4269 /* Create the object: obj[0] = userdata.
4270 * Note that the base of the Converters object is the
4271 * same than the TXN object.
4272 */
4273 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004274 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004275 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004276 luactx->appctx = ctx;
4277 luactx->htxn.s = s;
4278 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004279
4280 /* Create the "f" field that contains a list of fetches. */
4281 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004282 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004283 return 0;
4284 lua_settable(L, -3);
4285
4286 /* Create the "sf" field that contains a list of stringsafe fetches. */
4287 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004288 if (!hlua_fetches_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 /* Create the "c" field that contains a list of converters. */
4293 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004294 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004295 return 0;
4296 lua_settable(L, -3);
4297
4298 /* Create the "sc" field that contains a list of stringsafe converters. */
4299 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004300 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004301 return 0;
4302 lua_settable(L, -3);
4303
4304 /* Pop a class stream metatable and affect it to the table. */
4305 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4306 lua_setmetatable(L, -2);
4307
4308 return 1;
4309}
4310
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004311__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4312{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004313 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004314 struct stream *s;
4315 const char *name;
4316 size_t len;
4317 struct sample smp;
4318
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004319 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4320 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004321
4322 /* It is useles to retrieve the stream, but this function
4323 * runs only in a stream context.
4324 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004325 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004326 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004327 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004328
4329 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004330 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004331 hlua_lua2smp(L, 3, &smp);
4332
4333 /* Store the sample in a variable. */
4334 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004335
4336 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4337 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4338 else
4339 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4340
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004341 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004342}
4343
4344__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4345{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004346 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004347 struct stream *s;
4348 const char *name;
4349 size_t len;
4350 struct sample smp;
4351
4352 MAY_LJMP(check_args(L, 2, "unset_var"));
4353
4354 /* It is useles to retrieve the stream, but this function
4355 * runs only in a stream context.
4356 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004357 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004358 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004359 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004360
4361 /* Unset the variable. */
4362 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004363 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4364 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004365}
4366
4367__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4368{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004369 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004370 struct stream *s;
4371 const char *name;
4372 size_t len;
4373 struct sample smp;
4374
4375 MAY_LJMP(check_args(L, 2, "get_var"));
4376
4377 /* It is useles to retrieve the stream, but this function
4378 * runs only in a stream context.
4379 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004380 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004381 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004382 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004383
4384 smp_set_owner(&smp, s->be, s->sess, s, 0);
4385 if (!vars_get_by_name(name, len, &smp)) {
4386 lua_pushnil(L);
4387 return 1;
4388 }
4389
4390 return hlua_smp2lua(L, &smp);
4391}
4392
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004393__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4394{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004395 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4396 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004397 struct hlua *hlua;
4398
4399 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004400 if (!s->hlua)
4401 return 0;
4402 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004403
4404 MAY_LJMP(check_args(L, 2, "set_priv"));
4405
4406 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004407 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004408
4409 /* Get and store new value. */
4410 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4411 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4412
4413 return 0;
4414}
4415
4416__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4417{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004418 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4419 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004420 struct hlua *hlua;
4421
4422 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004423 if (!s->hlua) {
4424 lua_pushnil(L);
4425 return 1;
4426 }
4427 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004428
4429 /* Push configuration index in the stack. */
4430 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4431
4432 return 1;
4433}
4434
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004435/* If expected data not yet available, it returns a yield. This function
4436 * consumes the data in the buffer. It returns a string containing the
4437 * data. This string can be empty.
4438 */
4439__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4440{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004441 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4442 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004443 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004444 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004445 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004446 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004447 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004448
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004449 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004450 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004451
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004452 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004453 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004454 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004455 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004456 }
4457
4458 /* End of data: commit the total strings and return. */
4459 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004460 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004461 return 1;
4462 }
4463
4464 /* Ensure that the block 2 length is usable. */
4465 if (ret == 1)
4466 len2 = 0;
4467
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004468 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004469 luaL_addlstring(&luactx->b, blk1, len1);
4470 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004471
4472 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004473 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004474 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004475 return 1;
4476}
4477
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004478/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004479__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4480{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004481 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004482
4483 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004484 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004485
4486 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4487}
4488
4489/* If expected data not yet available, it returns a yield. This function
4490 * consumes the data in the buffer. It returns a string containing the
4491 * data. This string can be empty.
4492 */
4493__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4494{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004495 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4496 struct stream_interface *si = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004497 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004498 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004499 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004500 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004501 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004502 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004503
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004504 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004505 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004506
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004507 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004508 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004509 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004510 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004511 }
4512
4513 /* End of data: commit the total strings and return. */
4514 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004515 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004516 return 1;
4517 }
4518
4519 /* Ensure that the block 2 length is usable. */
4520 if (ret == 1)
4521 len2 = 0;
4522
4523 if (len == -1) {
4524
4525 /* If len == -1, catenate all the data avalaile and
4526 * yield because we want to get all the data until
4527 * the end of data stream.
4528 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004529 luaL_addlstring(&luactx->b, blk1, len1);
4530 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004531 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004532 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004533 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004534
4535 } else {
4536
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004537 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004538 if (len1 > len)
4539 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004540 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004541 len -= len1;
4542
4543 /* Copy the second block. */
4544 if (len2 > len)
4545 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004546 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004547 len -= len2;
4548
4549 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004550 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004551
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004552 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553 if (len > 0) {
4554 lua_pushinteger(L, len);
4555 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004556 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004557 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004558 }
4559
4560 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004561 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004562 return 1;
4563 }
4564
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004565 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004566 hlua_pusherror(L, "Lua: internal error");
4567 WILL_LJMP(lua_error(L));
4568 return 0;
4569}
4570
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004571/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004572__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4573{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004574 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004575 int len = -1;
4576
4577 if (lua_gettop(L) > 2)
4578 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4579 if (lua_gettop(L) >= 2) {
4580 len = MAY_LJMP(luaL_checkinteger(L, 2));
4581 lua_pop(L, 1);
4582 }
4583
4584 /* Confirm or set the required length */
4585 lua_pushinteger(L, len);
4586
4587 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004588 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004589
4590 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4591}
4592
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004593/* Append data in the output side of the buffer. This data is immediately
4594 * sent. The function returns the amount of data written. If the buffer
4595 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004596 * if the channel is closed.
4597 */
4598__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4599{
4600 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004601 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004602 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4603 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004604 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004605 struct channel *chn = si_ic(si);
4606 int max;
4607
4608 /* Get the max amount of data which can write as input in the channel. */
4609 max = channel_recv_max(chn);
4610 if (max > (len - l))
4611 max = len - l;
4612
4613 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004614 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004615
4616 /* update counters. */
4617 l += max;
4618 lua_pop(L, 1);
4619 lua_pushinteger(L, l);
4620
4621 /* If some data is not send, declares the situation to the
4622 * applet, and returns a yield.
4623 */
4624 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004625 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004626 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004627 }
4628
4629 return 1;
4630}
4631
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004632/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004633 * yield the LUA process, and resume it without checking the
4634 * input arguments.
4635 */
4636__LJMP static int hlua_applet_tcp_send(lua_State *L)
4637{
4638 MAY_LJMP(check_args(L, 2, "send"));
4639 lua_pushinteger(L, 0);
4640
4641 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4642}
4643
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004644/*
4645 *
4646 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004647 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004648 *
4649 *
4650 */
4651
4652/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004653 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004654 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004655__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004656{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004657 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004658}
4659
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004660/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004661 * according with a current TXN.
4662 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004663static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004664{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004665 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004666 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004667 struct stream_interface *si = ctx->owner;
4668 struct stream *s = si_strm(si);
4669 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004670 struct htx *htx;
4671 struct htx_blk *blk;
4672 struct htx_sl *sl;
4673 struct ist path;
4674 unsigned long long len = 0;
4675 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004676 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004677
4678 /* Check stack size. */
4679 if (!lua_checkstack(L, 3))
4680 return 0;
4681
4682 /* Create the object: obj[0] = userdata.
4683 * Note that the base of the Converters object is the
4684 * same than the TXN object.
4685 */
4686 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004687 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004688 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004689 luactx->appctx = ctx;
4690 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4691 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4692 luactx->htxn.s = s;
4693 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004694
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004695 /* Create the "f" field that contains a list of fetches. */
4696 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004697 if (!hlua_fetches_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 "sf" field that contains a list of stringsafe fetches. */
4702 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004703 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004704 return 0;
4705 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004706
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004707 /* Create the "c" field that contains a list of converters. */
4708 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004709 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004710 return 0;
4711 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004712
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004713 /* Create the "sc" field that contains a list of stringsafe converters. */
4714 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004715 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004716 return 0;
4717 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004718
Christopher Fauleta2097962019-07-15 16:25:33 +02004719 htx = htxbuf(&s->req.buf);
4720 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004721 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004722 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004723
Christopher Fauleta2097962019-07-15 16:25:33 +02004724 /* Stores the request method. */
4725 lua_pushstring(L, "method");
4726 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4727 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004728
Christopher Fauleta2097962019-07-15 16:25:33 +02004729 /* Stores the http version. */
4730 lua_pushstring(L, "version");
4731 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4732 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004733
Christopher Fauleta2097962019-07-15 16:25:33 +02004734 /* creates an array of headers. hlua_http_get_headers() crates and push
4735 * the array on the top of the stack.
4736 */
4737 lua_pushstring(L, "headers");
4738 htxn.s = s;
4739 htxn.p = px;
4740 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004741 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004742 return 0;
4743 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004744
Amaury Denoyellec453f952021-07-06 11:40:12 +02004745 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4746 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004747 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004748 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004749
Christopher Fauleta2097962019-07-15 16:25:33 +02004750 p = path.ptr;
4751 end = path.ptr + path.len;
4752 q = p;
4753 while (q < end && *q != '?')
4754 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004755
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004756 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004757 lua_pushstring(L, "path");
4758 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004759 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004760
Christopher Fauleta2097962019-07-15 16:25:33 +02004761 /* Stores the query string. */
4762 lua_pushstring(L, "qs");
4763 if (*q == '?')
4764 q++;
4765 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004766 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004767 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004768
Christopher Fauleta2097962019-07-15 16:25:33 +02004769 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4770 struct htx_blk *blk = htx_get_blk(htx, pos);
4771 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004772
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004773 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004774 break;
4775 if (type == HTX_BLK_DATA)
4776 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004777 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004778 if (htx->extra != ULLONG_MAX)
4779 len += htx->extra;
4780
4781 /* Stores the request path. */
4782 lua_pushstring(L, "length");
4783 lua_pushinteger(L, len);
4784 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004785
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004786 /* Create an empty array of HTTP request headers. */
4787 lua_pushstring(L, "response");
4788 lua_newtable(L);
4789 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004790
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004791 /* Pop a class stream metatable and affect it to the table. */
4792 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4793 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004794
4795 return 1;
4796}
4797
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004798__LJMP static int hlua_applet_http_set_var(lua_State *L)
4799{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004800 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004801 struct stream *s;
4802 const char *name;
4803 size_t len;
4804 struct sample smp;
4805
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004806 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4807 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004808
4809 /* It is useles to retrieve the stream, but this function
4810 * runs only in a stream context.
4811 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004812 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004813 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004814 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004815
4816 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004817 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004818 hlua_lua2smp(L, 3, &smp);
4819
4820 /* Store the sample in a variable. */
4821 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004822
4823 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4824 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4825 else
4826 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4827
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004828 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004829}
4830
4831__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4832{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004833 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004834 struct stream *s;
4835 const char *name;
4836 size_t len;
4837 struct sample smp;
4838
4839 MAY_LJMP(check_args(L, 2, "unset_var"));
4840
4841 /* It is useles to retrieve the stream, but this function
4842 * runs only in a stream context.
4843 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004844 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004845 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004846 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004847
4848 /* Unset the variable. */
4849 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004850 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4851 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004852}
4853
4854__LJMP static int hlua_applet_http_get_var(lua_State *L)
4855{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004856 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004857 struct stream *s;
4858 const char *name;
4859 size_t len;
4860 struct sample smp;
4861
4862 MAY_LJMP(check_args(L, 2, "get_var"));
4863
4864 /* It is useles to retrieve the stream, but this function
4865 * runs only in a stream context.
4866 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004867 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004868 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004869 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004870
4871 smp_set_owner(&smp, s->be, s->sess, s, 0);
4872 if (!vars_get_by_name(name, len, &smp)) {
4873 lua_pushnil(L);
4874 return 1;
4875 }
4876
4877 return hlua_smp2lua(L, &smp);
4878}
4879
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004880__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4881{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004882 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4883 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004884 struct hlua *hlua;
4885
4886 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004887 if (!s->hlua)
4888 return 0;
4889 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004890
4891 MAY_LJMP(check_args(L, 2, "set_priv"));
4892
4893 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004894 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004895
4896 /* Get and store new value. */
4897 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4898 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4899
4900 return 0;
4901}
4902
4903__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4904{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004905 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4906 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004907 struct hlua *hlua;
4908
4909 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004910 if (!s->hlua) {
4911 lua_pushnil(L);
4912 return 1;
4913 }
4914 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004915
4916 /* Push configuration index in the stack. */
4917 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4918
4919 return 1;
4920}
4921
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004922/* If expected data not yet available, it returns a yield. This function
4923 * consumes the data in the buffer. It returns a string containing the
4924 * data. This string can be empty.
4925 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004926__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004927{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004928 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4929 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004930 struct channel *req = si_oc(si);
4931 struct htx *htx;
4932 struct htx_blk *blk;
4933 size_t count;
4934 int stop = 0;
4935
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004936 htx = htx_from_buf(&req->buf);
4937 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004938 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004939
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004940 while (count && !stop && blk) {
4941 enum htx_blk_type type = htx_get_blk_type(blk);
4942 uint32_t sz = htx_get_blksz(blk);
4943 struct ist v;
4944 uint32_t vlen;
4945 char *nl;
4946
4947 vlen = sz;
4948 if (vlen > count) {
4949 if (type != HTX_BLK_DATA)
4950 break;
4951 vlen = count;
4952 }
4953
4954 switch (type) {
4955 case HTX_BLK_UNUSED:
4956 break;
4957
4958 case HTX_BLK_DATA:
4959 v = htx_get_blk_value(htx, blk);
4960 v.len = vlen;
4961 nl = istchr(v, '\n');
4962 if (nl != NULL) {
4963 stop = 1;
4964 vlen = nl - v.ptr + 1;
4965 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004966 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004967 break;
4968
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004969 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004970 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004971 stop = 1;
4972 break;
4973
4974 default:
4975 break;
4976 }
4977
4978 co_set_data(req, co_data(req) - vlen);
4979 count -= vlen;
4980 if (sz == vlen)
4981 blk = htx_remove_blk(htx, blk);
4982 else {
4983 htx_cut_data_blk(htx, blk, vlen);
4984 break;
4985 }
4986 }
4987
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004988 /* The message was fully consumed and no more data are expected
4989 * (EOM flag set).
4990 */
4991 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
4992 stop = 1;
4993
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004994 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004995 if (!stop) {
4996 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004997 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004998 }
4999
5000 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005001 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005002 return 1;
5003}
5004
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005005
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005006/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005007__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005008{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005009 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005010
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005011 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005012 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005013
Christopher Fauleta2097962019-07-15 16:25:33 +02005014 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005015}
5016
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005017/* If expected data not yet available, it returns a yield. This function
5018 * consumes the data in the buffer. It returns a string containing the
5019 * data. This string can be empty.
5020 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005021__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005022{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005023 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5024 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005025 struct channel *req = si_oc(si);
5026 struct htx *htx;
5027 struct htx_blk *blk;
5028 size_t count;
5029 int len;
5030
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005031 htx = htx_from_buf(&req->buf);
5032 len = MAY_LJMP(luaL_checkinteger(L, 2));
5033 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005034 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005035 while (count && len && blk) {
5036 enum htx_blk_type type = htx_get_blk_type(blk);
5037 uint32_t sz = htx_get_blksz(blk);
5038 struct ist v;
5039 uint32_t vlen;
5040
5041 vlen = sz;
5042 if (len > 0 && vlen > len)
5043 vlen = len;
5044 if (vlen > count) {
5045 if (type != HTX_BLK_DATA)
5046 break;
5047 vlen = count;
5048 }
5049
5050 switch (type) {
5051 case HTX_BLK_UNUSED:
5052 break;
5053
5054 case HTX_BLK_DATA:
5055 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005056 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005057 break;
5058
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005059 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005060 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005061 len = 0;
5062 break;
5063
5064 default:
5065 break;
5066 }
5067
5068 co_set_data(req, co_data(req) - vlen);
5069 count -= vlen;
5070 if (len > 0)
5071 len -= vlen;
5072 if (sz == vlen)
5073 blk = htx_remove_blk(htx, blk);
5074 else {
5075 htx_cut_data_blk(htx, blk, vlen);
5076 break;
5077 }
5078 }
5079
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005080 /* The message was fully consumed and no more data are expected
5081 * (EOM flag set).
5082 */
5083 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5084 len = 0;
5085
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005086 htx_to_buf(htx, &req->buf);
5087
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005088 /* If we are no other data available, yield waiting for new data. */
5089 if (len) {
5090 if (len > 0) {
5091 lua_pushinteger(L, len);
5092 lua_replace(L, 2);
5093 }
5094 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005095 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005096 }
5097
5098 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005099 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005100 return 1;
5101}
5102
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005103/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005104__LJMP static int hlua_applet_http_recv(lua_State *L)
5105{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005106 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005107 int len = -1;
5108
5109 /* Check arguments. */
5110 if (lua_gettop(L) > 2)
5111 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5112 if (lua_gettop(L) >= 2) {
5113 len = MAY_LJMP(luaL_checkinteger(L, 2));
5114 lua_pop(L, 1);
5115 }
5116
Christopher Fauleta2097962019-07-15 16:25:33 +02005117 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005118
Christopher Fauleta2097962019-07-15 16:25:33 +02005119 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005120 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005121
Christopher Fauleta2097962019-07-15 16:25:33 +02005122 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005123}
5124
5125/* Append data in the output side of the buffer. This data is immediately
5126 * sent. The function returns the amount of data written. If the buffer
5127 * cannot contain the data, the function yields. The function returns -1
5128 * if the channel is closed.
5129 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005130__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005131{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005132 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5133 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005134 struct channel *res = si_ic(si);
5135 struct htx *htx = htx_from_buf(&res->buf);
5136 const char *data;
5137 size_t len;
5138 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5139 int max;
5140
Christopher Faulet9060fc02019-07-03 11:39:30 +02005141 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005142 if (!max)
5143 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005144
5145 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5146
5147 /* Get the max amount of data which can write as input in the channel. */
5148 if (max > (len - l))
5149 max = len - l;
5150
5151 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005152 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005153 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005154
5155 /* update counters. */
5156 l += max;
5157 lua_pop(L, 1);
5158 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005159
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005160 /* If some data is not send, declares the situation to the
5161 * applet, and returns a yield.
5162 */
5163 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005164 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005165 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005166 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005167 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005168 }
5169
Christopher Fauleta2097962019-07-15 16:25:33 +02005170 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005171 return 1;
5172}
5173
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005174/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005175 * yield the LUA process, and resume it without checking the
5176 * input arguments.
5177 */
5178__LJMP static int hlua_applet_http_send(lua_State *L)
5179{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005180 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005181
5182 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005183 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005184 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5185 WILL_LJMP(lua_error(L));
5186 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005187
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005188 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005189 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005190
Christopher Fauleta2097962019-07-15 16:25:33 +02005191 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005192}
5193
5194__LJMP static int hlua_applet_http_addheader(lua_State *L)
5195{
5196 const char *name;
5197 int ret;
5198
5199 MAY_LJMP(hlua_checkapplet_http(L, 1));
5200 name = MAY_LJMP(luaL_checkstring(L, 2));
5201 MAY_LJMP(luaL_checkstring(L, 3));
5202
5203 /* Push in the stack the "response" entry. */
5204 ret = lua_getfield(L, 1, "response");
5205 if (ret != LUA_TTABLE) {
5206 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5207 "is expected as an array. %s found", lua_typename(L, ret));
5208 WILL_LJMP(lua_error(L));
5209 }
5210
5211 /* check if the header is already registered if it is not
5212 * the case, register it.
5213 */
5214 ret = lua_getfield(L, -1, name);
5215 if (ret == LUA_TNIL) {
5216
5217 /* Entry not found. */
5218 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5219
5220 /* Insert the new header name in the array in the top of the stack.
5221 * It left the new array in the top of the stack.
5222 */
5223 lua_newtable(L);
5224 lua_pushvalue(L, 2);
5225 lua_pushvalue(L, -2);
5226 lua_settable(L, -4);
5227
5228 } else if (ret != LUA_TTABLE) {
5229
5230 /* corruption error. */
5231 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5232 "is expected as an array. %s found", name, lua_typename(L, ret));
5233 WILL_LJMP(lua_error(L));
5234 }
5235
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005236 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005237 * the header value as new entry.
5238 */
5239 lua_pushvalue(L, 3);
5240 ret = lua_rawlen(L, -2);
5241 lua_rawseti(L, -2, ret + 1);
5242 lua_pushboolean(L, 1);
5243 return 1;
5244}
5245
5246__LJMP static int hlua_applet_http_status(lua_State *L)
5247{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005248 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005249 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005250 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005251
5252 if (status < 100 || status > 599) {
5253 lua_pushboolean(L, 0);
5254 return 1;
5255 }
5256
Willy Tarreau7e702d12021-04-28 17:59:21 +02005257 luactx->appctx->ctx.hlua_apphttp.status = status;
5258 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005259 lua_pushboolean(L, 1);
5260 return 1;
5261}
5262
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005263
Christopher Fauleta2097962019-07-15 16:25:33 +02005264__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005265{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005266 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5267 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005268 struct channel *res = si_ic(si);
5269 struct htx *htx;
5270 struct htx_sl *sl;
5271 struct h1m h1m;
5272 const char *status, *reason;
5273 const char *name, *value;
5274 size_t nlen, vlen;
5275 unsigned int flags;
5276
5277 /* Send the message at once. */
5278 htx = htx_from_buf(&res->buf);
5279 h1m_init_res(&h1m);
5280
5281 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005282 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5283 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005284 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005285 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5286 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005287 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5288 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5289 }
5290 else {
5291 flags = HTX_SL_F_IS_RESP;
5292 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5293 }
5294 if (!sl) {
5295 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005296 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005297 WILL_LJMP(lua_error(L));
5298 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005299 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005300
5301 /* Get the array associated to the field "response" in the object AppletHTTP. */
5302 lua_pushvalue(L, 0);
5303 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5304 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005305 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005306 WILL_LJMP(lua_error(L));
5307 }
5308
5309 /* Browse the list of headers. */
5310 lua_pushnil(L);
5311 while(lua_next(L, -2) != 0) {
5312 /* We expect a string as -2. */
5313 if (lua_type(L, -2) != LUA_TSTRING) {
5314 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005315 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005316 lua_typename(L, lua_type(L, -2)));
5317 WILL_LJMP(lua_error(L));
5318 }
5319 name = lua_tolstring(L, -2, &nlen);
5320
5321 /* We expect an array as -1. */
5322 if (lua_type(L, -1) != LUA_TTABLE) {
5323 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 +02005324 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005325 name,
5326 lua_typename(L, lua_type(L, -1)));
5327 WILL_LJMP(lua_error(L));
5328 }
5329
5330 /* Browse the table who is on the top of the stack. */
5331 lua_pushnil(L);
5332 while(lua_next(L, -2) != 0) {
5333 int id;
5334
5335 /* We expect a number as -2. */
5336 if (lua_type(L, -2) != LUA_TNUMBER) {
5337 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 +02005338 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005339 name,
5340 lua_typename(L, lua_type(L, -2)));
5341 WILL_LJMP(lua_error(L));
5342 }
5343 id = lua_tointeger(L, -2);
5344
5345 /* We expect a string as -2. */
5346 if (lua_type(L, -1) != LUA_TSTRING) {
5347 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 +02005348 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005349 name, id,
5350 lua_typename(L, lua_type(L, -1)));
5351 WILL_LJMP(lua_error(L));
5352 }
5353 value = lua_tolstring(L, -1, &vlen);
5354
5355 /* Simple Protocol checks. */
5356 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01005357 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005358 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5359 struct ist v = ist2(value, vlen);
5360 int ret;
5361
5362 ret = h1_parse_cont_len_header(&h1m, &v);
5363 if (ret < 0) {
5364 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005365 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005366 name);
5367 WILL_LJMP(lua_error(L));
5368 }
5369 else if (ret == 0)
5370 goto next; /* Skip it */
5371 }
5372
5373 /* Add a new header */
5374 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5375 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005376 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005377 name);
5378 WILL_LJMP(lua_error(L));
5379 }
5380 next:
5381 /* Remove the array from the stack, and get next element with a remaining string. */
5382 lua_pop(L, 1);
5383 }
5384
5385 /* Remove the array from the stack, and get next element with a remaining string. */
5386 lua_pop(L, 1);
5387 }
5388
5389 if (h1m.flags & H1_MF_CHNK)
5390 h1m.flags &= ~H1_MF_CLEN;
5391 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5392 h1m.flags |= H1_MF_XFER_LEN;
5393
5394 /* Uset HTX start-line flags */
5395 if (h1m.flags & H1_MF_XFER_ENC)
5396 flags |= HTX_SL_F_XFER_ENC;
5397 if (h1m.flags & H1_MF_XFER_LEN) {
5398 flags |= HTX_SL_F_XFER_LEN;
5399 if (h1m.flags & H1_MF_CHNK)
5400 flags |= HTX_SL_F_CHNK;
5401 else if (h1m.flags & H1_MF_CLEN)
5402 flags |= HTX_SL_F_CLEN;
5403 if (h1m.body_len == 0)
5404 flags |= HTX_SL_F_BODYLESS;
5405 }
5406 sl->flags |= flags;
5407
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005408 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005409 * and the status code implies the presence of a message body, we must
5410 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005411 * for the keepalive compliance. If the applet announces a transfer-encoding
5412 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005413 */
5414 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005415 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5416 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5417 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005418 /* Add a new header */
5419 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5420 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5421 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005422 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005423 WILL_LJMP(lua_error(L));
5424 }
5425 }
5426
5427 /* Finalize headers. */
5428 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5429 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005430 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005431 WILL_LJMP(lua_error(L));
5432 }
5433
5434 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5435 b_reset(&res->buf);
5436 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5437 WILL_LJMP(lua_error(L));
5438 }
5439
5440 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005441 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005442
5443 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005444 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005445 return 0;
5446
5447}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005448/* We will build the status line and the headers of the HTTP response.
5449 * We will try send at once if its not possible, we give back the hand
5450 * waiting for more room.
5451 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005452__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005453{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005454 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5455 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005456 struct channel *res = si_ic(si);
5457
5458 if (co_data(res)) {
5459 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005460 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005461 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005462 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005463}
5464
5465
Christopher Fauleta2097962019-07-15 16:25:33 +02005466__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005467{
Christopher Fauleta2097962019-07-15 16:25:33 +02005468 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005469}
5470
Christopher Fauleta2097962019-07-15 16:25:33 +02005471/*
5472 *
5473 *
5474 * Class HTTP
5475 *
5476 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005477 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005478
5479/* Returns a struct hlua_txn if the stack entry "ud" is
5480 * a class stream, otherwise it throws an error.
5481 */
5482__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005483{
Christopher Fauleta2097962019-07-15 16:25:33 +02005484 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5485}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005486
Christopher Fauleta2097962019-07-15 16:25:33 +02005487/* This function creates and push in the stack a HTTP object
5488 * according with a current TXN.
5489 */
5490static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5491{
5492 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005493
Christopher Fauleta2097962019-07-15 16:25:33 +02005494 /* Check stack size. */
5495 if (!lua_checkstack(L, 3))
5496 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005497
Christopher Fauleta2097962019-07-15 16:25:33 +02005498 /* Create the object: obj[0] = userdata.
5499 * Note that the base of the Converters object is the
5500 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005501 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005502 lua_newtable(L);
5503 htxn = lua_newuserdata(L, sizeof(*htxn));
5504 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005505
5506 htxn->s = txn->s;
5507 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005508 htxn->dir = txn->dir;
5509 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005510
5511 /* Pop a class stream metatable and affect it to the table. */
5512 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5513 lua_setmetatable(L, -2);
5514
5515 return 1;
5516}
5517
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005518/* This function creates and returns an array containing the status-line
5519 * elements. This function does not fails.
5520 */
5521__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5522{
5523 /* Create the table. */
5524 lua_newtable(L);
5525
5526 if (sl->flags & HTX_SL_F_IS_RESP) {
5527 lua_pushstring(L, "version");
5528 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5529 lua_settable(L, -3);
5530 lua_pushstring(L, "code");
5531 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5532 lua_settable(L, -3);
5533 lua_pushstring(L, "reason");
5534 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5535 lua_settable(L, -3);
5536 }
5537 else {
5538 lua_pushstring(L, "method");
5539 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5540 lua_settable(L, -3);
5541 lua_pushstring(L, "uri");
5542 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5543 lua_settable(L, -3);
5544 lua_pushstring(L, "version");
5545 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5546 lua_settable(L, -3);
5547 }
5548 return 1;
5549}
5550
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005551/* This function creates ans returns an array of HTTP headers.
5552 * This function does not fails. It is used as wrapper with the
5553 * 2 following functions.
5554 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005555__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005556{
Christopher Fauleta2097962019-07-15 16:25:33 +02005557 struct htx *htx;
5558 int32_t pos;
5559
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005560 /* Create the table. */
5561 lua_newtable(L);
5562
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005563
Christopher Fauleta2097962019-07-15 16:25:33 +02005564 htx = htxbuf(&msg->chn->buf);
5565 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5566 struct htx_blk *blk = htx_get_blk(htx, pos);
5567 enum htx_blk_type type = htx_get_blk_type(blk);
5568 struct ist n, v;
5569 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005570
Christopher Fauleta2097962019-07-15 16:25:33 +02005571 if (type == HTX_BLK_HDR) {
5572 n = htx_get_blk_name(htx,blk);
5573 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005574 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005575 else if (type == HTX_BLK_EOH)
5576 break;
5577 else
5578 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005579
Christopher Fauleta2097962019-07-15 16:25:33 +02005580 /* Check for existing entry:
5581 * assume that the table is on the top of the stack, and
5582 * push the key in the stack, the function lua_gettable()
5583 * perform the lookup.
5584 */
5585 lua_pushlstring(L, n.ptr, n.len);
5586 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005587
Christopher Fauleta2097962019-07-15 16:25:33 +02005588 switch (lua_type(L, -1)) {
5589 case LUA_TNIL:
5590 /* Table not found, create it. */
5591 lua_pop(L, 1); /* remove the nil value. */
5592 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5593 lua_newtable(L); /* create and push empty table. */
5594 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5595 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5596 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005597 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005598
Christopher Fauleta2097962019-07-15 16:25:33 +02005599 case LUA_TTABLE:
5600 /* Entry found: push the value in the table. */
5601 len = lua_rawlen(L, -1);
5602 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5603 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5604 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5605 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005606
Christopher Fauleta2097962019-07-15 16:25:33 +02005607 default:
5608 /* Other cases are errors. */
5609 hlua_pusherror(L, "internal error during the parsing of headers.");
5610 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005611 }
5612 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005613 return 1;
5614}
5615
5616__LJMP static int hlua_http_req_get_headers(lua_State *L)
5617{
5618 struct hlua_txn *htxn;
5619
5620 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5621 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5622
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005623 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005624 WILL_LJMP(lua_error(L));
5625
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005626 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005627}
5628
5629__LJMP static int hlua_http_res_get_headers(lua_State *L)
5630{
5631 struct hlua_txn *htxn;
5632
5633 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5634 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5635
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005636 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005637 WILL_LJMP(lua_error(L));
5638
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005639 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005640}
5641
5642/* This function replace full header, or just a value in
5643 * the request or in the response. It is a wrapper fir the
5644 * 4 following functions.
5645 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005646__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005647{
5648 size_t name_len;
5649 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5650 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5651 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005652 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005653 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005654
Dragan Dosen26743032019-04-30 15:54:36 +02005655 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005656 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5657
Christopher Fauleta2097962019-07-15 16:25:33 +02005658 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005659 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005660 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005661 return 0;
5662}
5663
5664__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5665{
5666 struct hlua_txn *htxn;
5667
5668 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5669 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5670
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005671 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005672 WILL_LJMP(lua_error(L));
5673
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005674 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005675}
5676
5677__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5678{
5679 struct hlua_txn *htxn;
5680
5681 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5682 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5683
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005684 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005685 WILL_LJMP(lua_error(L));
5686
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005687 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005688}
5689
5690__LJMP static int hlua_http_req_rep_val(lua_State *L)
5691{
5692 struct hlua_txn *htxn;
5693
5694 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5695 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5696
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005697 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005698 WILL_LJMP(lua_error(L));
5699
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005700 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005701}
5702
5703__LJMP static int hlua_http_res_rep_val(lua_State *L)
5704{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005705 struct hlua_txn *htxn;
5706
5707 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5708 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5709
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005710 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005711 WILL_LJMP(lua_error(L));
5712
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005713 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005714}
5715
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005716/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005717 * It is a wrapper for the 2 following functions.
5718 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005719__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005720{
5721 size_t len;
5722 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005723 struct htx *htx = htxbuf(&msg->chn->buf);
5724 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005725
Christopher Fauleta2097962019-07-15 16:25:33 +02005726 ctx.blk = NULL;
5727 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5728 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005729 return 0;
5730}
5731
5732__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5733{
5734 struct hlua_txn *htxn;
5735
5736 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5737 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5738
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005739 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005740 WILL_LJMP(lua_error(L));
5741
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005742 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005743}
5744
5745__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5746{
5747 struct hlua_txn *htxn;
5748
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005749 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005750 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5751
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005752 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005753 WILL_LJMP(lua_error(L));
5754
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005755 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005756}
5757
5758/* This function adds an header. It is a wrapper used by
5759 * the 2 following functions.
5760 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005761__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005762{
5763 size_t name_len;
5764 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5765 size_t value_len;
5766 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005767 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005768
Christopher Fauleta2097962019-07-15 16:25:33 +02005769 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5770 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005771 return 0;
5772}
5773
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005774__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5775{
5776 struct hlua_txn *htxn;
5777
5778 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5779 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5780
5781 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5782 WILL_LJMP(lua_error(L));
5783
5784 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5785}
5786
5787__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5788{
5789 struct hlua_txn *htxn;
5790
5791 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5792 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5793
5794 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5795 WILL_LJMP(lua_error(L));
5796
5797 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5798}
5799
5800static int hlua_http_req_set_hdr(lua_State *L)
5801{
5802 struct hlua_txn *htxn;
5803
5804 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5805 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5806
5807 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5808 WILL_LJMP(lua_error(L));
5809
5810 hlua_http_del_hdr(L, &htxn->s->txn->req);
5811 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5812}
5813
5814static int hlua_http_res_set_hdr(lua_State *L)
5815{
5816 struct hlua_txn *htxn;
5817
5818 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5819 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5820
5821 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5822 WILL_LJMP(lua_error(L));
5823
5824 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5825 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5826}
5827
5828/* This function set the method. */
5829static int hlua_http_req_set_meth(lua_State *L)
5830{
5831 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5832 size_t name_len;
5833 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5834
5835 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5836 WILL_LJMP(lua_error(L));
5837
5838 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5839 return 1;
5840}
5841
5842/* This function set the method. */
5843static int hlua_http_req_set_path(lua_State *L)
5844{
5845 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5846 size_t name_len;
5847 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5848
5849 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5850 WILL_LJMP(lua_error(L));
5851
5852 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5853 return 1;
5854}
5855
5856/* This function set the query-string. */
5857static int hlua_http_req_set_query(lua_State *L)
5858{
5859 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5860 size_t name_len;
5861 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5862
5863 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5864 WILL_LJMP(lua_error(L));
5865
5866 /* Check length. */
5867 if (name_len > trash.size - 1) {
5868 lua_pushboolean(L, 0);
5869 return 1;
5870 }
5871
5872 /* Add the mark question as prefix. */
5873 chunk_reset(&trash);
5874 trash.area[trash.data++] = '?';
5875 memcpy(trash.area + trash.data, name, name_len);
5876 trash.data += name_len;
5877
5878 lua_pushboolean(L,
5879 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5880 return 1;
5881}
5882
5883/* This function set the uri. */
5884static int hlua_http_req_set_uri(lua_State *L)
5885{
5886 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5887 size_t name_len;
5888 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5889
5890 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5891 WILL_LJMP(lua_error(L));
5892
5893 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5894 return 1;
5895}
5896
5897/* This function set the response code & optionally reason. */
5898static int hlua_http_res_set_status(lua_State *L)
5899{
5900 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5901 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5902 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5903 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5904
5905 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5906 WILL_LJMP(lua_error(L));
5907
5908 http_res_set_status(code, reason, htxn->s);
5909 return 0;
5910}
5911
5912/*
5913 *
5914 *
5915 * Class HTTPMessage
5916 *
5917 *
5918 */
5919
5920/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5921 * otherwise it throws an error.
5922 */
5923__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5924{
5925 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5926}
5927
5928/* Creates and pushes on the stack a HTTP object according with a current TXN.
5929 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005930static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005931{
5932 /* Check stack size. */
5933 if (!lua_checkstack(L, 3))
5934 return 0;
5935
5936 lua_newtable(L);
5937 lua_pushlightuserdata(L, msg);
5938 lua_rawseti(L, -2, 0);
5939
5940 /* Create the "channel" field that contains the request channel object. */
5941 lua_pushstring(L, "channel");
5942 if (!hlua_channel_new(L, msg->chn))
5943 return 0;
5944 lua_rawset(L, -3);
5945
5946 /* Pop a class stream metatable and affect it to the table. */
5947 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5948 lua_setmetatable(L, -2);
5949
5950 return 1;
5951}
5952
5953/* Helper function returning a filter attached to the HTTP message at the
5954 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05005955 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005956 * filled with output and input length respectively.
5957 */
5958static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5959{
5960 struct channel *chn = msg->chn;
5961 struct htx *htx = htxbuf(&chn->buf);
5962 struct filter *filter = NULL;
5963
5964 *offset = co_data(msg->chn);
5965 *len = htx->data - co_data(msg->chn);
5966
5967 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5968 filter = lua_touserdata (L, -1);
5969 if (msg->msg_state >= HTTP_MSG_DATA) {
5970 struct hlua_flt_ctx *flt_ctx = filter->ctx;
5971
5972 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
5973 *len = flt_ctx->cur_len[CHN_IDX(chn)];
5974 }
5975 }
5976
5977 lua_pop(L, 1);
5978 return filter;
5979}
5980
5981/* Returns true if the channel attached to the HTTP message is the response
5982 * channel.
5983 */
5984__LJMP static int hlua_http_msg_is_resp(lua_State *L)
5985{
5986 struct http_msg *msg;
5987
5988 MAY_LJMP(check_args(L, 1, "is_resp"));
5989 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
5990
5991 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
5992 return 1;
5993}
5994
5995/* Returns an array containing the elements status-line of the HTTP message. It relies
5996 * on hlua_http_get_stline().
5997 */
5998__LJMP static int hlua_http_msg_get_stline(lua_State *L)
5999{
6000 struct http_msg *msg;
6001 struct htx *htx;
6002 struct htx_sl *sl;
6003
6004 MAY_LJMP(check_args(L, 1, "get_stline"));
6005 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6006
6007 if (msg->msg_state > HTTP_MSG_BODY)
6008 WILL_LJMP(lua_error(L));
6009
6010 htx = htxbuf(&msg->chn->buf);
6011 sl = http_get_stline(htx);
6012 if (!sl)
6013 return 0;
6014 return hlua_http_get_stline(L, sl);
6015}
6016
6017/* Returns an array containing all headers of the HTTP message. it relies on
6018 * hlua_http_get_headers().
6019 */
6020__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6021{
6022 struct http_msg *msg;
6023
6024 MAY_LJMP(check_args(L, 1, "get_headers"));
6025 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6026
6027 if (msg->msg_state > HTTP_MSG_BODY)
6028 WILL_LJMP(lua_error(L));
6029
6030 return hlua_http_get_headers(L, msg);
6031}
6032
6033/* Deletes all occurrences of an header in the HTTP message matching on its
6034 * name. It relies on hlua_http_del_hdr().
6035 */
6036__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6037{
6038 struct http_msg *msg;
6039
6040 MAY_LJMP(check_args(L, 2, "del_header"));
6041 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6042
6043 if (msg->msg_state > HTTP_MSG_BODY)
6044 WILL_LJMP(lua_error(L));
6045
6046 return hlua_http_del_hdr(L, msg);
6047}
6048
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006049/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006050 * message given its name against a regex and replaces it if it matches. It
6051 * relies on hlua_http_rep_hdr().
6052 */
6053__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6054{
6055 struct http_msg *msg;
6056
6057 MAY_LJMP(check_args(L, 4, "rep_header"));
6058 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6059
6060 if (msg->msg_state > HTTP_MSG_BODY)
6061 WILL_LJMP(lua_error(L));
6062
6063 return hlua_http_rep_hdr(L, msg, 1);
6064}
6065
6066/* Matches all comma-separated values of all occurences of an header in the HTTP
6067 * message given its name against a regex and replaces it if it matches. It
6068 * relies on hlua_http_rep_hdr().
6069 */
6070__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6071{
6072 struct http_msg *msg;
6073
6074 MAY_LJMP(check_args(L, 4, "rep_value"));
6075 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6076
6077 if (msg->msg_state > HTTP_MSG_BODY)
6078 WILL_LJMP(lua_error(L));
6079
6080 return hlua_http_rep_hdr(L, msg, 0);
6081}
6082
6083/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6084__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6085{
6086 struct http_msg *msg;
6087
6088 MAY_LJMP(check_args(L, 3, "add_header"));
6089 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6090
6091 if (msg->msg_state > HTTP_MSG_BODY)
6092 WILL_LJMP(lua_error(L));
6093
6094 return hlua_http_add_hdr(L, msg);
6095}
6096
6097/* Add an header in the HTTP message removing existing headers with the same
6098 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6099 */
6100__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6101{
6102 struct http_msg *msg;
6103
6104 MAY_LJMP(check_args(L, 3, "set_header"));
6105 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6106
6107 if (msg->msg_state > HTTP_MSG_BODY)
6108 WILL_LJMP(lua_error(L));
6109
6110 hlua_http_del_hdr(L, msg);
6111 return hlua_http_add_hdr(L, msg);
6112}
6113
6114/* Rewrites the request method. It relies on http_req_replace_stline(). */
6115__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6116{
6117 struct stream *s;
6118 struct http_msg *msg;
6119 const char *name;
6120 size_t name_len;
6121
6122 MAY_LJMP(check_args(L, 2, "set_method"));
6123 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6124 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6125
6126 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6127 WILL_LJMP(lua_error(L));
6128
6129 s = chn_strm(msg->chn);
6130 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6131 return 1;
6132}
6133
6134/* Rewrites the request path. It relies on http_req_replace_stline(). */
6135__LJMP static int hlua_http_msg_set_path(lua_State *L)
6136{
6137 struct stream *s;
6138 struct http_msg *msg;
6139 const char *name;
6140 size_t name_len;
6141
6142 MAY_LJMP(check_args(L, 2, "set_path"));
6143 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6144 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6145
6146 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6147 WILL_LJMP(lua_error(L));
6148
6149 s = chn_strm(msg->chn);
6150 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6151 return 1;
6152}
6153
6154/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6155__LJMP static int hlua_http_msg_set_query(lua_State *L)
6156{
6157 struct stream *s;
6158 struct http_msg *msg;
6159 const char *name;
6160 size_t name_len;
6161
6162 MAY_LJMP(check_args(L, 2, "set_query"));
6163 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6164 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6165
6166 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6167 WILL_LJMP(lua_error(L));
6168
6169 /* Check length. */
6170 if (name_len > trash.size - 1) {
6171 lua_pushboolean(L, 0);
6172 return 1;
6173 }
6174
6175 /* Add the mark question as prefix. */
6176 chunk_reset(&trash);
6177 trash.area[trash.data++] = '?';
6178 memcpy(trash.area + trash.data, name, name_len);
6179 trash.data += name_len;
6180
6181 s = chn_strm(msg->chn);
6182 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6183 return 1;
6184}
6185
6186/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6187__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6188{
6189 struct stream *s;
6190 struct http_msg *msg;
6191 const char *name;
6192 size_t name_len;
6193
6194 MAY_LJMP(check_args(L, 2, "set_uri"));
6195 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6196 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6197
6198 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6199 WILL_LJMP(lua_error(L));
6200
6201 s = chn_strm(msg->chn);
6202 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6203 return 1;
6204}
6205
6206/* Rewrites the response status code. It relies on http_res_set_status(). */
6207__LJMP static int hlua_http_msg_set_status(lua_State *L)
6208{
6209 struct http_msg *msg;
6210 unsigned int code;
6211 const char *reason;
6212 size_t reason_len;
6213
6214 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6215 code = MAY_LJMP(luaL_checkinteger(L, 2));
6216 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6217
6218 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6219 WILL_LJMP(lua_error(L));
6220
6221 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6222 return 1;
6223}
6224
6225/* Returns true if the HTTP message is full. */
6226__LJMP static int hlua_http_msg_is_full(lua_State *L)
6227{
6228 struct http_msg *msg;
6229
6230 MAY_LJMP(check_args(L, 1, "is_full"));
6231 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6232 lua_pushboolean(L, channel_full(msg->chn, 0));
6233 return 1;
6234}
6235
6236/* Returns true if the HTTP message may still receive data. */
6237__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6238{
6239 struct http_msg *msg;
6240 struct htx *htx;
6241
6242 MAY_LJMP(check_args(L, 1, "may_recv"));
6243 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6244 htx = htxbuf(&msg->chn->buf);
6245 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6246 return 1;
6247}
6248
6249/* Returns true if the HTTP message EOM was received */
6250__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6251{
6252 struct http_msg *msg;
6253 struct htx *htx;
6254
6255 MAY_LJMP(check_args(L, 1, "may_recv"));
6256 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6257 htx = htxbuf(&msg->chn->buf);
6258 lua_pushboolean(L, !htx_expect_more(htx));
6259 return 1;
6260}
6261
6262/* Returns the number of bytes available in the input side of the HTTP
6263 * message. This function never fails.
6264 */
6265__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6266{
6267 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006268 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006269
6270 MAY_LJMP(check_args(L, 1, "input"));
6271 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006272 hlua_http_msg_filter(L, 1, msg, &output, &input);
6273 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006274 return 1;
6275}
6276
6277/* Returns the number of bytes available in the output side of the HTTP
6278 * message. This function never fails.
6279 */
6280__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6281{
6282 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006283 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006284
6285 MAY_LJMP(check_args(L, 1, "output"));
6286 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006287 hlua_http_msg_filter(L, 1, msg, &output, &input);
6288 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006289 return 1;
6290}
6291
6292/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6293 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006294 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006295 * block. This function is called during the payload filtering, so the headers
6296 * are already scheduled for output (from the filter point of view).
6297 */
6298static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6299{
6300 struct htx *htx = htxbuf(&msg->chn->buf);
6301 struct htx_blk *blk;
6302 struct htx_ret htxret;
6303 luaL_Buffer b;
6304 int ret = 0;
6305
6306 luaL_buffinit(L, &b);
6307 htxret = htx_find_offset(htx, offset);
6308 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6309 enum htx_blk_type type = htx_get_blk_type(blk);
6310 struct ist v;
6311
6312 switch (type) {
6313 case HTX_BLK_UNUSED:
6314 break;
6315
6316 case HTX_BLK_DATA:
6317 v = htx_get_blk_value(htx, blk);
6318 v.ptr += offset;
6319 v.len -= offset;
6320 if (v.len > len)
6321 v.len = len;
6322
6323 luaL_addlstring(&b, v.ptr, v.len);
6324 ret += v.len;
6325 break;
6326
6327 default:
6328 if (!ret) {
6329 /* Remove the empty string and push nil on the stack */
6330 lua_pop(L, 1);
6331 lua_pushnil(L);
6332 }
6333 goto end;
6334 }
6335 offset = 0;
6336 }
6337
6338 luaL_pushresult(&b);
6339
6340end:
6341 return ret;
6342}
6343
6344/* Copies the string <str> to the HTTP message <msg> at the offset
6345 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006346 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006347 * the filter context.
6348 */
6349static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6350{
6351 struct htx *htx = htx_from_buf(&msg->chn->buf);
6352 struct htx_ret htxret;
6353 int /*max, */ret = 0;
6354
6355 /* Nothing to do, just return */
6356 if (unlikely(istlen(str) == 0))
6357 goto end;
6358
6359 if (istlen(str) > htx_free_data_space(htx)) {
6360 ret = -1;
6361 goto end;
6362 }
6363
6364 htxret = htx_find_offset(htx, offset);
6365 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6366 if (!htx_add_last_data(htx, str))
6367 goto end;
6368 }
6369 else {
6370 struct ist v = htx_get_blk_value(htx, htxret.blk);
6371 v.ptr += htxret.ret;
6372 v.len = 0;
6373 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6374 goto end;
6375 }
6376 ret = str.len;
6377 if (ret) {
6378 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6379 flt_update_offsets(filter, msg->chn, ret);
6380 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6381 }
6382
6383 end:
6384 htx_to_buf(htx, &msg->chn->buf);
6385 return ret;
6386}
6387
6388/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6389 * position <offset>. It stops on the first non-DATA HTX block. This function is
6390 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006391 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006392 * update the filter context.
6393 */
6394static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6395{
6396 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6397 struct htx *htx = htx_from_buf(&msg->chn->buf);
6398 struct htx_blk *blk;
6399 struct htx_ret htxret;
6400 size_t ret = 0;
6401
6402 /* Be sure <len> is always the amount of DATA to remove */
6403 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6404 htx_truncate(htx, offset);
6405 ret = len;
6406 goto end;
6407 }
6408
6409 htxret = htx_find_offset(htx, offset);
6410 blk = htxret.blk;
6411 if (htxret.ret) {
6412 struct ist v;
6413
6414 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6415 goto end;
6416 v = htx_get_blk_value(htx, blk);
6417 v.ptr += htxret.ret;
6418 if (v.len > len)
6419 v.len = len;
6420 blk = htx_replace_blk_value(htx, blk, v, ist2(NULL, 0));
6421 len -= v.len;
6422 ret += v.len;
6423 }
6424
6425
6426 while (blk && len) {
6427 enum htx_blk_type type = htx_get_blk_type(blk);
6428 uint32_t sz = htx_get_blksz(blk);
6429
6430 switch (type) {
6431 case HTX_BLK_UNUSED:
6432 break;
6433
6434 case HTX_BLK_DATA:
6435 if (len < sz) {
6436 htx_cut_data_blk(htx, blk, len);
6437 ret += len;
6438 goto end;
6439 }
6440 break;
6441
6442 default:
6443 goto end;
6444 }
6445
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006446 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006447 len -= sz;
6448 ret += sz;
6449 blk = htx_remove_blk(htx, blk);
6450 }
6451
6452end:
6453 flt_update_offsets(filter, msg->chn, -ret);
6454 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6455 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6456 * to loose the EOM flag if the message is empty.
6457 */
6458}
6459
6460/* Copies input data found in an HTTP message. Unlike the channel function used
6461 * to duplicate raw data, this one can only be called inside a filter, from
6462 * http_payload callback. So it cannot yield. An exception is returned if it is
6463 * called from another callback. If nothing was copied, a nil value is pushed on
6464 * the stack.
6465 */
6466__LJMP static int hlua_http_msg_get_body(lua_State *L)
6467{
6468 struct http_msg *msg;
6469 struct filter *filter;
6470 size_t output, input;
6471 int offset, len;
6472
6473 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6474 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6475 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6476
6477 if (msg->msg_state < HTTP_MSG_DATA)
6478 WILL_LJMP(lua_error(L));
6479
6480 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6481 if (!filter || !hlua_filter_from_payload(filter))
6482 WILL_LJMP(lua_error(L));
6483
6484 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6485 lua_pushnil(L);
6486 return 1;
6487 }
6488
6489 offset = output;
6490 if (lua_gettop(L) > 1) {
6491 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6492 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006493 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006494 offset += output;
6495 if (offset < output || offset > input + output) {
6496 lua_pushfstring(L, "offset out of range.");
6497 WILL_LJMP(lua_error(L));
6498 }
6499 }
6500 len = output + input - offset;
6501 if (lua_gettop(L) == 3) {
6502 len = MAY_LJMP(luaL_checkinteger(L, 3));
6503 if (!len)
6504 goto dup;
6505 if (len == -1)
6506 len = global.tune.bufsize;
6507 if (len < 0) {
6508 lua_pushfstring(L, "length out of range.");
6509 WILL_LJMP(lua_error(L));
6510 }
6511 }
6512
6513 dup:
6514 _hlua_http_msg_dup(msg, L, offset, len);
6515 return 1;
6516}
6517
6518/* Appends a string to the HTTP message, after all existing DATA blocks but
6519 * before the trailers, if any. It returns the amount of data written or -1 if
6520 * nothing was copied. Unlike the channel function used to append data, this one
6521 * can only be called inside a filter, from http_payload callback. So it cannot
6522 * yield. An exception is returned if it is called from another callback.
6523 */
6524__LJMP static int hlua_http_msg_append(lua_State *L)
6525{
6526 struct http_msg *msg;
6527 struct filter *filter;
6528 const char *str;
6529 size_t offset, len, sz;
6530 int ret;
6531
6532 MAY_LJMP(check_args(L, 2, "append"));
6533 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6534
6535 if (msg->msg_state < HTTP_MSG_DATA)
6536 WILL_LJMP(lua_error(L));
6537
6538 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6539 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6540 if (!filter || !hlua_filter_from_payload(filter))
6541 WILL_LJMP(lua_error(L));
6542
6543 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6544 lua_pushinteger(L, ret);
6545 return 1;
6546}
6547
6548/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6549 * returns the amount of data written or -1 if nothing was copied. Unlike the
6550 * channel function used to prepend data, this one can only be called inside a
6551 * filter, from http_payload callback. So it cannot yield. An exception is
6552 * returned if it is called from another callback.
6553 */
6554__LJMP static int hlua_http_msg_prepend(lua_State *L)
6555{
6556 struct http_msg *msg;
6557 struct filter *filter;
6558 const char *str;
6559 size_t offset, len, sz;
6560 int ret;
6561
6562 MAY_LJMP(check_args(L, 2, "prepend"));
6563 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006564
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006565 if (msg->msg_state < HTTP_MSG_DATA)
6566 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006567
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006568 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6569 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6570 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006571 WILL_LJMP(lua_error(L));
6572
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006573 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6574 lua_pushinteger(L, ret);
6575 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006576}
6577
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006578/* Inserts a string to the HTTP message at a given offset. By default the string
6579 * is appended at the end of DATA blocks. It returns the amount of data written
6580 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6581 * this one can only be called inside a filter, from http_payload callback. So
6582 * it cannot yield. An exception is returned if it is called from another
6583 * callback.
6584 */
6585__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006586{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006587 struct http_msg *msg;
6588 struct filter *filter;
6589 const char *str;
6590 size_t input, output, sz;
6591 int offset;
6592 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006593
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006594 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6595 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6596 MAY_LJMP(check_args(L, 2, "insert"));
6597 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006598
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006599 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006600 WILL_LJMP(lua_error(L));
6601
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006602 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6603 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6604 if (!filter || !hlua_filter_from_payload(filter))
6605 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006606
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006607 offset = input + output;
6608 if (lua_gettop(L) > 2) {
6609 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6610 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006611 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006612 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006613 if (offset < output || offset > output + input) {
6614 lua_pushfstring(L, "offset out of range.");
6615 WILL_LJMP(lua_error(L));
6616 }
6617 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006618
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006619 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6620 lua_pushinteger(L, ret);
6621 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006622}
6623
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006624/* Removes a given amount of data from the HTTP message at a given offset. By
6625 * default all DATA blocks are removed. It returns the amount of data
6626 * removed. Unlike the channel function used to remove data, this one can only
6627 * be called inside a filter, from http_payload callback. So it cannot yield. An
6628 * exception is returned if it is called from another callback.
6629 */
6630__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006631{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006632 struct http_msg *msg;
6633 struct filter *filter;
6634 size_t input, output;
6635 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006636
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006637 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6638 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6639 MAY_LJMP(check_args(L, 2, "insert"));
6640 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006641
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006642 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006643 WILL_LJMP(lua_error(L));
6644
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006645 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6646 if (!filter || !hlua_filter_from_payload(filter))
6647 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006648
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006649 offset = input + output;
6650 if (lua_gettop(L) > 2) {
6651 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6652 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006653 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006654 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006655 if (offset < output || offset > output + input) {
6656 lua_pushfstring(L, "offset out of range.");
6657 WILL_LJMP(lua_error(L));
6658 }
6659 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006660
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006661 len = output + input - offset;
6662 if (lua_gettop(L) == 4) {
6663 len = MAY_LJMP(luaL_checkinteger(L, 4));
6664 if (!len)
6665 goto end;
6666 if (len == -1)
6667 len = output + input - offset;
6668 if (len < 0 || offset + len > output + input) {
6669 lua_pushfstring(L, "length out of range.");
6670 WILL_LJMP(lua_error(L));
6671 }
6672 }
6673
6674 _hlua_http_msg_delete(msg, filter, offset, len);
6675
6676 end:
6677 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006678 return 1;
6679}
6680
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006681/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006682 * all remaining data are removed, accordingly to the filter context. It returns
6683 * the amount of data written or -1 if nothing was copied. Unlike the channel
6684 * function used to replace data, this one can only be called inside a filter,
6685 * from http_payload callback. So it cannot yield. An exception is returned if
6686 * it is called from another callback.
6687 */
6688__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006689{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006690 struct http_msg *msg;
6691 struct filter *filter;
6692 struct htx *htx;
6693 const char *str;
6694 size_t input, output, sz;
6695 int offset, len;
6696 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006697
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006698 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6699 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6700 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6701
6702 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006703 WILL_LJMP(lua_error(L));
6704
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006705 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6706 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6707 if (!filter || !hlua_filter_from_payload(filter))
6708 WILL_LJMP(lua_error(L));
6709
6710 offset = output;
6711 if (lua_gettop(L) > 2) {
6712 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6713 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006714 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006715 offset += output;
6716 if (offset < output || offset > input + output) {
6717 lua_pushfstring(L, "offset out of range.");
6718 WILL_LJMP(lua_error(L));
6719 }
6720 }
6721
6722 len = output + input - offset;
6723 if (lua_gettop(L) == 4) {
6724 len = MAY_LJMP(luaL_checkinteger(L, 4));
6725 if (!len)
6726 goto set;
6727 if (len == -1)
6728 len = output + input - offset;
6729 if (len < 0 || offset + len > output + input) {
6730 lua_pushfstring(L, "length out of range.");
6731 WILL_LJMP(lua_error(L));
6732 }
6733 }
6734
6735 set:
6736 /* Be sure we can copied the string once input data will be removed. */
6737 htx = htx_from_buf(&msg->chn->buf);
6738 if (sz > htx_free_data_space(htx) + len)
6739 lua_pushinteger(L, -1);
6740 else {
6741 _hlua_http_msg_delete(msg, filter, offset, len);
6742 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6743 lua_pushinteger(L, ret);
6744 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006745 return 1;
6746}
6747
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006748/* Prepends data into an HTTP message and forward it, from the filter point of
6749 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6750 * the channel function used to send data, this one can only be called inside a
6751 * filter, from http_payload callback. So it cannot yield. An exception is
6752 * returned if it is called from another callback.
6753 */
6754__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006755{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006756 struct http_msg *msg;
6757 struct filter *filter;
6758 struct htx *htx;
6759 const char *str;
6760 size_t offset, len, sz;
6761 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006762
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006763 MAY_LJMP(check_args(L, 2, "send"));
6764 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6765
6766 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006767 WILL_LJMP(lua_error(L));
6768
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006769 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6770 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6771 if (!filter || !hlua_filter_from_payload(filter))
6772 WILL_LJMP(lua_error(L));
6773
6774 /* Return an error if the channel's output is closed */
6775 if (unlikely(channel_output_closed(msg->chn))) {
6776 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006777 return 1;
6778 }
6779
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006780 htx = htx_from_buf(&msg->chn->buf);
6781 if (sz > htx_free_data_space(htx)) {
6782 lua_pushinteger(L, -1);
6783 return 1;
6784 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006785
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006786 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6787 if (ret > 0) {
6788 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6789
6790 FLT_OFF(filter, msg->chn) += ret;
6791 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6792 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6793 }
6794
6795 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006796 return 1;
6797}
6798
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006799/* Forwards a given amount of bytes. It return -1 if the channel's output is
6800 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6801 * channel function used to forward data, this one can only be called inside a
6802 * filter, from http_payload callback. So it cannot yield. An exception is
6803 * returned if it is called from another callback. All other functions deal with
6804 * DATA block, this one not.
6805*/
6806__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006807{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006808 struct http_msg *msg;
6809 struct filter *filter;
6810 size_t offset, len;
6811 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006812
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006813 MAY_LJMP(check_args(L, 2, "forward"));
6814 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6815
6816 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006817 WILL_LJMP(lua_error(L));
6818
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006819 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6820 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6821 if (!filter || !hlua_filter_from_payload(filter))
6822 WILL_LJMP(lua_error(L));
6823
6824 /* Nothing to do, just return */
6825 if (!fwd)
6826 goto end;
6827
6828 /* Return an error if the channel's output is closed */
6829 if (unlikely(channel_output_closed(msg->chn))) {
6830 ret = -1;
6831 goto end;
6832 }
6833
6834 ret = fwd;
6835 if (ret > len)
6836 ret = len;
6837
6838 if (ret) {
6839 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6840
6841 FLT_OFF(filter, msg->chn) += ret;
6842 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6843 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6844 }
6845
6846 end:
6847 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006848 return 1;
6849}
6850
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006851/* Set EOM flag on the HTX message.
6852 *
6853 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6854 * really know how to do without this feature.
6855 */
6856__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006857{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006858 struct http_msg *msg;
6859 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006860
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006861 MAY_LJMP(check_args(L, 1, "set_eom"));
6862 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6863 htx = htxbuf(&msg->chn->buf);
6864 htx->flags |= HTX_FL_EOM;
6865 return 0;
6866}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006867
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006868/* Unset EOM flag on the HTX message.
6869 *
6870 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6871 * really know how to do without this feature.
6872 */
6873__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6874{
6875 struct http_msg *msg;
6876 struct htx *htx;
6877
6878 MAY_LJMP(check_args(L, 1, "set_eom"));
6879 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6880 htx = htxbuf(&msg->chn->buf);
6881 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006882 return 0;
6883}
6884
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006885/*
6886 *
6887 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006888 * Class TXN
6889 *
6890 *
6891 */
6892
6893/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02006894 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006895 */
6896__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
6897{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006898 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006899}
6900
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006901__LJMP static int hlua_set_var(lua_State *L)
6902{
6903 struct hlua_txn *htxn;
6904 const char *name;
6905 size_t len;
6906 struct sample smp;
6907
Tim Duesterhus4e172c92020-05-19 13:49:42 +02006908 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6909 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006910
6911 /* It is useles to retrieve the stream, but this function
6912 * runs only in a stream context.
6913 */
6914 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6915 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6916
6917 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01006918 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006919 hlua_lua2smp(L, 3, &smp);
6920
6921 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01006922 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02006923
6924 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
6925 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
6926 else
6927 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
6928
Tim Duesterhus84ebc132020-05-19 13:49:41 +02006929 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006930}
6931
Christopher Faulet85d79c92016-11-09 16:54:56 +01006932__LJMP static int hlua_unset_var(lua_State *L)
6933{
6934 struct hlua_txn *htxn;
6935 const char *name;
6936 size_t len;
6937 struct sample smp;
6938
6939 MAY_LJMP(check_args(L, 2, "unset_var"));
6940
6941 /* It is useles to retrieve the stream, but this function
6942 * runs only in a stream context.
6943 */
6944 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6945 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6946
6947 /* Unset the variable. */
6948 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02006949 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
6950 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01006951}
6952
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006953__LJMP static int hlua_get_var(lua_State *L)
6954{
6955 struct hlua_txn *htxn;
6956 const char *name;
6957 size_t len;
6958 struct sample smp;
6959
6960 MAY_LJMP(check_args(L, 2, "get_var"));
6961
6962 /* It is useles to retrieve the stream, but this function
6963 * runs only in a stream context.
6964 */
6965 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6966 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6967
Willy Tarreau7560dd42016-03-10 16:28:58 +01006968 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01006969 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006970 lua_pushnil(L);
6971 return 1;
6972 }
6973
6974 return hlua_smp2lua(L, &smp);
6975}
6976
Willy Tarreau59551662015-03-10 14:23:13 +01006977__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006978{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006979 struct hlua *hlua;
6980
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006981 MAY_LJMP(check_args(L, 2, "set_priv"));
6982
Willy Tarreau87b09662015-04-03 00:22:06 +02006983 /* It is useles to retrieve the stream, but this function
6984 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006985 */
6986 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006987
6988 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006989 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006990 if (!hlua)
6991 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006992
6993 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02006994 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006995
6996 /* Get and store new value. */
6997 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
6998 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
6999
7000 return 0;
7001}
7002
Willy Tarreau59551662015-03-10 14:23:13 +01007003__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007004{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007005 struct hlua *hlua;
7006
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007007 MAY_LJMP(check_args(L, 1, "get_priv"));
7008
Willy Tarreau87b09662015-04-03 00:22:06 +02007009 /* It is useles to retrieve the stream, but this function
7010 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007011 */
7012 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007013
7014 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007015 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007016 if (!hlua) {
7017 lua_pushnil(L);
7018 return 1;
7019 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007020
7021 /* Push configuration index in the stack. */
7022 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7023
7024 return 1;
7025}
7026
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007027/* Create stack entry containing a class TXN. This function
7028 * return 0 if the stack does not contains free slots,
7029 * otherwise it returns 1.
7030 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007031static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007032{
Willy Tarreaude491382015-04-06 11:04:28 +02007033 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007034
7035 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007036 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007037 return 0;
7038
7039 /* NOTE: The allocation never fails. The failure
7040 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007041 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007042 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007043 /* Create the object: obj[0] = userdata. */
7044 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007045 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007046 lua_rawseti(L, -2, 0);
7047
Willy Tarreaude491382015-04-06 11:04:28 +02007048 htxn->s = s;
7049 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007050 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007051 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007052
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007053 /* Create the "f" field that contains a list of fetches. */
7054 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007055 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007056 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007057 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007058
7059 /* Create the "sf" field that contains a list of stringsafe fetches. */
7060 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007061 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007062 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007063 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007064
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007065 /* Create the "c" field that contains a list of converters. */
7066 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007067 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007068 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007069 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007070
7071 /* Create the "sc" field that contains a list of stringsafe converters. */
7072 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007073 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007074 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007075 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007076
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007077 /* Create the "req" field that contains the request channel object. */
7078 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007079 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007080 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007081 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007082
7083 /* Create the "res" field that contains the response channel object. */
7084 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007085 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007086 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007087 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007088
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007089 /* Creates the HTTP object is the current proxy allows http. */
7090 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007091 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007092 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007093 return 0;
7094 }
7095 else
7096 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007097 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007098
Christopher Faulet78c35472020-02-26 17:14:08 +01007099 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7100 /* HTTPMessage object are created when a lua TXN is created from
7101 * a filter context only
7102 */
7103
7104 /* Creates the HTTP-Request object is the current proxy allows http. */
7105 lua_pushstring(L, "http_req");
7106 if (p->mode == PR_MODE_HTTP) {
7107 if (!hlua_http_msg_new(L, &s->txn->req))
7108 return 0;
7109 }
7110 else
7111 lua_pushnil(L);
7112 lua_rawset(L, -3);
7113
7114 /* Creates the HTTP-Response object is the current proxy allows http. */
7115 lua_pushstring(L, "http_res");
7116 if (p->mode == PR_MODE_HTTP) {
7117 if (!hlua_http_msg_new(L, &s->txn->rsp))
7118 return 0;
7119 }
7120 else
7121 lua_pushnil(L);
7122 lua_rawset(L, -3);
7123 }
7124
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007125 /* Pop a class sesison metatable and affect it to the userdata. */
7126 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7127 lua_setmetatable(L, -2);
7128
7129 return 1;
7130}
7131
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007132__LJMP static int hlua_txn_deflog(lua_State *L)
7133{
7134 const char *msg;
7135 struct hlua_txn *htxn;
7136
7137 MAY_LJMP(check_args(L, 2, "deflog"));
7138 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7139 msg = MAY_LJMP(luaL_checkstring(L, 2));
7140
7141 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7142 return 0;
7143}
7144
7145__LJMP static int hlua_txn_log(lua_State *L)
7146{
7147 int level;
7148 const char *msg;
7149 struct hlua_txn *htxn;
7150
7151 MAY_LJMP(check_args(L, 3, "log"));
7152 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7153 level = MAY_LJMP(luaL_checkinteger(L, 2));
7154 msg = MAY_LJMP(luaL_checkstring(L, 3));
7155
7156 if (level < 0 || level >= NB_LOG_LEVELS)
7157 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7158
7159 hlua_sendlog(htxn->s->be, level, msg);
7160 return 0;
7161}
7162
7163__LJMP static int hlua_txn_log_debug(lua_State *L)
7164{
7165 const char *msg;
7166 struct hlua_txn *htxn;
7167
7168 MAY_LJMP(check_args(L, 2, "Debug"));
7169 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7170 msg = MAY_LJMP(luaL_checkstring(L, 2));
7171 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7172 return 0;
7173}
7174
7175__LJMP static int hlua_txn_log_info(lua_State *L)
7176{
7177 const char *msg;
7178 struct hlua_txn *htxn;
7179
7180 MAY_LJMP(check_args(L, 2, "Info"));
7181 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7182 msg = MAY_LJMP(luaL_checkstring(L, 2));
7183 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7184 return 0;
7185}
7186
7187__LJMP static int hlua_txn_log_warning(lua_State *L)
7188{
7189 const char *msg;
7190 struct hlua_txn *htxn;
7191
7192 MAY_LJMP(check_args(L, 2, "Warning"));
7193 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7194 msg = MAY_LJMP(luaL_checkstring(L, 2));
7195 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7196 return 0;
7197}
7198
7199__LJMP static int hlua_txn_log_alert(lua_State *L)
7200{
7201 const char *msg;
7202 struct hlua_txn *htxn;
7203
7204 MAY_LJMP(check_args(L, 2, "Alert"));
7205 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7206 msg = MAY_LJMP(luaL_checkstring(L, 2));
7207 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7208 return 0;
7209}
7210
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007211__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7212{
7213 struct hlua_txn *htxn;
7214 int ll;
7215
7216 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7217 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7218 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7219
7220 if (ll < 0 || ll > 7)
7221 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7222
7223 htxn->s->logs.level = ll;
7224 return 0;
7225}
7226
7227__LJMP static int hlua_txn_set_tos(lua_State *L)
7228{
7229 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007230 int tos;
7231
7232 MAY_LJMP(check_args(L, 2, "set_tos"));
7233 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7234 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7235
Willy Tarreau1a18b542018-12-11 16:37:42 +01007236 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007237 return 0;
7238}
7239
7240__LJMP static int hlua_txn_set_mark(lua_State *L)
7241{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007242 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007243 int mark;
7244
7245 MAY_LJMP(check_args(L, 2, "set_mark"));
7246 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7247 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7248
Lukas Tribus579e3e32019-08-11 18:03:45 +02007249 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007250 return 0;
7251}
7252
Patrick Hemmer268a7072018-05-11 12:52:31 -04007253__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7254{
7255 struct hlua_txn *htxn;
7256
7257 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7258 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7259 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7260 return 0;
7261}
7262
7263__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7264{
7265 struct hlua_txn *htxn;
7266
7267 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7268 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7269 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7270 return 0;
7271}
7272
Christopher Faulet700d9e82020-01-31 12:21:52 +01007273/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007274 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007275 * message and terminate the transaction. It returns 1 on success and 0 on
7276 * error. The Reply must be on top of the stack.
7277 */
7278__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7279{
7280 struct htx *htx;
7281 struct htx_sl *sl;
7282 struct h1m h1m;
7283 const char *status, *reason, *body;
7284 size_t status_len, reason_len, body_len;
7285 int ret, code, flags;
7286
7287 code = 200;
7288 status = "200";
7289 status_len = 3;
7290 ret = lua_getfield(L, -1, "status");
7291 if (ret == LUA_TNUMBER) {
7292 code = lua_tointeger(L, -1);
7293 status = lua_tolstring(L, -1, &status_len);
7294 }
7295 lua_pop(L, 1);
7296
7297 reason = http_get_reason(code);
7298 reason_len = strlen(reason);
7299 ret = lua_getfield(L, -1, "reason");
7300 if (ret == LUA_TSTRING)
7301 reason = lua_tolstring(L, -1, &reason_len);
7302 lua_pop(L, 1);
7303
7304 body = NULL;
7305 body_len = 0;
7306 ret = lua_getfield(L, -1, "body");
7307 if (ret == LUA_TSTRING)
7308 body = lua_tolstring(L, -1, &body_len);
7309 lua_pop(L, 1);
7310
7311 /* Prepare the response before inserting the headers */
7312 h1m_init_res(&h1m);
7313 htx = htx_from_buf(&s->res.buf);
7314 channel_htx_truncate(&s->res, htx);
7315 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7316 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7317 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7318 ist2(status, status_len), ist2(reason, reason_len));
7319 }
7320 else {
7321 flags = HTX_SL_F_IS_RESP;
7322 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7323 ist2(status, status_len), ist2(reason, reason_len));
7324 }
7325 if (!sl)
7326 goto fail;
7327 sl->info.res.status = code;
7328
7329 /* Push in the stack the "headers" entry. */
7330 ret = lua_getfield(L, -1, "headers");
7331 if (ret != LUA_TTABLE)
7332 goto skip_headers;
7333
7334 lua_pushnil(L);
7335 while (lua_next(L, -2) != 0) {
7336 struct ist name, value;
7337 const char *n, *v;
7338 size_t nlen, vlen;
7339
7340 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7341 /* Skip element if the key is not a string or if the value is not a table */
7342 goto next_hdr;
7343 }
7344
7345 n = lua_tolstring(L, -2, &nlen);
7346 name = ist2(n, nlen);
7347 if (isteqi(name, ist("content-length"))) {
7348 /* Always skip content-length header. It will be added
7349 * later with the correct len
7350 */
7351 goto next_hdr;
7352 }
7353
7354 /* Loop on header's values */
7355 lua_pushnil(L);
7356 while (lua_next(L, -2)) {
7357 if (!lua_isstring(L, -1)) {
7358 /* Skip the value if it is not a string */
7359 goto next_value;
7360 }
7361
7362 v = lua_tolstring(L, -1, &vlen);
7363 value = ist2(v, vlen);
7364
7365 if (isteqi(name, ist("transfer-encoding")))
7366 h1_parse_xfer_enc_header(&h1m, value);
7367 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7368 goto fail;
7369
7370 next_value:
7371 lua_pop(L, 1);
7372 }
7373
7374 next_hdr:
7375 lua_pop(L, 1);
7376 }
7377 skip_headers:
7378 lua_pop(L, 1);
7379
7380 /* Update h1m flags: CLEN is set if CHNK is not present */
7381 if (!(h1m.flags & H1_MF_CHNK)) {
7382 const char *clen = ultoa(body_len);
7383
7384 h1m.flags |= H1_MF_CLEN;
7385 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7386 goto fail;
7387 }
7388 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7389 h1m.flags |= H1_MF_XFER_LEN;
7390
7391 /* Update HTX start-line flags */
7392 if (h1m.flags & H1_MF_XFER_ENC)
7393 flags |= HTX_SL_F_XFER_ENC;
7394 if (h1m.flags & H1_MF_XFER_LEN) {
7395 flags |= HTX_SL_F_XFER_LEN;
7396 if (h1m.flags & H1_MF_CHNK)
7397 flags |= HTX_SL_F_CHNK;
7398 else if (h1m.flags & H1_MF_CLEN)
7399 flags |= HTX_SL_F_CLEN;
7400 if (h1m.body_len == 0)
7401 flags |= HTX_SL_F_BODYLESS;
7402 }
7403 sl->flags |= flags;
7404
7405
7406 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007407 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007408 goto fail;
7409
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007410 htx->flags |= HTX_FL_EOM;
7411
Christopher Faulet700d9e82020-01-31 12:21:52 +01007412 /* Now, forward the response and terminate the transaction */
7413 s->txn->status = code;
7414 htx_to_buf(htx, &s->res.buf);
7415 if (!http_forward_proxy_resp(s, 1))
7416 goto fail;
7417
7418 return 1;
7419
7420 fail:
7421 channel_htx_truncate(&s->res, htx);
7422 return 0;
7423}
7424
7425/* Terminate a transaction if called from a lua action. For TCP streams,
7426 * processing is just aborted. Nothing is returned to the client and all
7427 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7428 * is forwarded to the client before terminating the transaction. On success,
7429 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7430 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7431 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007432 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007433__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007434{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007435 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007436 struct stream *s;
7437 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007438
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007439 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007440
Christopher Faulet700d9e82020-01-31 12:21:52 +01007441 /* If the flags NOTERM is set, we cannot terminate the session, so we
7442 * just end the execution of the current lua code. */
7443 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007444 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007445
Christopher Faulet700d9e82020-01-31 12:21:52 +01007446 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007447 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007448 struct channel *req = &s->req;
7449 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007450
Christopher Faulet700d9e82020-01-31 12:21:52 +01007451 channel_auto_read(req);
7452 channel_abort(req);
7453 channel_auto_close(req);
7454 channel_erase(req);
7455
7456 res->wex = tick_add_ifset(now_ms, res->wto);
7457 channel_auto_read(res);
7458 channel_auto_close(res);
7459 channel_shutr_now(res);
7460
7461 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7462 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007463 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007464
Christopher Faulet700d9e82020-01-31 12:21:52 +01007465 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7466 /* No reply or invalid reply */
7467 s->txn->status = 0;
7468 http_reply_and_close(s, 0, NULL);
7469 }
7470 else {
7471 /* Remove extra args to have the reply on top of the stack */
7472 if (lua_gettop(L) > 2)
7473 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007474
Christopher Faulet700d9e82020-01-31 12:21:52 +01007475 if (!hlua_txn_forward_reply(L, s)) {
7476 if (!(s->flags & SF_ERR_MASK))
7477 s->flags |= SF_ERR_PRXCOND;
7478 lua_pushinteger(L, ACT_RET_ERR);
7479 WILL_LJMP(hlua_done(L));
7480 return 0; /* Never reached */
7481 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007482 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007483
Christopher Faulet700d9e82020-01-31 12:21:52 +01007484 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7485 if (htxn->dir == SMP_OPT_DIR_REQ) {
7486 /* let's log the request time */
7487 s->logs.tv_request = now;
7488 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007489 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007490 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007491
Christopher Faulet700d9e82020-01-31 12:21:52 +01007492 done:
7493 if (!(s->flags & SF_ERR_MASK))
7494 s->flags |= SF_ERR_LOCAL;
7495 if (!(s->flags & SF_FINST_MASK))
7496 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007497
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007498 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7499 lua_pushinteger(L, -1);
7500 else
7501 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007502 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007503 return 0;
7504}
7505
Christopher Faulet700d9e82020-01-31 12:21:52 +01007506/*
7507 *
7508 *
7509 * Class REPLY
7510 *
7511 *
7512 */
7513
7514/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
7515 * free slots, the function fails and returns 0;
7516 */
7517static int hlua_txn_reply_new(lua_State *L)
7518{
7519 struct hlua_txn *htxn;
7520 const char *reason, *body = NULL;
7521 int ret, status;
7522
7523 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007524 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007525 hlua_pusherror(L, "txn object is not an HTTP transaction.");
7526 WILL_LJMP(lua_error(L));
7527 }
7528
7529 /* Default value */
7530 status = 200;
7531 reason = http_get_reason(status);
7532
7533 if (lua_istable(L, 2)) {
7534 /* load status and reason from the table argument at index 2 */
7535 ret = lua_getfield(L, 2, "status");
7536 if (ret == LUA_TNIL)
7537 goto reason;
7538 else if (ret != LUA_TNUMBER) {
7539 /* invalid status: ignore the reason */
7540 goto body;
7541 }
7542 status = lua_tointeger(L, -1);
7543
7544 reason:
7545 lua_pop(L, 1); /* restore the stack: remove status */
7546 ret = lua_getfield(L, 2, "reason");
7547 if (ret == LUA_TSTRING)
7548 reason = lua_tostring(L, -1);
7549
7550 body:
7551 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
7552 ret = lua_getfield(L, 2, "body");
7553 if (ret == LUA_TSTRING)
7554 body = lua_tostring(L, -1);
7555 lua_pop(L, 1); /* restore the stack: remove body */
7556 }
7557
7558 /* Create the Reply table */
7559 lua_newtable(L);
7560
7561 /* Add status element */
7562 lua_pushstring(L, "status");
7563 lua_pushinteger(L, status);
7564 lua_settable(L, -3);
7565
7566 /* Add reason element */
7567 reason = http_get_reason(status);
7568 lua_pushstring(L, "reason");
7569 lua_pushstring(L, reason);
7570 lua_settable(L, -3);
7571
7572 /* Add body element, nil if undefined */
7573 lua_pushstring(L, "body");
7574 if (body)
7575 lua_pushstring(L, body);
7576 else
7577 lua_pushnil(L);
7578 lua_settable(L, -3);
7579
7580 /* Add headers element */
7581 lua_pushstring(L, "headers");
7582 lua_newtable(L);
7583
7584 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7585 if (lua_istable(L, 2)) {
7586 /* load headers from the table argument at index 2. If it is a table, copy it. */
7587 ret = lua_getfield(L, 2, "headers");
7588 if (ret == LUA_TTABLE) {
7589 /* stack: [ ... <headers:table>, <table> ] */
7590 lua_pushnil(L);
7591 while (lua_next(L, -2) != 0) {
7592 /* stack: [ ... <headers:table>, <table>, k, v] */
7593 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
7594 /* invalid value type, skip it */
7595 lua_pop(L, 1);
7596 continue;
7597 }
7598
7599
7600 /* Duplicate the key and swap it with the value. */
7601 lua_pushvalue(L, -2);
7602 lua_insert(L, -2);
7603 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
7604
7605 lua_newtable(L);
7606 lua_insert(L, -2);
7607 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
7608
7609 if (lua_isstring(L, -1)) {
7610 /* push the value in the inner table */
7611 lua_rawseti(L, -2, 1);
7612 }
7613 else { /* table */
7614 lua_pushnil(L);
7615 while (lua_next(L, -2) != 0) {
7616 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
7617 if (!lua_isstring(L, -1)) {
7618 /* invalid value type, skip it*/
7619 lua_pop(L, 1);
7620 continue;
7621 }
7622 /* push the value in the inner table */
7623 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
7624 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
7625 }
7626 lua_pop(L, 1);
7627 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
7628 }
7629
7630 /* push (k,v) on the stack in the headers table:
7631 * stack: [ ... <headers:table>, <table>, k, k, v ]
7632 */
7633 lua_settable(L, -5);
7634 /* stack: [ ... <headers:table>, <table>, k ] */
7635 }
7636 }
7637 lua_pop(L, 1);
7638 }
7639 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7640 lua_settable(L, -3);
7641 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
7642
7643 /* Pop a class sesison metatable and affect it to the userdata. */
7644 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
7645 lua_setmetatable(L, -2);
7646 return 1;
7647}
7648
7649/* Set the reply status code, and optionally the reason. If no reason is
7650 * provided, the default one corresponding to the status code is used.
7651 */
7652__LJMP static int hlua_txn_reply_set_status(lua_State *L)
7653{
7654 int status = MAY_LJMP(luaL_checkinteger(L, 2));
7655 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
7656
7657 /* First argument (self) must be a table */
7658 luaL_checktype(L, 1, LUA_TTABLE);
7659
7660 if (status < 100 || status > 599) {
7661 lua_pushboolean(L, 0);
7662 return 1;
7663 }
7664 if (!reason)
7665 reason = http_get_reason(status);
7666
7667 lua_pushinteger(L, status);
7668 lua_setfield(L, 1, "status");
7669
7670 lua_pushstring(L, reason);
7671 lua_setfield(L, 1, "reason");
7672
7673 lua_pushboolean(L, 1);
7674 return 1;
7675}
7676
7677/* Add a header into the reply object. Each header name is associated to an
7678 * array of values in the "headers" table. If the header name is not found, a
7679 * new entry is created.
7680 */
7681__LJMP static int hlua_txn_reply_add_header(lua_State *L)
7682{
7683 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7684 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
7685 int ret;
7686
7687 /* First argument (self) must be a table */
7688 luaL_checktype(L, 1, LUA_TTABLE);
7689
7690 /* Push in the stack the "headers" entry. */
7691 ret = lua_getfield(L, 1, "headers");
7692 if (ret != LUA_TTABLE) {
7693 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
7694 WILL_LJMP(lua_error(L));
7695 }
7696
7697 /* check if the header is already registered. If not, register it. */
7698 ret = lua_getfield(L, -1, name);
7699 if (ret == LUA_TNIL) {
7700 /* Entry not found. */
7701 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
7702
7703 /* Insert the new header name in the array in the top of the stack.
7704 * It left the new array in the top of the stack.
7705 */
7706 lua_newtable(L);
7707 lua_pushstring(L, name);
7708 lua_pushvalue(L, -2);
7709 lua_settable(L, -4);
7710 }
7711 else if (ret != LUA_TTABLE) {
7712 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
7713 WILL_LJMP(lua_error(L));
7714 }
7715
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07007716 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01007717 * the header value as new entry.
7718 */
7719 lua_pushstring(L, value);
7720 ret = lua_rawlen(L, -2);
7721 lua_rawseti(L, -2, ret + 1);
7722
7723 lua_pushboolean(L, 1);
7724 return 1;
7725}
7726
7727/* Remove all occurrences of a given header name. */
7728__LJMP static int hlua_txn_reply_del_header(lua_State *L)
7729{
7730 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7731 int ret;
7732
7733 /* First argument (self) must be a table */
7734 luaL_checktype(L, 1, LUA_TTABLE);
7735
7736 /* Push in the stack the "headers" entry. */
7737 ret = lua_getfield(L, 1, "headers");
7738 if (ret != LUA_TTABLE) {
7739 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
7740 WILL_LJMP(lua_error(L));
7741 }
7742
7743 lua_pushstring(L, name);
7744 lua_pushnil(L);
7745 lua_settable(L, -3);
7746
7747 lua_pushboolean(L, 1);
7748 return 1;
7749}
7750
7751/* Set the reply's body. Overwrite any existing entry. */
7752__LJMP static int hlua_txn_reply_set_body(lua_State *L)
7753{
7754 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
7755
7756 /* First argument (self) must be a table */
7757 luaL_checktype(L, 1, LUA_TTABLE);
7758
7759 lua_pushstring(L, payload);
7760 lua_setfield(L, 1, "body");
7761
7762 lua_pushboolean(L, 1);
7763 return 1;
7764}
7765
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007766__LJMP static int hlua_log(lua_State *L)
7767{
7768 int level;
7769 const char *msg;
7770
7771 MAY_LJMP(check_args(L, 2, "log"));
7772 level = MAY_LJMP(luaL_checkinteger(L, 1));
7773 msg = MAY_LJMP(luaL_checkstring(L, 2));
7774
7775 if (level < 0 || level >= NB_LOG_LEVELS)
7776 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7777
7778 hlua_sendlog(NULL, level, msg);
7779 return 0;
7780}
7781
7782__LJMP static int hlua_log_debug(lua_State *L)
7783{
7784 const char *msg;
7785
7786 MAY_LJMP(check_args(L, 1, "debug"));
7787 msg = MAY_LJMP(luaL_checkstring(L, 1));
7788 hlua_sendlog(NULL, LOG_DEBUG, msg);
7789 return 0;
7790}
7791
7792__LJMP static int hlua_log_info(lua_State *L)
7793{
7794 const char *msg;
7795
7796 MAY_LJMP(check_args(L, 1, "info"));
7797 msg = MAY_LJMP(luaL_checkstring(L, 1));
7798 hlua_sendlog(NULL, LOG_INFO, msg);
7799 return 0;
7800}
7801
7802__LJMP static int hlua_log_warning(lua_State *L)
7803{
7804 const char *msg;
7805
7806 MAY_LJMP(check_args(L, 1, "warning"));
7807 msg = MAY_LJMP(luaL_checkstring(L, 1));
7808 hlua_sendlog(NULL, LOG_WARNING, msg);
7809 return 0;
7810}
7811
7812__LJMP static int hlua_log_alert(lua_State *L)
7813{
7814 const char *msg;
7815
7816 MAY_LJMP(check_args(L, 1, "alert"));
7817 msg = MAY_LJMP(luaL_checkstring(L, 1));
7818 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007819 return 0;
7820}
7821
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007822__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007823{
7824 int wakeup_ms = lua_tointeger(L, -1);
7825 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02007826 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007827 return 0;
7828}
7829
7830__LJMP static int hlua_sleep(lua_State *L)
7831{
7832 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007833 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007834
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007835 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007836
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007837 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007838 wakeup_ms = tick_add(now_ms, delay);
7839 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007840
Willy Tarreau9635e032018-10-16 17:52:55 +02007841 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007842 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007843}
7844
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007845__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007846{
7847 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007848 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007849
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007850 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007851
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007852 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007853 wakeup_ms = tick_add(now_ms, delay);
7854 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007855
Willy Tarreau9635e032018-10-16 17:52:55 +02007856 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007857 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007858}
7859
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007860/* This functionis an LUA binding. it permits to give back
7861 * the hand at the HAProxy scheduler. It is used when the
7862 * LUA processing consumes a lot of time.
7863 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007864__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007865{
7866 return 0;
7867}
7868
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007869__LJMP static int hlua_yield(lua_State *L)
7870{
Willy Tarreau9635e032018-10-16 17:52:55 +02007871 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007872 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007873}
7874
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007875/* This function change the nice of the currently executed
7876 * task. It is used set low or high priority at the current
7877 * task.
7878 */
Willy Tarreau59551662015-03-10 14:23:13 +01007879__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007880{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007881 struct hlua *hlua;
7882 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007883
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007884 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007885 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007886
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007887 /* Get hlua struct, or NULL if we execute from main lua state */
7888 hlua = hlua_gethlua(L);
7889
7890 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007891 if (!hlua || !hlua->task)
7892 return 0;
7893
7894 if (nice < -1024)
7895 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007896 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007897 nice = 1024;
7898
7899 hlua->task->nice = nice;
7900 return 0;
7901}
7902
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007903/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007904 * HAProxy task subsystem when the task is awaked. The LUA runtime can
7905 * return an E_AGAIN signal, the emmiter of this signal must set a
7906 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007907 *
7908 * Task wrapper are longjmp safe because the only one Lua code
7909 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007910 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01007911struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007912{
Olivier Houchard9f6af332018-05-25 14:04:04 +02007913 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007914 enum hlua_exec status;
7915
Christopher Faulet5bc99722018-04-25 10:34:45 +02007916 if (task->thread_mask == MAX_THREADS_MASK)
7917 task_set_affinity(task, tid_bit);
7918
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007919 /* If it is the first call to the task, we must initialize the
7920 * execution timeouts.
7921 */
7922 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007923 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007924
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007925 /* Execute the Lua code. */
7926 status = hlua_ctx_resume(hlua, 1);
7927
7928 switch (status) {
7929 /* finished or yield */
7930 case HLUA_E_OK:
7931 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007932 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02007933 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007934 break;
7935
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01007936 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01007937 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02007938 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007939 break;
7940
7941 /* finished with error. */
7942 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007943 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007944 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007945 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007946 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007947 break;
7948
7949 case HLUA_E_ERR:
7950 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007951 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007952 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007953 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007954 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007955 break;
7956 }
Emeric Brun253e53e2017-10-17 18:58:40 +02007957 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007958}
7959
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007960/* This function is an LUA binding that register LUA function to be
7961 * executed after the HAProxy configuration parsing and before the
7962 * HAProxy scheduler starts. This function expect only one LUA
7963 * argument that is a function. This function returns nothing, but
7964 * throws if an error is encountered.
7965 */
7966__LJMP static int hlua_register_init(lua_State *L)
7967{
7968 struct hlua_init_function *init;
7969 int ref;
7970
7971 MAY_LJMP(check_args(L, 1, "register_init"));
7972
7973 ref = MAY_LJMP(hlua_checkfunction(L, 1));
7974
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007975 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007976 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007977 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007978
7979 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02007980 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007981 return 0;
7982}
7983
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007984/* This functio is an LUA binding. It permits to register a task
7985 * executed in parallel of the main HAroxy activity. The task is
7986 * created and it is set in the HAProxy scheduler. It can be called
7987 * from the "init" section, "post init" or during the runtime.
7988 *
7989 * Lua prototype:
7990 *
7991 * <none> core.register_task(<function>)
7992 */
7993static int hlua_register_task(lua_State *L)
7994{
Christopher Faulet5294ec02021-04-12 12:24:47 +02007995 struct hlua *hlua = NULL;
7996 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007997 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01007998 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007999
8000 MAY_LJMP(check_args(L, 1, "register_task"));
8001
8002 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8003
Thierry Fournier75fc0292020-11-28 13:18:56 +01008004 /* Get the reference state. If the reference is NULL, L is the master
8005 * state, otherwise hlua->T is.
8006 */
8007 hlua = hlua_gethlua(L);
8008 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008009 /* we are in runtime processing */
8010 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008011 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008012 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008013 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008014
Willy Tarreaubafbe012017-11-24 17:34:44 +01008015 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008016 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008017 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008018 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008019
Thierry Fournier59f11be2020-11-29 00:37:41 +01008020 /* We are in the common lua state, execute the task anywhere,
8021 * otherwise, inherit the current thread identifier
8022 */
8023 if (state_id == 0)
8024 task = task_new(MAX_THREADS_MASK);
8025 else
8026 task = task_new(tid_bit);
Willy Tarreaue09101e2018-10-16 17:37:12 +02008027 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008028 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008029
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008030 task->context = hlua;
8031 task->process = hlua_process_task;
8032
Thierry Fournier021d9862020-11-28 23:42:03 +01008033 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008034 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008035
8036 /* Restore the function in the stack. */
8037 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8038 hlua->nargs = 0;
8039
8040 /* Schedule task. */
8041 task_schedule(task, now_ms);
8042
8043 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008044
8045 alloc_error:
8046 task_destroy(task);
8047 hlua_ctx_destroy(hlua);
8048 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8049 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008050}
8051
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008052/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8053 * doesn't allow "yield" functions because the HAProxy engine cannot
8054 * resume converters.
8055 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008056static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008057{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008058 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008059 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008060 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008061
Willy Tarreaube508f12016-03-10 11:47:01 +01008062 if (!stream)
8063 return 0;
8064
Willy Tarreau87b09662015-04-03 00:22:06 +02008065 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008066 * Lua context can be not initialized. This behavior
8067 * permits to save performances because a systematic
8068 * Lua initialization cause 5% performances loss.
8069 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008070 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008071 struct hlua *hlua;
8072
8073 hlua = pool_alloc(pool_head_hlua);
8074 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008075 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8076 return 0;
8077 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008078 HLUA_INIT(hlua);
8079 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008080 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008081 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8082 return 0;
8083 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008084 }
8085
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008086 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008087 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008088
8089 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008090 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008091 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8092 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008093 else
8094 error = "critical error";
8095 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008096 return 0;
8097 }
8098
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008099 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008100 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008101 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008102 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008103 return 0;
8104 }
8105
8106 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008107 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008108
8109 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008110 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008111 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008112 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008113 return 0;
8114 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008115 hlua_smp2lua(stream->hlua->T, smp);
8116 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008117
8118 /* push keywords in the stack. */
8119 if (arg_p) {
8120 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008121 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008122 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008123 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008124 return 0;
8125 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008126 hlua_arg2lua(stream->hlua->T, arg_p);
8127 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008128 }
8129 }
8130
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008131 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008132 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008133
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008134 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008135 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008136 }
8137
8138 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008139 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008140 /* finished. */
8141 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008142 /* If the stack is empty, the function fails. */
8143 if (lua_gettop(stream->hlua->T) <= 0)
8144 return 0;
8145
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008146 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008147 hlua_lua2smp(stream->hlua->T, -1, smp);
8148 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008149 return 1;
8150
8151 /* yield. */
8152 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008153 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008154 return 0;
8155
8156 /* finished with error. */
8157 case HLUA_E_ERRMSG:
8158 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008159 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008160 fcn->name, lua_tostring(stream->hlua->T, -1));
8161 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008162 return 0;
8163
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008164 case HLUA_E_ETMOUT:
8165 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8166 return 0;
8167
8168 case HLUA_E_NOMEM:
8169 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8170 return 0;
8171
8172 case HLUA_E_YIELD:
8173 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8174 return 0;
8175
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008176 case HLUA_E_ERR:
8177 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008178 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008179 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008180
8181 default:
8182 return 0;
8183 }
8184}
8185
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008186/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8187 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008188 * resume sample-fetches. This function will be called by the sample
8189 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008190 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008191static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8192 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008193{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008194 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008195 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008196 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008197 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008198
Willy Tarreaube508f12016-03-10 11:47:01 +01008199 if (!stream)
8200 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008201
Willy Tarreau87b09662015-04-03 00:22:06 +02008202 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008203 * Lua context can be not initialized. This behavior
8204 * permits to save performances because a systematic
8205 * Lua initialization cause 5% performances loss.
8206 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008207 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008208 struct hlua *hlua;
8209
8210 hlua = pool_alloc(pool_head_hlua);
8211 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008212 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8213 return 0;
8214 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008215 hlua->T = NULL;
8216 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008217 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008218 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8219 return 0;
8220 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008221 }
8222
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008223 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008224 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008225
8226 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008227 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008228 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8229 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008230 else
8231 error = "critical error";
8232 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008233 return 0;
8234 }
8235
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008236 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008237 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008238 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008239 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008240 return 0;
8241 }
8242
8243 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008244 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008245
8246 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008247 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008248 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008249 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008250 return 0;
8251 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008252 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008253
8254 /* push keywords in the stack. */
8255 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8256 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008257 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008258 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008259 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008260 return 0;
8261 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008262 hlua_arg2lua(stream->hlua->T, arg_p);
8263 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008264 }
8265
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008266 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008267 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008268
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008269 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008270 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008271 }
8272
8273 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008274 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008275 /* finished. */
8276 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008277 /* If the stack is empty, the function fails. */
8278 if (lua_gettop(stream->hlua->T) <= 0)
8279 return 0;
8280
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008281 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008282 hlua_lua2smp(stream->hlua->T, -1, smp);
8283 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008284
8285 /* Set the end of execution flag. */
8286 smp->flags &= ~SMP_F_MAY_CHANGE;
8287 return 1;
8288
8289 /* yield. */
8290 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008291 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008292 return 0;
8293
8294 /* finished with error. */
8295 case HLUA_E_ERRMSG:
8296 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008297 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008298 fcn->name, lua_tostring(stream->hlua->T, -1));
8299 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008300 return 0;
8301
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008302 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008303 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8304 return 0;
8305
8306 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008307 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8308 return 0;
8309
8310 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008311 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8312 return 0;
8313
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008314 case HLUA_E_ERR:
8315 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008316 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008317 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008318
8319 default:
8320 return 0;
8321 }
8322}
8323
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008324/* This function is an LUA binding used for registering
8325 * "sample-conv" functions. It expects a converter name used
8326 * in the haproxy configuration file, and an LUA function.
8327 */
8328__LJMP static int hlua_register_converters(lua_State *L)
8329{
8330 struct sample_conv_kw_list *sck;
8331 const char *name;
8332 int ref;
8333 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008334 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008335 struct sample_conv *sc;
8336 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008337
8338 MAY_LJMP(check_args(L, 2, "register_converters"));
8339
8340 /* First argument : converter name. */
8341 name = MAY_LJMP(luaL_checkstring(L, 1));
8342
8343 /* Second argument : lua function. */
8344 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8345
Thierry Fournierf67442e2020-11-28 20:41:07 +01008346 /* Check if the converter is already registered */
8347 trash = get_trash_chunk();
8348 chunk_printf(trash, "lua.%s", name);
8349 sc = find_sample_conv(trash->area, trash->data);
8350 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008351 fcn = sc->private;
8352 if (fcn->function_ref[hlua_state_id] != -1) {
8353 ha_warning("Trying to register converter 'lua.%s' more than once. "
8354 "This will become a hard error in version 2.5.\n", name);
8355 }
8356 fcn->function_ref[hlua_state_id] = ref;
8357 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008358 }
8359
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008360 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008361 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008362 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008363 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008364 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008365 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008366 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008367
8368 /* Fill fcn. */
8369 fcn->name = strdup(name);
8370 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008371 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008372 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008373
8374 /* List head */
8375 sck->list.n = sck->list.p = NULL;
8376
8377 /* converter keyword. */
8378 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008379 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008380 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008381 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008382
8383 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8384 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008385 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 +01008386 sck->kw[0].val_args = NULL;
8387 sck->kw[0].in_type = SMP_T_STR;
8388 sck->kw[0].out_type = SMP_T_STR;
8389 sck->kw[0].private = fcn;
8390
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008391 /* Register this new converter */
8392 sample_register_convs(sck);
8393
8394 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008395
8396 alloc_error:
8397 release_hlua_function(fcn);
8398 ha_free(&sck);
8399 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8400 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008401}
8402
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008403/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008404 * "sample-fetch" functions. It expects a converter name used
8405 * in the haproxy configuration file, and an LUA function.
8406 */
8407__LJMP static int hlua_register_fetches(lua_State *L)
8408{
8409 const char *name;
8410 int ref;
8411 int len;
8412 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008413 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008414 struct sample_fetch *sf;
8415 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008416
8417 MAY_LJMP(check_args(L, 2, "register_fetches"));
8418
8419 /* First argument : sample-fetch name. */
8420 name = MAY_LJMP(luaL_checkstring(L, 1));
8421
8422 /* Second argument : lua function. */
8423 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8424
Thierry Fournierf67442e2020-11-28 20:41:07 +01008425 /* Check if the sample-fetch is already registered */
8426 trash = get_trash_chunk();
8427 chunk_printf(trash, "lua.%s", name);
8428 sf = find_sample_fetch(trash->area, trash->data);
8429 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008430 fcn = sf->private;
8431 if (fcn->function_ref[hlua_state_id] != -1) {
8432 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8433 "This will become a hard error in version 2.5.\n", name);
8434 }
8435 fcn->function_ref[hlua_state_id] = ref;
8436 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008437 }
8438
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008439 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008440 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008441 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008442 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008443 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008444 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008445 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008446
8447 /* Fill fcn. */
8448 fcn->name = strdup(name);
8449 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008450 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008451 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008452
8453 /* List head */
8454 sfk->list.n = sfk->list.p = NULL;
8455
8456 /* sample-fetch keyword. */
8457 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008458 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008459 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008460 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008461
8462 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8463 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008464 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 +01008465 sfk->kw[0].val_args = NULL;
8466 sfk->kw[0].out_type = SMP_T_STR;
8467 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8468 sfk->kw[0].val = 0;
8469 sfk->kw[0].private = fcn;
8470
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008471 /* Register this new fetch. */
8472 sample_register_fetches(sfk);
8473
8474 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008475
8476 alloc_error:
8477 release_hlua_function(fcn);
8478 ha_free(&sfk);
8479 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8480 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008481}
8482
Christopher Faulet501465d2020-02-26 14:54:16 +01008483/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008484 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008485__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008486{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008487 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008488 unsigned int delay;
8489 unsigned int wakeup_ms;
8490
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008491 /* Get hlua struct, or NULL if we execute from main lua state */
8492 hlua = hlua_gethlua(L);
8493 if (!hlua) {
8494 return 0;
8495 }
8496
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008497 MAY_LJMP(check_args(L, 1, "wake_time"));
8498
8499 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8500 wakeup_ms = tick_add(now_ms, delay);
8501 hlua->wake_time = wakeup_ms;
8502 return 0;
8503}
8504
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008505/* This function is a wrapper to execute each LUA function declared as an action
8506 * wrapper during the initialisation period. This function may return any
8507 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8508 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8509 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008510 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008511static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02008512 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008513{
8514 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008515 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008516 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008517 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008518
8519 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008520 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
8521 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
8522 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
8523 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008524 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008525 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008526 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008527 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008528
Willy Tarreau87b09662015-04-03 00:22:06 +02008529 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008530 * Lua context can be not initialized. This behavior
8531 * permits to save performances because a systematic
8532 * Lua initialization cause 5% performances loss.
8533 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008534 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008535 struct hlua *hlua;
8536
8537 hlua = pool_alloc(pool_head_hlua);
8538 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008539 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008540 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008541 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008542 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008543 HLUA_INIT(hlua);
8544 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008545 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 +01008546 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008547 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008548 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008549 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008550 }
8551
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008552 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008553 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008554
8555 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008556 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008557 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
8558 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008559 else
8560 error = "critical error";
8561 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008562 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008563 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008564 }
8565
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008566 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008567 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008568 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008569 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008570 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008571 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008572 }
8573
8574 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008575 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 +01008576
Willy Tarreau87b09662015-04-03 00:22:06 +02008577 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008578 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008579 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008580 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008581 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008582 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008583 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008584 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008585
8586 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008587 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008588 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008589 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008590 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008591 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008592 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008593 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008594 lua_pushstring(s->hlua->T, *arg);
8595 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008596 }
8597
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008598 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008599 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008600
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008601 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008602 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008603 }
8604
8605 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01008606 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008607 /* finished. */
8608 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008609 /* Catch the return value */
8610 if (lua_gettop(s->hlua->T) > 0)
8611 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008612
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008613 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02008614 if (act_ret == ACT_RET_YIELD) {
8615 if (flags & ACT_OPT_FINAL)
8616 goto err_yield;
8617
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008618 if (dir == SMP_OPT_DIR_REQ)
8619 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8620 s->hlua->wake_time);
8621 else
8622 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8623 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008624 }
8625 goto end;
8626
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008627 /* yield. */
8628 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008629 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008630 if (dir == SMP_OPT_DIR_REQ)
8631 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8632 s->hlua->wake_time);
8633 else
8634 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8635 s->hlua->wake_time);
8636
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008637 /* Some actions can be wake up when a "write" event
8638 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008639 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008640 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02008641 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008642 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008643 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008644 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008645 act_ret = ACT_RET_YIELD;
8646 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008647
8648 /* finished with error. */
8649 case HLUA_E_ERRMSG:
8650 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008651 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008652 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008653 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008654 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008655
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008656 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008657 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008658 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008659
8660 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008661 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008662 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008663
8664 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02008665 err_yield:
8666 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008667 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008668 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008669 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008670
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008671 case HLUA_E_ERR:
8672 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008673 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008674 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008675
8676 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008677 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008678 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008679
8680 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02008681 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008682 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008683 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008684}
8685
Willy Tarreau144f84a2021-03-02 16:09:26 +01008686struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008687{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008688 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008689
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008690 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02008691 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02008692 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008693}
8694
8695static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8696{
8697 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008698 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008699 struct task *task;
8700 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008701 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008702
Willy Tarreaubafbe012017-11-24 17:34:44 +01008703 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008704 if (!hlua) {
8705 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008706 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008707 return 0;
8708 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008709 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008710 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008711 ctx->ctx.hlua_apptcp.flags = 0;
8712
8713 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008714 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008715 if (!task) {
8716 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008717 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008718 return 0;
8719 }
8720 task->nice = 0;
8721 task->context = ctx;
8722 task->process = hlua_applet_wakeup;
8723 ctx->ctx.hlua_apptcp.task = task;
8724
8725 /* In the execution wrappers linked with a stream, the
8726 * Lua context can be not initialized. This behavior
8727 * permits to save performances because a systematic
8728 * Lua initialization cause 5% performances loss.
8729 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008730 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 +02008731 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008732 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008733 return 0;
8734 }
8735
8736 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008737 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008738
8739 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008740 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008741 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8742 error = lua_tostring(hlua->T, -1);
8743 else
8744 error = "critical error";
8745 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008746 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008747 return 0;
8748 }
8749
8750 /* Check stack available size. */
8751 if (!lua_checkstack(hlua->T, 1)) {
8752 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008753 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008754 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008755 return 0;
8756 }
8757
8758 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008759 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008760
8761 /* Create and and push object stream in the stack. */
8762 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
8763 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008764 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008765 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008766 return 0;
8767 }
8768 hlua->nargs = 1;
8769
8770 /* push keywords in the stack. */
8771 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8772 if (!lua_checkstack(hlua->T, 1)) {
8773 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008774 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008775 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008776 return 0;
8777 }
8778 lua_pushstring(hlua->T, *arg);
8779 hlua->nargs++;
8780 }
8781
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008782 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008783
8784 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008785 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01008786 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008787
8788 return 1;
8789}
8790
Willy Tarreau60409db2019-08-21 14:14:50 +02008791void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008792{
8793 struct stream_interface *si = ctx->owner;
8794 struct stream *strm = si_strm(si);
8795 struct channel *res = si_ic(si);
8796 struct act_rule *rule = ctx->rule;
8797 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008798 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008799
8800 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02008801 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
8802 /* eat the whole request */
8803 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008804 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02008805 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008806
8807 /* If the stream is disconnect or closed, ldo nothing. */
8808 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8809 return;
8810
8811 /* Execute the function. */
8812 switch (hlua_ctx_resume(hlua, 1)) {
8813 /* finished. */
8814 case HLUA_E_OK:
8815 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8816
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008817 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02008818 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008819 res->flags |= CF_READ_NULL;
8820 si_shutr(si);
8821 return;
8822
8823 /* yield. */
8824 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01008825 if (hlua->wake_time != TICK_ETERNITY)
8826 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008827 return;
8828
8829 /* finished with error. */
8830 case HLUA_E_ERRMSG:
8831 /* Display log. */
8832 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008833 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008834 lua_pop(hlua->T, 1);
8835 goto error;
8836
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008837 case HLUA_E_ETMOUT:
8838 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008839 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008840 goto error;
8841
8842 case HLUA_E_NOMEM:
8843 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008844 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008845 goto error;
8846
8847 case HLUA_E_YIELD: /* unexpected */
8848 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008849 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008850 goto error;
8851
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008852 case HLUA_E_ERR:
8853 /* Display log. */
8854 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008855 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008856 goto error;
8857
8858 default:
8859 goto error;
8860 }
8861
8862error:
8863
8864 /* For all other cases, just close the stream. */
8865 si_shutw(si);
8866 si_shutr(si);
8867 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8868}
8869
8870static void hlua_applet_tcp_release(struct appctx *ctx)
8871{
Olivier Houchard3f795f72019-04-17 22:51:06 +02008872 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008873 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008874 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008875 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008876}
8877
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008878/* The function returns 1 if the initialisation is complete, 0 if
8879 * an errors occurs and -1 if more data are required for initializing
8880 * the applet.
8881 */
8882static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8883{
8884 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008885 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008886 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008887 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008888 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008889 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008890
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008891 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01008892 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008893 if (!hlua) {
8894 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008895 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008896 return 0;
8897 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008898 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008899 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008900 ctx->ctx.hlua_apphttp.left_bytes = -1;
8901 ctx->ctx.hlua_apphttp.flags = 0;
8902
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01008903 if (txn->req.flags & HTTP_MSGF_VER_11)
8904 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
8905
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008906 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008907 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008908 if (!task) {
8909 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008910 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008911 return 0;
8912 }
8913 task->nice = 0;
8914 task->context = ctx;
8915 task->process = hlua_applet_wakeup;
8916 ctx->ctx.hlua_apphttp.task = task;
8917
8918 /* In the execution wrappers linked with a stream, the
8919 * Lua context can be not initialized. This behavior
8920 * permits to save performances because a systematic
8921 * Lua initialization cause 5% performances loss.
8922 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008923 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 +02008924 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008925 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008926 return 0;
8927 }
8928
8929 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008930 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008931
8932 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008933 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008934 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8935 error = lua_tostring(hlua->T, -1);
8936 else
8937 error = "critical error";
8938 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008939 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008940 return 0;
8941 }
8942
8943 /* Check stack available size. */
8944 if (!lua_checkstack(hlua->T, 1)) {
8945 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008946 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008947 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008948 return 0;
8949 }
8950
8951 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008952 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008953
8954 /* Create and and push object stream in the stack. */
8955 if (!hlua_applet_http_new(hlua->T, ctx)) {
8956 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008957 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008958 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008959 return 0;
8960 }
8961 hlua->nargs = 1;
8962
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008963 /* push keywords in the stack. */
8964 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8965 if (!lua_checkstack(hlua->T, 1)) {
8966 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008967 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008968 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008969 return 0;
8970 }
8971 lua_pushstring(hlua->T, *arg);
8972 hlua->nargs++;
8973 }
8974
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008975 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008976
8977 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008978 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008979
8980 return 1;
8981}
8982
Willy Tarreau60409db2019-08-21 14:14:50 +02008983void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008984{
8985 struct stream_interface *si = ctx->owner;
8986 struct stream *strm = si_strm(si);
8987 struct channel *req = si_oc(si);
8988 struct channel *res = si_ic(si);
8989 struct act_rule *rule = ctx->rule;
8990 struct proxy *px = strm->be;
8991 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
8992 struct htx *req_htx, *res_htx;
8993
8994 res_htx = htx_from_buf(&res->buf);
8995
8996 /* If the stream is disconnect or closed, ldo nothing. */
8997 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8998 goto out;
8999
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009000 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009001 if (!b_size(&res->buf)) {
9002 si_rx_room_blk(si);
9003 goto out;
9004 }
9005 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009006 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009007 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9008
9009 /* Set the currently running flag. */
9010 if (!HLUA_IS_RUNNING(hlua) &&
9011 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009012 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009013 si_cant_get(si);
9014 goto out;
9015 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009016 }
9017
9018 /* Executes The applet if it is not done. */
9019 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9020
9021 /* Execute the function. */
9022 switch (hlua_ctx_resume(hlua, 1)) {
9023 /* finished. */
9024 case HLUA_E_OK:
9025 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9026 break;
9027
9028 /* yield. */
9029 case HLUA_E_AGAIN:
9030 if (hlua->wake_time != TICK_ETERNITY)
9031 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009032 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009033
9034 /* finished with error. */
9035 case HLUA_E_ERRMSG:
9036 /* Display log. */
9037 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009038 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009039 lua_pop(hlua->T, 1);
9040 goto error;
9041
9042 case HLUA_E_ETMOUT:
9043 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009044 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009045 goto error;
9046
9047 case HLUA_E_NOMEM:
9048 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009049 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009050 goto error;
9051
9052 case HLUA_E_YIELD: /* unexpected */
9053 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009054 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009055 goto error;
9056
9057 case HLUA_E_ERR:
9058 /* Display log. */
9059 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009060 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009061 goto error;
9062
9063 default:
9064 goto error;
9065 }
9066 }
9067
9068 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009069 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9070 goto done;
9071
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009072 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9073 goto error;
9074
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009075 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
9076 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009077 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9078 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009079 }
9080
9081 done:
9082 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009083 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009084 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009085 si_shutr(si);
9086 }
9087
9088 /* eat the whole request */
9089 if (co_data(req)) {
9090 req_htx = htx_from_buf(&req->buf);
9091 co_htx_skip(req, req_htx, co_data(req));
9092 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009093 }
9094 }
9095
9096 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009097 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009098 return;
9099
9100 error:
9101
9102 /* If we are in HTTP mode, and we are not send any
9103 * data, return a 500 server error in best effort:
9104 * if there is no room available in the buffer,
9105 * just close the connection.
9106 */
9107 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009108 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009109
9110 channel_erase(res);
9111 res->buf.data = b_data(err);
9112 memcpy(res->buf.area, b_head(err), b_data(err));
9113 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009114 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009115 }
9116 if (!(strm->flags & SF_ERR_MASK))
9117 strm->flags |= SF_ERR_RESOURCE;
9118 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9119 goto done;
9120}
9121
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009122static void hlua_applet_http_release(struct appctx *ctx)
9123{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009124 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009125 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009126 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009127 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009128}
9129
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009130/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009131 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009132 *
9133 * This function can fail with an abort() due to an Lua critical error.
9134 * We are in the configuration parsing process of HAProxy, this abort() is
9135 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009136 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009137static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9138 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009139{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009140 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009141 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009142
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009143 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009144 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009145 if (!rule->arg.hlua_rule) {
9146 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009147 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009148 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009149
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009150 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009151 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9152 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009153 if (!rule->arg.hlua_rule->args) {
9154 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009155 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009156 }
9157
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009158 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009159 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009160
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009161 /* Expect some arguments */
9162 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009163 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009164 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009165 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009166 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009167 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009168 if (!rule->arg.hlua_rule->args[i]) {
9169 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009170 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009171 }
9172 (*cur_arg)++;
9173 }
9174 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009175
Thierry FOURNIER42148732015-09-02 17:17:33 +02009176 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009177 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009178 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009179
9180 error:
9181 if (rule->arg.hlua_rule) {
9182 if (rule->arg.hlua_rule->args) {
9183 for (i = 0; i < fcn->nargs; i++)
9184 ha_free(&rule->arg.hlua_rule->args[i]);
9185 ha_free(&rule->arg.hlua_rule->args);
9186 }
9187 ha_free(&rule->arg.hlua_rule);
9188 }
9189 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009190}
9191
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009192static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9193 struct act_rule *rule, char **err)
9194{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009195 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009196
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009197 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009198 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009199 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009200 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009201 * the call of this analyzer.
9202 */
9203 if (rule->from != ACT_F_HTTP_REQ) {
9204 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9205 return ACT_RET_PRS_ERR;
9206 }
9207
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009208 /* Memory for the rule. */
9209 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9210 if (!rule->arg.hlua_rule) {
9211 memprintf(err, "out of memory error");
9212 return ACT_RET_PRS_ERR;
9213 }
9214
9215 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009216 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009217
9218 /* TODO: later accept arguments. */
9219 rule->arg.hlua_rule->args = NULL;
9220
9221 /* Add applet pointer in the rule. */
9222 rule->applet.obj_type = OBJ_TYPE_APPLET;
9223 rule->applet.name = fcn->name;
9224 rule->applet.init = hlua_applet_http_init;
9225 rule->applet.fct = hlua_applet_http_fct;
9226 rule->applet.release = hlua_applet_http_release;
9227 rule->applet.timeout = hlua_timeout_applet;
9228
9229 return ACT_RET_PRS_OK;
9230}
9231
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009232/* This function is an LUA binding used for registering
9233 * "sample-conv" functions. It expects a converter name used
9234 * in the haproxy configuration file, and an LUA function.
9235 */
9236__LJMP static int hlua_register_action(lua_State *L)
9237{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009238 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009239 const char *name;
9240 int ref;
9241 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009242 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009243 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009244 struct buffer *trash;
9245 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009246
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009247 /* Initialise the number of expected arguments at 0. */
9248 nargs = 0;
9249
9250 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9251 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009252
9253 /* First argument : converter name. */
9254 name = MAY_LJMP(luaL_checkstring(L, 1));
9255
9256 /* Second argument : environment. */
9257 if (lua_type(L, 2) != LUA_TTABLE)
9258 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9259
9260 /* Third argument : lua function. */
9261 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9262
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009263 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009264 if (lua_gettop(L) >= 4)
9265 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9266
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009267 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009268 lua_pushnil(L);
9269 while (lua_next(L, 2) != 0) {
9270 if (lua_type(L, -1) != LUA_TSTRING)
9271 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9272
Thierry Fournierf67442e2020-11-28 20:41:07 +01009273 /* Check if action exists */
9274 trash = get_trash_chunk();
9275 chunk_printf(trash, "lua.%s", name);
9276 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9277 akw = tcp_req_cont_action(trash->area);
9278 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9279 akw = tcp_res_cont_action(trash->area);
9280 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9281 akw = action_http_req_custom(trash->area);
9282 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9283 akw = action_http_res_custom(trash->area);
9284 } else {
9285 akw = NULL;
9286 }
9287 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009288 fcn = akw->private;
9289 if (fcn->function_ref[hlua_state_id] != -1) {
9290 ha_warning("Trying to register action 'lua.%s' more than once. "
9291 "This will become a hard error in version 2.5.\n", name);
9292 }
9293 fcn->function_ref[hlua_state_id] = ref;
9294
9295 /* pop the environment string. */
9296 lua_pop(L, 1);
9297 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009298 }
9299
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009300 /* Check required environment. Only accepted "http" or "tcp". */
9301 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009302 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009303 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009304 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009305 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009306 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009307 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009308
9309 /* Fill fcn. */
9310 fcn->name = strdup(name);
9311 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009312 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009313 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009314
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009315 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009316 fcn->nargs = nargs;
9317
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009318 /* List head */
9319 akl->list.n = akl->list.p = NULL;
9320
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009321 /* action keyword. */
9322 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009323 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009324 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009325 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009326
9327 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9328
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009329 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009330 akl->kw[0].private = fcn;
9331 akl->kw[0].parse = action_register_lua;
9332
9333 /* select the action registering point. */
9334 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9335 tcp_req_cont_keywords_register(akl);
9336 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9337 tcp_res_cont_keywords_register(akl);
9338 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9339 http_req_keywords_register(akl);
9340 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9341 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009342 else {
9343 release_hlua_function(fcn);
9344 if (akl)
9345 ha_free((char **)&(akl->kw[0].kw));
9346 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009347 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009348 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9349 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009350 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009351
9352 /* pop the environment string. */
9353 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009354
9355 /* reset for next loop */
9356 akl = NULL;
9357 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009358 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009359 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009360
9361 alloc_error:
9362 release_hlua_function(fcn);
9363 ha_free(&akl);
9364 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9365 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009366}
9367
9368static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9369 struct act_rule *rule, char **err)
9370{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009371 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009372
Christopher Faulet280f85b2019-07-15 15:02:04 +02009373 if (px->mode == PR_MODE_HTTP) {
9374 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009375 return ACT_RET_PRS_ERR;
9376 }
9377
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009378 /* Memory for the rule. */
9379 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9380 if (!rule->arg.hlua_rule) {
9381 memprintf(err, "out of memory error");
9382 return ACT_RET_PRS_ERR;
9383 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009384
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009385 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009386 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009387
9388 /* TODO: later accept arguments. */
9389 rule->arg.hlua_rule->args = NULL;
9390
9391 /* Add applet pointer in the rule. */
9392 rule->applet.obj_type = OBJ_TYPE_APPLET;
9393 rule->applet.name = fcn->name;
9394 rule->applet.init = hlua_applet_tcp_init;
9395 rule->applet.fct = hlua_applet_tcp_fct;
9396 rule->applet.release = hlua_applet_tcp_release;
9397 rule->applet.timeout = hlua_timeout_applet;
9398
9399 return 0;
9400}
9401
9402/* This function is an LUA binding used for registering
9403 * "sample-conv" functions. It expects a converter name used
9404 * in the haproxy configuration file, and an LUA function.
9405 */
9406__LJMP static int hlua_register_service(lua_State *L)
9407{
9408 struct action_kw_list *akl;
9409 const char *name;
9410 const char *env;
9411 int ref;
9412 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009413 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009414 struct buffer *trash;
9415 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009416
9417 MAY_LJMP(check_args(L, 3, "register_service"));
9418
9419 /* First argument : converter name. */
9420 name = MAY_LJMP(luaL_checkstring(L, 1));
9421
9422 /* Second argument : environment. */
9423 env = MAY_LJMP(luaL_checkstring(L, 2));
9424
9425 /* Third argument : lua function. */
9426 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9427
Thierry Fournierf67442e2020-11-28 20:41:07 +01009428 /* Check for service already registered */
9429 trash = get_trash_chunk();
9430 chunk_printf(trash, "lua.%s", name);
9431 akw = service_find(trash->area);
9432 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009433 fcn = akw->private;
9434 if (fcn->function_ref[hlua_state_id] != -1) {
9435 ha_warning("Trying to register service 'lua.%s' more than once. "
9436 "This will become a hard error in version 2.5.\n", name);
9437 }
9438 fcn->function_ref[hlua_state_id] = ref;
9439 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009440 }
9441
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009442 /* Allocate and fill the sample fetch keyword struct. */
9443 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9444 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009445 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009446 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009447 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009448 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009449
9450 /* Fill fcn. */
9451 len = strlen("<lua.>") + strlen(name) + 1;
9452 fcn->name = calloc(1, len);
9453 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009454 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009455 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009456 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009457
9458 /* List head */
9459 akl->list.n = akl->list.p = NULL;
9460
9461 /* converter keyword. */
9462 len = strlen("lua.") + strlen(name) + 1;
9463 akl->kw[0].kw = calloc(1, len);
9464 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009465 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009466
9467 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9468
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009469 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009470 if (strcmp(env, "tcp") == 0)
9471 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009472 else if (strcmp(env, "http") == 0)
9473 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009474 else {
9475 release_hlua_function(fcn);
9476 if (akl)
9477 ha_free((char **)&(akl->kw[0].kw));
9478 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009479 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009480 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009481 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009482
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009483 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009484 akl->kw[0].private = fcn;
9485
9486 /* End of array. */
9487 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9488
9489 /* Register this new converter */
9490 service_keywords_register(akl);
9491
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009492 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009493
9494 alloc_error:
9495 release_hlua_function(fcn);
9496 ha_free(&akl);
9497 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9498 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009499}
9500
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009501/* This function initialises Lua cli handler. It copies the
9502 * arguments in the Lua stack and create channel IO objects.
9503 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02009504static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009505{
9506 struct hlua *hlua;
9507 struct hlua_function *fcn;
9508 int i;
9509 const char *error;
9510
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009511 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009512 appctx->ctx.hlua_cli.fcn = private;
9513
Willy Tarreaubafbe012017-11-24 17:34:44 +01009514 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009515 if (!hlua) {
9516 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009517 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009518 }
9519 HLUA_INIT(hlua);
9520 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009521
9522 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05009523 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009524 * applet_http. It is absolutely compatible.
9525 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01009526 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009527 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01009528 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009529 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009530 }
9531 appctx->ctx.hlua_cli.task->nice = 0;
9532 appctx->ctx.hlua_cli.task->context = appctx;
9533 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
9534
9535 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +01009536 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 +01009537 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009538 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009539 }
9540
9541 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009542 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009543 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9544 error = lua_tostring(hlua->T, -1);
9545 else
9546 error = "critical error";
9547 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
9548 goto error;
9549 }
9550
9551 /* Check stack available size. */
9552 if (!lua_checkstack(hlua->T, 2)) {
9553 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9554 goto error;
9555 }
9556
9557 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009558 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009559
9560 /* Once the arguments parsed, the CLI is like an AppletTCP,
9561 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009562 */
9563 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
9564 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9565 goto error;
9566 }
9567 hlua->nargs = 1;
9568
9569 /* push keywords in the stack. */
9570 for (i = 0; *args[i]; i++) {
9571 /* Check stack available size. */
9572 if (!lua_checkstack(hlua->T, 1)) {
9573 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9574 goto error;
9575 }
9576 lua_pushstring(hlua->T, args[i]);
9577 hlua->nargs++;
9578 }
9579
9580 /* We must initialize the execution timeouts. */
9581 hlua->max_time = hlua_timeout_session;
9582
9583 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009584 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009585
9586 /* It's ok */
9587 return 0;
9588
9589 /* It's not ok. */
9590error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009591 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009592 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009593 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009594 return 1;
9595}
9596
9597static int hlua_cli_io_handler_fct(struct appctx *appctx)
9598{
9599 struct hlua *hlua;
9600 struct stream_interface *si;
9601 struct hlua_function *fcn;
9602
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009603 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009604 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01009605 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009606
9607 /* If the stream is disconnect or closed, ldo nothing. */
9608 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9609 return 1;
9610
9611 /* Execute the function. */
9612 switch (hlua_ctx_resume(hlua, 1)) {
9613
9614 /* finished. */
9615 case HLUA_E_OK:
9616 return 1;
9617
9618 /* yield. */
9619 case HLUA_E_AGAIN:
9620 /* We want write. */
9621 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01009622 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009623 /* Set the timeout. */
9624 if (hlua->wake_time != TICK_ETERNITY)
9625 task_schedule(hlua->task, hlua->wake_time);
9626 return 0;
9627
9628 /* finished with error. */
9629 case HLUA_E_ERRMSG:
9630 /* Display log. */
9631 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
9632 fcn->name, lua_tostring(hlua->T, -1));
9633 lua_pop(hlua->T, 1);
9634 return 1;
9635
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009636 case HLUA_E_ETMOUT:
9637 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
9638 fcn->name);
9639 return 1;
9640
9641 case HLUA_E_NOMEM:
9642 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
9643 fcn->name);
9644 return 1;
9645
9646 case HLUA_E_YIELD: /* unexpected */
9647 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
9648 fcn->name);
9649 return 1;
9650
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009651 case HLUA_E_ERR:
9652 /* Display log. */
9653 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
9654 fcn->name);
9655 return 1;
9656
9657 default:
9658 return 1;
9659 }
9660
9661 return 1;
9662}
9663
9664static void hlua_cli_io_release_fct(struct appctx *appctx)
9665{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009666 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009667 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009668}
9669
9670/* This function is an LUA binding used for registering
9671 * new keywords in the cli. It expects a list of keywords
9672 * which are the "path". It is limited to 5 keywords. A
9673 * description of the command, a function to be executed
9674 * for the parsing and a function for io handlers.
9675 */
9676__LJMP static int hlua_register_cli(lua_State *L)
9677{
9678 struct cli_kw_list *cli_kws;
9679 const char *message;
9680 int ref_io;
9681 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009682 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009683 int index;
9684 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009685 struct buffer *trash;
9686 const char *kw[5];
9687 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009688 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009689
9690 MAY_LJMP(check_args(L, 3, "register_cli"));
9691
9692 /* First argument : an array of maximum 5 keywords. */
9693 if (!lua_istable(L, 1))
9694 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
9695
9696 /* Second argument : string with contextual message. */
9697 message = MAY_LJMP(luaL_checkstring(L, 2));
9698
9699 /* Third and fourth argument : lua function. */
9700 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
9701
Thierry Fournierf67442e2020-11-28 20:41:07 +01009702 /* Check for CLI service already registered */
9703 trash = get_trash_chunk();
9704 index = 0;
9705 lua_pushnil(L);
9706 memset(kw, 0, sizeof(kw));
9707 while (lua_next(L, 1) != 0) {
9708 if (index >= CLI_PREFIX_KW_NB)
9709 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
9710 if (lua_type(L, -1) != LUA_TSTRING)
9711 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
9712 kw[index] = lua_tostring(L, -1);
9713 if (index == 0)
9714 chunk_printf(trash, "%s", kw[index]);
9715 else
9716 chunk_appendf(trash, " %s", kw[index]);
9717 index++;
9718 lua_pop(L, 1);
9719 }
9720 cli_kw = cli_find_kw_exact((char **)kw);
9721 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009722 fcn = cli_kw->private;
9723 if (fcn->function_ref[hlua_state_id] != -1) {
9724 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
9725 "This will become a hard error in version 2.5.\n", trash->area);
9726 }
9727 fcn->function_ref[hlua_state_id] = ref_io;
9728 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009729 }
9730
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009731 /* Allocate and fill the sample fetch keyword struct. */
9732 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009733 if (!cli_kws) {
9734 errmsg = "Lua out of memory error.";
9735 goto error;
9736 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009737 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009738 if (!fcn) {
9739 errmsg = "Lua out of memory error.";
9740 goto error;
9741 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009742
9743 /* Fill path. */
9744 index = 0;
9745 lua_pushnil(L);
9746 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009747 if (index >= 5) {
9748 errmsg = "1st argument must be a table with a maximum of 5 entries";
9749 goto error;
9750 }
9751 if (lua_type(L, -1) != LUA_TSTRING) {
9752 errmsg = "1st argument must be a table filled with strings";
9753 goto error;
9754 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009755 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009756 if (!cli_kws->kw[0].str_kw[index]) {
9757 errmsg = "Lua out of memory error.";
9758 goto error;
9759 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009760 index++;
9761 lua_pop(L, 1);
9762 }
9763
9764 /* Copy help message. */
9765 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009766 if (!cli_kws->kw[0].usage) {
9767 errmsg = "Lua out of memory error.";
9768 goto error;
9769 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009770
9771 /* Fill fcn io handler. */
9772 len = strlen("<lua.cli>") + 1;
9773 for (i = 0; i < index; i++)
9774 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
9775 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009776 if (!fcn->name) {
9777 errmsg = "Lua out of memory error.";
9778 goto error;
9779 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009780 strncat((char *)fcn->name, "<lua.cli", len);
9781 for (i = 0; i < index; i++) {
9782 strncat((char *)fcn->name, ".", len);
9783 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
9784 }
9785 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +01009786 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009787
9788 /* Fill last entries. */
9789 cli_kws->kw[0].private = fcn;
9790 cli_kws->kw[0].parse = hlua_cli_parse_fct;
9791 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
9792 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
9793
9794 /* Register this new converter */
9795 cli_register_kw(cli_kws);
9796
9797 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009798
9799 error:
9800 release_hlua_function(fcn);
9801 if (cli_kws) {
9802 for (i = 0; i < index; i++)
9803 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
9804 ha_free((char **)&(cli_kws->kw[0].usage));
9805 }
9806 ha_free(&cli_kws);
9807 WILL_LJMP(luaL_error(L, errmsg));
9808 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009809}
9810
Christopher Faulet69c581a2021-05-31 08:54:04 +02009811static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
9812{
9813 struct hlua_flt_config *conf = fconf->conf;
9814 lua_State *L;
9815 int error, pos, state_id, flt_ref;
9816
9817 state_id = reg_flt_to_stack_id(conf->reg);
9818 L = hlua_states[state_id];
9819 pos = lua_gettop(L);
9820
9821 /* The filter parsing function */
9822 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
9823
9824 /* Push the filter class on the stack and resolve all callbacks */
9825 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
9826
9827 /* Duplicate the filter class so each filter will have its own copy */
9828 lua_newtable(L);
9829 lua_pushnil(L);
9830
9831 while (lua_next(L, pos+2)) {
9832 lua_pushvalue(L, -2);
9833 lua_insert(L, -2);
9834 lua_settable(L, -4);
9835 }
9836 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
9837
9838 /* Remove the original lua filter class from the stack */
9839 lua_pop(L, 1);
9840
9841 /* Push the copy on the stack */
9842 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
9843
9844 /* extra args are pushed in a table */
9845 lua_newtable(L);
9846 for (pos = 0; conf->args[pos]; pos++) {
9847 /* Check stack available size. */
9848 if (!lua_checkstack(L, 1)) {
9849 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
9850 goto error;
9851 }
9852 lua_pushstring(L, conf->args[pos]);
9853 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
9854 }
9855
9856 error = lua_pcall(L, 2, LUA_MULTRET, 0);
9857 switch (error) {
9858 case LUA_OK:
9859 /* replace the filter ref */
9860 conf->ref[state_id] = flt_ref;
9861 break;
9862 case LUA_ERRRUN:
9863 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
9864 goto error;
9865 case LUA_ERRMEM:
9866 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
9867 goto error;
9868 case LUA_ERRERR:
9869 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
9870 goto error;
9871#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
9872 case LUA_ERRGCMM:
9873 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
9874 goto error;
9875#endif
9876 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05009877 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +02009878 goto error;
9879 }
9880
9881 lua_settop(L, 0);
9882 return 0;
9883
9884 error:
9885 lua_settop(L, 0);
9886 return -1;
9887}
9888
9889static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
9890{
9891 struct hlua_flt_config *conf = fconf->conf;
9892 lua_State *L;
9893 int state_id;
9894
9895 if (!conf)
9896 return;
9897
9898 state_id = reg_flt_to_stack_id(conf->reg);
9899 L = hlua_states[state_id];
9900 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
9901}
9902
9903static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
9904{
9905 struct hlua_flt_config *conf = fconf->conf;
9906 int state_id = reg_flt_to_stack_id(conf->reg);
9907
9908 /* Rely on per-thread init for global scripts */
9909 if (!state_id)
9910 return hlua_filter_init_per_thread(px, fconf);
9911 return 0;
9912}
9913
9914static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
9915{
9916
9917 if (fconf->conf) {
9918 struct hlua_flt_config *conf = fconf->conf;
9919 int state_id = reg_flt_to_stack_id(conf->reg);
9920 int pos;
9921
9922 /* Rely on per-thread deinit for global scripts */
9923 if (!state_id)
9924 hlua_filter_deinit_per_thread(px, fconf);
9925
9926 for (pos = 0; conf->args[pos]; pos++)
9927 free(conf->args[pos]);
9928 free(conf->args);
9929 }
9930 ha_free(&fconf->conf);
9931 ha_free((char **)&fconf->id);
9932 ha_free(&fconf->ops);
9933}
9934
9935static int hlua_filter_new(struct stream *s, struct filter *filter)
9936{
9937 struct hlua_flt_config *conf = FLT_CONF(filter);
9938 struct hlua_flt_ctx *flt_ctx = NULL;
9939 int ret = 1;
9940
9941 /* In the execution wrappers linked with a stream, the
9942 * Lua context can be not initialized. This behavior
9943 * permits to save performances because a systematic
9944 * Lua initialization cause 5% performances loss.
9945 */
9946 if (!s->hlua) {
9947 struct hlua *hlua;
9948
9949 hlua = pool_alloc(pool_head_hlua);
9950 if (!hlua) {
9951 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9952 conf->reg->name);
9953 ret = 0;
9954 goto end;
9955 }
9956 HLUA_INIT(hlua);
9957 s->hlua = hlua;
9958 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9959 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9960 conf->reg->name);
9961 ret = 0;
9962 goto end;
9963 }
9964 }
9965
9966 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
9967 if (!flt_ctx) {
9968 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9969 conf->reg->name);
9970 ret = 0;
9971 goto end;
9972 }
9973 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
9974 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
9975 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
9976 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9977 conf->reg->name);
9978 ret = 0;
9979 goto end;
9980 }
9981 HLUA_INIT(flt_ctx->hlua[0]);
9982 HLUA_INIT(flt_ctx->hlua[1]);
9983 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
9984 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9985 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9986 conf->reg->name);
9987 ret = 0;
9988 goto end;
9989 }
9990
9991 if (!HLUA_IS_RUNNING(s->hlua)) {
9992 /* The following Lua calls can fail. */
9993 if (!SET_SAFE_LJMP(s->hlua)) {
9994 const char *error;
9995
9996 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9997 error = lua_tostring(s->hlua->T, -1);
9998 else
9999 error = "critical error";
10000 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10001 ret = 0;
10002 goto end;
10003 }
10004
10005 /* Check stack size. */
10006 if (!lua_checkstack(s->hlua->T, 1)) {
10007 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10008 ret = 0;
10009 goto end;
10010 }
10011
10012 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10013 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10014 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10015 conf->reg->name);
10016 RESET_SAFE_LJMP(s->hlua);
10017 ret = 0;
10018 goto end;
10019 }
10020 lua_insert(s->hlua->T, -2);
10021
10022 /* Push the copy on the stack */
10023 s->hlua->nargs = 1;
10024
10025 /* We must initialize the execution timeouts. */
10026 s->hlua->max_time = hlua_timeout_session;
10027
10028 /* At this point the execution is safe. */
10029 RESET_SAFE_LJMP(s->hlua);
10030 }
10031
10032 switch (hlua_ctx_resume(s->hlua, 0)) {
10033 case HLUA_E_OK:
10034 /* Nothing returned or not a table, ignore the filter for current stream */
10035 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10036 ret = 0;
10037 goto end;
10038 }
10039
10040 /* Attached the filter pointer to the ctx */
10041 lua_pushstring(s->hlua->T, "__filter");
10042 lua_pushlightuserdata(s->hlua->T, filter);
10043 lua_settable(s->hlua->T, -3);
10044
10045 /* Save a ref on the filter ctx */
10046 lua_pushvalue(s->hlua->T, 1);
10047 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10048 filter->ctx = flt_ctx;
10049 break;
10050 case HLUA_E_ERRMSG:
10051 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10052 ret = -1;
10053 goto end;
10054 case HLUA_E_ETMOUT:
10055 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10056 ret = 0;
10057 goto end;
10058 case HLUA_E_NOMEM:
10059 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10060 ret = 0;
10061 goto end;
10062 case HLUA_E_AGAIN:
10063 case HLUA_E_YIELD:
10064 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10065 " are not allowed from 'new' function.\n", conf->reg->name);
10066 ret = 0;
10067 goto end;
10068 case HLUA_E_ERR:
10069 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10070 ret = 0;
10071 goto end;
10072 default:
10073 ret = 0;
10074 goto end;
10075 }
10076
10077 end:
10078 if (s->hlua)
10079 lua_settop(s->hlua->T, 0);
10080 if (ret <= 0) {
10081 if (flt_ctx) {
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 }
10086 }
10087 return ret;
10088}
10089
10090static void hlua_filter_delete(struct stream *s, struct filter *filter)
10091{
10092 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10093
10094 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10095 hlua_ctx_destroy(flt_ctx->hlua[0]);
10096 hlua_ctx_destroy(flt_ctx->hlua[1]);
10097 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10098 filter->ctx = NULL;
10099}
10100
Christopher Faulet9f55a502020-02-25 15:21:02 +010010101static int hlua_filter_from_payload(struct filter *filter)
10102{
10103 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10104
10105 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10106}
10107
Christopher Fauletc404f112020-02-26 15:03:09 +010010108static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10109 int dir, unsigned int flags)
10110{
10111 struct hlua *flt_hlua;
10112 struct hlua_flt_config *conf = FLT_CONF(filter);
10113 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10114 unsigned int hflags = HLUA_TXN_FLT_CTX;
10115 int ret = 1;
10116
10117 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10118 if (!flt_hlua)
10119 goto end;
10120
10121 if (!HLUA_IS_RUNNING(flt_hlua)) {
10122 int extra_idx = lua_gettop(flt_hlua->T);
10123
10124 /* The following Lua calls can fail. */
10125 if (!SET_SAFE_LJMP(flt_hlua)) {
10126 const char *error;
10127
10128 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10129 error = lua_tostring(flt_hlua->T, -1);
10130 else
10131 error = "critical error";
10132 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10133 goto end;
10134 }
10135
10136 /* Check stack size. */
10137 if (!lua_checkstack(flt_hlua->T, 3)) {
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
10143 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10144 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10145 RESET_SAFE_LJMP(flt_hlua);
10146 goto end;
10147 }
10148 lua_insert(flt_hlua->T, -2);
10149
10150 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10151 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10152 RESET_SAFE_LJMP(flt_hlua);
10153 goto end;
10154 }
10155 flt_hlua->nargs = 2;
10156
10157 if (flags & HLUA_FLT_CB_ARG_CHN) {
10158 if (dir == SMP_OPT_DIR_REQ)
10159 lua_getfield(flt_hlua->T, -1, "req");
10160 else
10161 lua_getfield(flt_hlua->T, -1, "res");
10162 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10163 lua_pushstring(flt_hlua->T, "__filter");
10164 lua_pushlightuserdata(flt_hlua->T, filter);
10165 lua_settable(flt_hlua->T, -3);
10166 }
10167 flt_hlua->nargs++;
10168 }
10169 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010170 if (dir == SMP_OPT_DIR_REQ)
10171 lua_getfield(flt_hlua->T, -1, "http_req");
10172 else
10173 lua_getfield(flt_hlua->T, -1, "http_res");
10174 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10175 lua_pushstring(flt_hlua->T, "__filter");
10176 lua_pushlightuserdata(flt_hlua->T, filter);
10177 lua_settable(flt_hlua->T, -3);
10178 }
10179 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010180 }
10181
10182 /* Check stack size. */
10183 if (!lua_checkstack(flt_hlua->T, 1)) {
10184 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10185 RESET_SAFE_LJMP(flt_hlua);
10186 goto end;
10187 }
10188
10189 while (extra_idx--) {
10190 lua_pushvalue(flt_hlua->T, 1);
10191 lua_remove(flt_hlua->T, 1);
10192 flt_hlua->nargs++;
10193 }
10194
10195 /* We must initialize the execution timeouts. */
10196 flt_hlua->max_time = hlua_timeout_session;
10197
10198 /* At this point the execution is safe. */
10199 RESET_SAFE_LJMP(flt_hlua);
10200 }
10201
10202 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10203 case HLUA_E_OK:
10204 /* Catch the return value if it required */
10205 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10206 ret = lua_tointeger(flt_hlua->T, -1);
10207 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10208 }
10209
10210 /* Set timeout in the required channel. */
10211 if (flt_hlua->wake_time != TICK_ETERNITY) {
10212 if (dir == SMP_OPT_DIR_REQ)
10213 s->req.analyse_exp = flt_hlua->wake_time;
10214 else
10215 s->res.analyse_exp = flt_hlua->wake_time;
10216 }
10217 break;
10218 case HLUA_E_AGAIN:
10219 /* Set timeout in the required channel. */
10220 if (flt_hlua->wake_time != TICK_ETERNITY) {
10221 if (dir == SMP_OPT_DIR_REQ)
10222 s->req.analyse_exp = flt_hlua->wake_time;
10223 else
10224 s->res.analyse_exp = flt_hlua->wake_time;
10225 }
10226 /* Some actions can be wake up when a "write" event
10227 * is detected on a response channel. This is useful
10228 * only for actions targeted on the requests.
10229 */
10230 if (HLUA_IS_WAKERESWR(flt_hlua))
10231 s->res.flags |= CF_WAKE_WRITE;
10232 if (HLUA_IS_WAKEREQWR(flt_hlua))
10233 s->req.flags |= CF_WAKE_WRITE;
10234 ret = 0;
10235 goto end;
10236 case HLUA_E_ERRMSG:
10237 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10238 ret = -1;
10239 goto end;
10240 case HLUA_E_ETMOUT:
10241 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10242 goto end;
10243 case HLUA_E_NOMEM:
10244 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10245 goto end;
10246 case HLUA_E_YIELD:
10247 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10248 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10249 goto end;
10250 case HLUA_E_ERR:
10251 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10252 goto end;
10253 default:
10254 goto end;
10255 }
10256
10257
10258 end:
10259 return ret;
10260}
10261
10262static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10263{
10264 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10265
10266 flt_ctx->flags = 0;
10267 return hlua_filter_callback(s, filter, "start_analyze",
10268 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10269 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10270}
10271
10272static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10273{
10274 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10275
10276 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10277 return hlua_filter_callback(s, filter, "end_analyze",
10278 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10279 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10280}
10281
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010282static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10283{
10284 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10285
10286 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10287 return hlua_filter_callback(s, filter, "http_headers",
10288 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10289 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10290}
10291
10292static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10293 unsigned int offset, unsigned int len)
10294{
10295 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10296 struct hlua *flt_hlua;
10297 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10298 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10299 int ret;
10300
10301 flt_hlua = flt_ctx->hlua[idx];
10302 flt_ctx->cur_off[idx] = offset;
10303 flt_ctx->cur_len[idx] = len;
10304 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10305 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10306 if (ret != -1) {
10307 ret = flt_ctx->cur_len[idx];
10308 if (lua_gettop(flt_hlua->T) > 0) {
10309 ret = lua_tointeger(flt_hlua->T, -1);
10310 if (ret > flt_ctx->cur_len[idx])
10311 ret = flt_ctx->cur_len[idx];
10312 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10313 }
10314 }
10315 return ret;
10316}
10317
10318static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10319{
10320 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10321
10322 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10323 return hlua_filter_callback(s, filter, "http_end",
10324 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10325 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10326}
10327
Christopher Fauletc404f112020-02-26 15:03:09 +010010328static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10329 unsigned int offset, unsigned int len)
10330{
10331 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10332 struct hlua *flt_hlua;
10333 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10334 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10335 int ret;
10336
10337 flt_hlua = flt_ctx->hlua[idx];
10338 flt_ctx->cur_off[idx] = offset;
10339 flt_ctx->cur_len[idx] = len;
10340 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10341 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10342 if (ret != -1) {
10343 ret = flt_ctx->cur_len[idx];
10344 if (lua_gettop(flt_hlua->T) > 0) {
10345 ret = lua_tointeger(flt_hlua->T, -1);
10346 if (ret > flt_ctx->cur_len[idx])
10347 ret = flt_ctx->cur_len[idx];
10348 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10349 }
10350 }
10351 return ret;
10352}
10353
Christopher Faulet69c581a2021-05-31 08:54:04 +020010354static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10355 struct flt_conf *fconf, char **err, void *private)
10356{
10357 struct hlua_reg_filter *reg_flt = private;
10358 lua_State *L;
10359 struct hlua_flt_config *conf = NULL;
10360 const char *flt_id = NULL;
10361 int state_id, pos, flt_flags = 0;
10362 struct flt_ops *hlua_flt_ops = NULL;
10363
10364 state_id = reg_flt_to_stack_id(reg_flt);
10365 L = hlua_states[state_id];
10366
10367 /* Initialize the filter ops with default callbacks */
10368 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010369 if (!hlua_flt_ops)
10370 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010371 hlua_flt_ops->init = hlua_filter_init;
10372 hlua_flt_ops->deinit = hlua_filter_deinit;
10373 if (state_id) {
10374 /* Set per-thread callback if script is loaded per-thread */
10375 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10376 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10377 }
10378 hlua_flt_ops->attach = hlua_filter_new;
10379 hlua_flt_ops->detach = hlua_filter_delete;
10380
10381 /* Push the filter class on the stack and resolve all callbacks */
10382 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10383
Christopher Fauletc404f112020-02-26 15:03:09 +010010384 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10385 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10386 lua_pop(L, 1);
10387 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10388 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10389 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010390 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10391 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10392 lua_pop(L, 1);
10393 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10394 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10395 lua_pop(L, 1);
10396 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10397 hlua_flt_ops->http_end = hlua_filter_http_end;
10398 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010399 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10400 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10401 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010402
10403 /* Get id and flags of the filter class */
10404 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10405 flt_id = lua_tostring(L, -1);
10406 lua_pop(L, 1);
10407 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10408 flt_flags = lua_tointeger(L, -1);
10409 lua_pop(L, 1);
10410
10411 /* Create the filter config */
10412 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010413 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010414 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010415 conf->reg = reg_flt;
10416
10417 /* duplicate args */
10418 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10419 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010420 if (!conf->args)
10421 goto error;
10422 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010423 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010424 if (!conf->args[pos])
10425 goto error;
10426 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010427 conf->args[pos] = NULL;
10428 *cur_arg += pos + 1;
10429
Christopher Fauletc86bb872021-08-13 08:33:57 +020010430 if (flt_id) {
10431 fconf->id = strdup(flt_id);
10432 if (!fconf->id)
10433 goto error;
10434 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010435 fconf->flags = flt_flags;
10436 fconf->conf = conf;
10437 fconf->ops = hlua_flt_ops;
10438
10439 lua_settop(L, 0);
10440 return 0;
10441
10442 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010443 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010444 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010445 if (conf && conf->args) {
10446 for (pos = 0; conf->args[pos]; pos++)
10447 free(conf->args[pos]);
10448 free(conf->args);
10449 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010450 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010451 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010452 lua_settop(L, 0);
10453 return -1;
10454}
10455
Christopher Fauletc404f112020-02-26 15:03:09 +010010456__LJMP static int hlua_register_data_filter(lua_State *L)
10457{
10458 struct filter *filter;
10459 struct channel *chn;
10460
10461 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10462 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10463 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10464
10465 lua_getfield(L, 1, "__filter");
10466 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10467 filter = lua_touserdata (L, -1);
10468 lua_pop(L, 1);
10469
10470 register_data_filter(chn_strm(chn), chn, filter);
10471 return 1;
10472}
10473
10474__LJMP static int hlua_unregister_data_filter(lua_State *L)
10475{
10476 struct filter *filter;
10477 struct channel *chn;
10478
10479 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10480 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10481 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10482
10483 lua_getfield(L, 1, "__filter");
10484 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10485 filter = lua_touserdata (L, -1);
10486 lua_pop(L, 1);
10487
10488 unregister_data_filter(chn_strm(chn), chn, filter);
10489 return 1;
10490}
10491
Christopher Faulet69c581a2021-05-31 08:54:04 +020010492/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010493 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020010494 * parse configuration arguments.
10495 */
10496__LJMP static int hlua_register_filter(lua_State *L)
10497{
10498 struct buffer *trash;
10499 struct flt_kw_list *fkl;
10500 struct flt_kw *fkw;
10501 const char *name;
10502 struct hlua_reg_filter *reg_flt= NULL;
10503 int flt_ref, fun_ref;
10504 int len;
10505
10506 MAY_LJMP(check_args(L, 3, "register_filter"));
10507
10508 /* First argument : filter name. */
10509 name = MAY_LJMP(luaL_checkstring(L, 1));
10510
10511 /* Second argument : The filter class */
10512 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
10513
10514 /* Third argument : lua function. */
10515 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
10516
10517 trash = get_trash_chunk();
10518 chunk_printf(trash, "lua.%s", name);
10519 fkw = flt_find_kw(trash->area);
10520 if (fkw != NULL) {
10521 reg_flt = fkw->private;
10522 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
10523 ha_warning("Trying to register filter 'lua.%s' more than once. "
10524 "This will become a hard error in version 2.5.\n", name);
10525 }
10526 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10527 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10528 return 0;
10529 }
10530
10531 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
10532 if (!fkl)
10533 goto alloc_error;
10534 fkl->scope = "HLUA";
10535
10536 reg_flt = new_hlua_reg_filter(name);
10537 if (!reg_flt)
10538 goto alloc_error;
10539
10540 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10541 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10542
10543 /* The filter keyword */
10544 len = strlen("lua.") + strlen(name) + 1;
10545 fkl->kw[0].kw = calloc(1, len);
10546 if (!fkl->kw[0].kw)
10547 goto alloc_error;
10548
10549 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
10550
10551 fkl->kw[0].parse = hlua_filter_parse_fct;
10552 fkl->kw[0].private = reg_flt;
10553 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
10554
10555 /* Register this new filter */
10556 flt_register_keywords(fkl);
10557
10558 return 0;
10559
10560 alloc_error:
10561 release_hlua_reg_filter(reg_flt);
10562 ha_free(&fkl);
10563 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10564 return 0; /* Never reached */
10565}
10566
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010567static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010568 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010569 char **err, unsigned int *timeout)
10570{
10571 const char *error;
10572
10573 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020010574 if (error == PARSE_TIME_OVER) {
10575 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
10576 args[1], args[0]);
10577 return -1;
10578 }
10579 else if (error == PARSE_TIME_UNDER) {
10580 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
10581 args[1], args[0]);
10582 return -1;
10583 }
10584 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010585 memprintf(err, "%s: invalid timeout", args[0]);
10586 return -1;
10587 }
10588 return 0;
10589}
10590
10591static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010592 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010593 char **err)
10594{
10595 return hlua_read_timeout(args, section_type, curpx, defpx,
10596 file, line, err, &hlua_timeout_session);
10597}
10598
10599static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010600 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010601 char **err)
10602{
10603 return hlua_read_timeout(args, section_type, curpx, defpx,
10604 file, line, err, &hlua_timeout_task);
10605}
10606
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010607static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010608 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010609 char **err)
10610{
10611 return hlua_read_timeout(args, section_type, curpx, defpx,
10612 file, line, err, &hlua_timeout_applet);
10613}
10614
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010615static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010616 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010617 char **err)
10618{
10619 char *error;
10620
10621 hlua_nb_instruction = strtoll(args[1], &error, 10);
10622 if (*error != '\0') {
10623 memprintf(err, "%s: invalid number", args[0]);
10624 return -1;
10625 }
10626 return 0;
10627}
10628
Willy Tarreau32f61e22015-03-18 17:54:59 +010010629static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010630 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010010631 char **err)
10632{
10633 char *error;
10634
10635 if (*(args[1]) == 0) {
10636 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
10637 return -1;
10638 }
10639 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
10640 if (*error != '\0') {
10641 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
10642 return -1;
10643 }
10644 return 0;
10645}
10646
10647
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010648/* This function is called by the main configuration key "lua-load". It loads and
10649 * execute an lua file during the parsing of the HAProxy configuration file. It is
10650 * the main lua entry point.
10651 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010652 * This function runs with the HAProxy keywords API. It returns -1 if an error
10653 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010654 *
10655 * In some error case, LUA set an error message in top of the stack. This function
10656 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010657 *
10658 * This function can fail with an abort() due to an Lua critical error.
10659 * We are in the configuration parsing process of HAProxy, this abort() is
10660 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010661 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010662static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010663{
10664 int error;
10665
10666 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010667 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010668 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010669 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
10670 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010671 return -1;
10672 }
10673
10674 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010675 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010676 switch (error) {
10677 case LUA_OK:
10678 break;
10679 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010680 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
10681 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010682 return -1;
10683 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010010684 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010685 return -1;
10686 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010687 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
10688 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010689 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010690#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010691 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010692 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
10693 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010694 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010695#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010696 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010697 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
10698 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010699 return -1;
10700 }
10701
10702 return 0;
10703}
10704
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010705static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010706 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010707 char **err)
10708{
10709 if (*(args[1]) == 0) {
10710 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
10711 return -1;
10712 }
10713
Thierry Fournier59f11be2020-11-29 00:37:41 +010010714 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010010715 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010716 ha_set_tid(0);
Thierry Fournierafc63e22020-11-28 17:06:51 +010010717 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010718}
10719
Thierry Fournier59f11be2020-11-29 00:37:41 +010010720static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010721 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010010722 char **err)
10723{
10724 int len;
10725
10726 if (*(args[1]) == 0) {
10727 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
10728 return -1;
10729 }
10730
10731 if (per_thread_load == NULL) {
10732 /* allocate the first entry large enough to store the final NULL */
10733 per_thread_load = calloc(1, sizeof(*per_thread_load));
10734 if (per_thread_load == NULL) {
10735 memprintf(err, "out of memory error");
10736 return -1;
10737 }
10738 }
10739
10740 /* count used entries */
10741 for (len = 0; per_thread_load[len] != NULL; len++)
10742 ;
10743
10744 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
10745 if (per_thread_load == NULL) {
10746 memprintf(err, "out of memory error");
10747 return -1;
10748 }
10749
10750 per_thread_load[len] = strdup(args[1]);
10751 per_thread_load[len + 1] = NULL;
10752
10753 if (per_thread_load[len] == NULL) {
10754 memprintf(err, "out of memory error");
10755 return -1;
10756 }
10757
10758 /* loading for thread 1 only */
10759 hlua_state_id = 1;
10760 ha_set_tid(0);
10761 return hlua_load_state(args[1], hlua_states[1], err);
10762}
10763
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010764/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
10765 * in the given <ctx>.
10766 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010767static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010768{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010769 lua_getglobal(L, "package"); /* push package variable */
10770 lua_pushstring(L, path); /* push given path */
10771 lua_pushstring(L, ";"); /* push semicolon */
10772 lua_getfield(L, -3, type); /* push old path */
10773 lua_concat(L, 3); /* concatenate to new path */
10774 lua_setfield(L, -2, type); /* store new path */
10775 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010776
10777 return 0;
10778}
10779
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010780static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010781 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010782 char **err)
10783{
10784 char *path;
10785 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010786 struct prepend_path *p = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010787
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010788 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010789 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010790 }
10791
10792 if (!(*args[1])) {
10793 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010794 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010795 }
10796 path = args[1];
10797
10798 if (*args[2]) {
10799 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
10800 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010801 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010802 }
10803 type = args[2];
10804 }
10805
Thierry Fournier59f11be2020-11-29 00:37:41 +010010806 p = calloc(1, sizeof(*p));
10807 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010808 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010809 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010810 }
10811 p->path = strdup(path);
10812 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010813 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010814 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010815 }
10816 p->type = strdup(type);
10817 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010818 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010819 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010820 }
Willy Tarreau2b718102021-04-21 07:32:39 +020010821 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010822
10823 hlua_prepend_path(hlua_states[0], type, path);
10824 hlua_prepend_path(hlua_states[1], type, path);
10825 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010826
10827err2:
10828 free(p->type);
10829 free(p->path);
10830err:
10831 free(p);
10832 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010833}
10834
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010835/* configuration keywords declaration */
10836static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010837 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010838 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010010839 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010840 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
10841 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020010842 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010843 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010010844 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010845 { 0, NULL, NULL },
10846}};
10847
Willy Tarreau0108d902018-11-25 19:14:37 +010010848INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
10849
Christopher Fauletafd8f102018-11-08 11:34:21 +010010850
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010851/* This function can fail with an abort() due to an Lua critical error.
10852 * We are in the initialisation process of HAProxy, this abort() is
10853 * tolerated.
10854 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010010855int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010856{
10857 struct hlua_init_function *init;
10858 const char *msg;
10859 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010010860 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010010861 const char *kind;
10862 const char *trace;
10863 int return_status = 1;
10864#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
10865 int nres;
10866#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010867
Willy Tarreaucdb53462020-12-02 12:12:00 +010010868 /* disable memory limit checks if limit is not set */
10869 if (!hlua_global_allocator.limit)
10870 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
10871
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050010872 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010010873 if (setjmp(safe_ljmp_env) != 0) {
10874 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010010875 if (lua_type(L, -1) == LUA_TSTRING)
10876 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010877 else
10878 error = "critical error";
10879 fprintf(stderr, "Lua post-init: %s.\n", error);
10880 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010010881 } else {
10882 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010883 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020010884
Thierry Fournierb8cef172020-11-28 15:37:17 +010010885 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010010886
Thierry Fournierc7492592020-11-28 23:57:24 +010010887 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010010888 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010010889
10890#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010010891 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010010892#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010010893 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010010894#endif
10895 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010896 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010010897
10898 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010010899 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010010900 break;
Thierry Fournier670db242020-11-28 10:49:59 +010010901
10902 case LUA_ERRERR:
10903 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010904 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010905 case LUA_ERRRUN:
10906 if (!kind)
10907 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010010908 msg = lua_tostring(L, -1);
10909 lua_settop(L, 0); /* Empty the stack. */
10910 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010010911 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010010912 if (msg)
10913 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
10914 else
10915 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
10916 return_status = 0;
10917 break;
10918
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010919 default:
Thierry Fournier670db242020-11-28 10:49:59 +010010920 /* Unknown error */
10921 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010922 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010923 case LUA_YIELD:
10924 /* yield is not configured at this step, this state doesn't happen */
10925 if (!kind)
10926 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070010927 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010010928 case LUA_ERRMEM:
10929 if (!kind)
10930 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010010931 lua_settop(L, 0);
10932 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010010933 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010010934 ha_alert("Lua init: %s: %s\n", kind, trace);
10935 return_status = 0;
10936 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010937 }
Thierry Fournier670db242020-11-28 10:49:59 +010010938 if (!return_status)
10939 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010940 }
Thierry Fournier3c539322020-11-28 16:05:05 +010010941
10942 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010010943 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010010944}
10945
Thierry Fournierb8cef172020-11-28 15:37:17 +010010946int hlua_post_init()
10947{
Thierry Fournier59f11be2020-11-29 00:37:41 +010010948 int ret;
10949 int i;
10950 int errors;
10951 char *err = NULL;
10952 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010953 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010954
Willy Tarreaub1310492021-08-30 09:35:18 +020010955#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010010956 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010010957 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010010958 int saved_used_backed = global.ssl_used_backend;
10959 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010010960 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010010961 global.ssl_used_backend = saved_used_backed;
10962 }
10963#endif
10964
Thierry Fournierc7492592020-11-28 23:57:24 +010010965 /* Perform post init of common thread */
10966 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010967 ha_set_tid(0);
10968 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
10969 if (ret == 0)
10970 return 0;
10971
10972 /* init remaining lua states and load files */
10973 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
10974
10975 /* set thread context */
10976 ha_set_tid(hlua_state_id - 1);
10977
10978 /* Init lua state */
10979 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
10980
10981 /* Load lua files */
10982 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
10983 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
10984 if (ret != 0) {
10985 ha_alert("Lua init: %s\n", err);
10986 return 0;
10987 }
10988 }
10989 }
10990
10991 /* Reset thread context */
10992 ha_set_tid(0);
10993
10994 /* Execute post init for all states */
10995 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
10996
10997 /* set thread context */
10998 ha_set_tid(hlua_state_id - 1);
10999
11000 /* run post init */
11001 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11002 if (ret == 0)
11003 return 0;
11004 }
11005
11006 /* Reset thread context */
11007 ha_set_tid(0);
11008
11009 /* control functions registering. Each function must have:
11010 * - only the function_ref[0] set positive and all other to -1
11011 * - only the function_ref[0] set to -1 and all other positive
11012 * This ensure a same reference is not used both in shared
11013 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011014 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011015 * complicated to found for the end user.
11016 */
11017 errors = 0;
11018 list_for_each_entry(fcn, &referenced_functions, l) {
11019 ret = 0;
11020 for (i = 1; i < global.nbthread + 1; i++) {
11021 if (fcn->function_ref[i] == -1)
11022 ret--;
11023 else
11024 ret++;
11025 }
11026 if (abs(ret) != global.nbthread) {
11027 ha_alert("Lua function '%s' is not referenced in all thread. "
11028 "Expect function in all thread or in none thread.\n", fcn->name);
11029 errors++;
11030 continue;
11031 }
11032
11033 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011034 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11035 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011036 "exclusive.\n", fcn->name);
11037 errors++;
11038 }
11039 }
11040
Christopher Faulet69c581a2021-05-31 08:54:04 +020011041 /* Do the same with registered filters */
11042 list_for_each_entry(reg_flt, &referenced_filters, l) {
11043 ret = 0;
11044 for (i = 1; i < global.nbthread + 1; i++) {
11045 if (reg_flt->flt_ref[i] == -1)
11046 ret--;
11047 else
11048 ret++;
11049 }
11050 if (abs(ret) != global.nbthread) {
11051 ha_alert("Lua filter '%s' is not referenced in all thread. "
11052 "Expect function in all thread or in none thread.\n", reg_flt->name);
11053 errors++;
11054 continue;
11055 }
11056
11057 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11058 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11059 "and per-thread Lua context (through lua-load-per-thread). these two context "
11060 "exclusive.\n", fcn->name);
11061 errors++;
11062 }
11063 }
11064
11065
Thierry Fournier59f11be2020-11-29 00:37:41 +010011066 if (errors > 0)
11067 return 0;
11068
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011069 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011070 * -1 in order to have probably a segfault if someone use it
11071 */
11072 hlua_state_id = -1;
11073
11074 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011075}
11076
Willy Tarreau32f61e22015-03-18 17:54:59 +010011077/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11078 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11079 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011080 * allocation. <nsize> is the requested new size. A new allocation is
11081 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011082 * zero. This one verifies that the limits are respected but is optimized
11083 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011084 */
11085static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11086{
11087 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011088 size_t limit, old, new;
11089
Tim Duesterhus22586522021-01-08 10:35:33 +010011090 if (unlikely(!ptr && !nsize))
11091 return NULL;
11092
Willy Tarreaucdb53462020-12-02 12:12:00 +010011093 /* a limit of ~0 means unlimited and boot complete, so there's no need
11094 * for accounting anymore.
11095 */
Christopher Fauletcc2c4f82021-03-24 14:52:24 +010011096 if (likely(~zone->limit == 0))
11097 return realloc(ptr, nsize);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011098
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011099 if (!ptr)
11100 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011101
Willy Tarreaucdb53462020-12-02 12:12:00 +010011102 /* enforce strict limits across all threads */
11103 limit = zone->limit;
11104 old = _HA_ATOMIC_LOAD(&zone->allocated);
11105 do {
11106 new = old + nsize - osize;
11107 if (unlikely(nsize && limit && new > limit))
11108 return NULL;
11109 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011110
11111 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011112
11113 if (unlikely(!ptr && nsize)) // failed
11114 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11115
11116 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011117 return ptr;
11118}
11119
Thierry Fournierecb83c22020-11-28 15:49:44 +010011120/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011121 * We are in the initialisation process of HAProxy, this abort() is
11122 * tolerated.
11123 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011124lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011125{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011126 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011127 int idx;
11128 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011129 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011130 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011131 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011132 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011133 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011134 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011135
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011136 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011137 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011138
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011139 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011140 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011141 *context = NULL;
11142
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011143 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011144 * the Lua function can fail with an abort. We are in the initialisation
11145 * process of HAProxy, this abort() is tolerated.
11146 */
11147
Thierry Fournier3c539322020-11-28 16:05:05 +010011148 /* Call post initialisation function in safe environment. */
11149 if (setjmp(safe_ljmp_env) != 0) {
11150 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011151 if (lua_type(L, -1) == LUA_TSTRING)
11152 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011153 else
11154 error_msg = "critical error";
11155 fprintf(stderr, "Lua init: %s.\n", error_msg);
11156 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011157 } else {
11158 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011159 }
11160
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011161 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011162 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011163#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11164#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11165#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011166 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011167#endif
11168#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011169 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011170#endif
11171#undef HLUA_PREPEND_PATH_TOSTRING
11172#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011173
Thierry Fournier59f11be2020-11-29 00:37:41 +010011174 /* Apply configured prepend path */
11175 list_for_each_entry(pp, &prepend_path_list, l)
11176 hlua_prepend_path(L, pp->type, pp->path);
11177
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011178 /*
11179 *
11180 * Create "core" object.
11181 *
11182 */
11183
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011184 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011185 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011186
Thierry Fournierecb83c22020-11-28 15:49:44 +010011187 /* set the thread id */
11188 hlua_class_const_int(L, "thread", thread_num);
11189
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011190 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011191 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011192 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011193
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011194 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011195 hlua_class_function(L, "register_init", hlua_register_init);
11196 hlua_class_function(L, "register_task", hlua_register_task);
11197 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11198 hlua_class_function(L, "register_converters", hlua_register_converters);
11199 hlua_class_function(L, "register_action", hlua_register_action);
11200 hlua_class_function(L, "register_service", hlua_register_service);
11201 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011202 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011203 hlua_class_function(L, "yield", hlua_yield);
11204 hlua_class_function(L, "set_nice", hlua_set_nice);
11205 hlua_class_function(L, "sleep", hlua_sleep);
11206 hlua_class_function(L, "msleep", hlua_msleep);
11207 hlua_class_function(L, "add_acl", hlua_add_acl);
11208 hlua_class_function(L, "del_acl", hlua_del_acl);
11209 hlua_class_function(L, "set_map", hlua_set_map);
11210 hlua_class_function(L, "del_map", hlua_del_map);
11211 hlua_class_function(L, "tcp", hlua_socket_new);
11212 hlua_class_function(L, "log", hlua_log);
11213 hlua_class_function(L, "Debug", hlua_log_debug);
11214 hlua_class_function(L, "Info", hlua_log_info);
11215 hlua_class_function(L, "Warning", hlua_log_warning);
11216 hlua_class_function(L, "Alert", hlua_log_alert);
11217 hlua_class_function(L, "done", hlua_done);
11218 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011219
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011220 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011221
11222 /*
11223 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011224 * Create "act" object.
11225 *
11226 */
11227
11228 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011229 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011230
11231 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011232 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11233 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11234 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11235 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11236 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11237 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11238 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11239 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011240
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011241 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011242
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011243 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011244
11245 /*
11246 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011247 * Create "Filter" object.
11248 *
11249 */
11250
11251 /* This table entry is the object "filter" base. */
11252 lua_newtable(L);
11253
11254 /* push flags and constants */
11255 hlua_class_const_int(L, "CONTINUE", 1);
11256 hlua_class_const_int(L, "WAIT", 0);
11257 hlua_class_const_int(L, "ERROR", -1);
11258
11259 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
11260
Christopher Fauletc404f112020-02-26 15:03:09 +010011261 hlua_class_function(L, "wake_time", hlua_set_wake_time);
11262 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
11263 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
11264
Christopher Faulet69c581a2021-05-31 08:54:04 +020011265 lua_setglobal(L, "filter");
11266
11267 /*
11268 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011269 * Register class Map
11270 *
11271 */
11272
11273 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011274 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011275
11276 /* register pattern types. */
11277 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011278 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011279 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011280 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011281 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011282 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011283
11284 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011285 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011286
11287 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011288 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011289
Ilya Shipitsind4259502020-04-08 01:07:56 +050011290 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011291 lua_pushstring(L, "__index");
11292 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011293
11294 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011295 hlua_class_function(L, "lookup", hlua_map_lookup);
11296 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011297
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011298 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011299
Thierry Fournier45e78d72016-02-19 18:34:46 +010011300 /* Register previous table in the registry with reference and named entry.
11301 * The function hlua_register_metatable() pops the stack, so we
11302 * previously create a copy of the table.
11303 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011304 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
11305 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011306
11307 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011308 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011309
11310 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011311 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011312
11313 /*
11314 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011315 * Register class Channel
11316 *
11317 */
11318
11319 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011320 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011321
Ilya Shipitsind4259502020-04-08 01:07:56 +050011322 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011323 lua_pushstring(L, "__index");
11324 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011325
11326 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011327 hlua_class_function(L, "data", hlua_channel_get_data);
11328 hlua_class_function(L, "line", hlua_channel_get_line);
11329 hlua_class_function(L, "set", hlua_channel_set_data);
11330 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011331 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011332 hlua_class_function(L, "prepend", hlua_channel_prepend);
11333 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011334 hlua_class_function(L, "send", hlua_channel_send);
11335 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011336 hlua_class_function(L, "input", hlua_channel_get_in_len);
11337 hlua_class_function(L, "output", hlua_channel_get_out_len);
11338 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011339 hlua_class_function(L, "is_full", hlua_channel_is_full);
11340 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011341
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011342 /* Deprecated API */
11343 hlua_class_function(L, "get", hlua_channel_get);
11344 hlua_class_function(L, "dup", hlua_channel_dup);
11345 hlua_class_function(L, "getline", hlua_channel_getline);
11346 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
11347 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
11348
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011349 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011350
11351 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011352 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011353
11354 /*
11355 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011356 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011357 *
11358 */
11359
11360 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011361 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011362
Ilya Shipitsind4259502020-04-08 01:07:56 +050011363 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011364 lua_pushstring(L, "__index");
11365 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011366
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011367 /* Browse existing fetches and create the associated
11368 * object method.
11369 */
11370 sf = NULL;
11371 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011372 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11373 * by an underscore.
11374 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011375 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011376 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011377 if (*p == '.' || *p == '-' || *p == '+')
11378 *p = '_';
11379
11380 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011381 lua_pushstring(L, trash.area);
11382 lua_pushlightuserdata(L, sf);
11383 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
11384 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011385 }
11386
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011387 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011388
11389 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011390 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011391
11392 /*
11393 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011394 * Register class Converters
11395 *
11396 */
11397
11398 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011399 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011400
11401 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011402 lua_pushstring(L, "__index");
11403 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011404
11405 /* Browse existing converters and create the associated
11406 * object method.
11407 */
11408 sc = NULL;
11409 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011410 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11411 * by an underscore.
11412 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011413 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011414 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011415 if (*p == '.' || *p == '-' || *p == '+')
11416 *p = '_';
11417
11418 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011419 lua_pushstring(L, trash.area);
11420 lua_pushlightuserdata(L, sc);
11421 lua_pushcclosure(L, hlua_run_sample_conv, 1);
11422 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011423 }
11424
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011425 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011426
11427 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011428 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011429
11430 /*
11431 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011432 * Register class HTTP
11433 *
11434 */
11435
11436 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011437 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011438
Ilya Shipitsind4259502020-04-08 01:07:56 +050011439 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011440 lua_pushstring(L, "__index");
11441 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011442
11443 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011444 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
11445 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
11446 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
11447 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
11448 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
11449 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
11450 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
11451 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
11452 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
11453 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011454
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011455 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
11456 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
11457 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
11458 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
11459 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
11460 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
11461 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011462
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011463 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011464
11465 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011466 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011467
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011468 /*
11469 *
11470 * Register class HTTPMessage
11471 *
11472 */
11473
11474 /* Create and fill the metatable. */
11475 lua_newtable(L);
11476
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011477 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011478 lua_pushstring(L, "__index");
11479 lua_newtable(L);
11480
11481 /* Register Lua functions. */
11482 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
11483 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
11484 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
11485 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
11486 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
11487 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
11488 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
11489 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
11490 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
11491 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
11492 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
11493 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
11494 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
11495 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
11496 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
11497 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
11498 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
11499 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
11500
11501 hlua_class_function(L, "body", hlua_http_msg_get_body);
11502 hlua_class_function(L, "set", hlua_http_msg_set_data);
11503 hlua_class_function(L, "remove", hlua_http_msg_del_data);
11504 hlua_class_function(L, "append", hlua_http_msg_append);
11505 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
11506 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
11507 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
11508 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
11509
11510 hlua_class_function(L, "send", hlua_http_msg_send);
11511 hlua_class_function(L, "forward", hlua_http_msg_forward);
11512
11513 lua_rawset(L, -3);
11514
11515 /* Register previous table in the registry with reference and named entry. */
11516 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011517 /*
11518 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011519 * Register class AppletTCP
11520 *
11521 */
11522
11523 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011524 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011525
Ilya Shipitsind4259502020-04-08 01:07:56 +050011526 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011527 lua_pushstring(L, "__index");
11528 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011529
11530 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011531 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
11532 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
11533 hlua_class_function(L, "send", hlua_applet_tcp_send);
11534 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
11535 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
11536 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
11537 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
11538 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011539
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011540 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011541
11542 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011543 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011544
11545 /*
11546 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011547 * Register class AppletHTTP
11548 *
11549 */
11550
11551 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011552 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011553
Ilya Shipitsind4259502020-04-08 01:07:56 +050011554 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011555 lua_pushstring(L, "__index");
11556 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011557
11558 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011559 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
11560 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
11561 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
11562 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
11563 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
11564 hlua_class_function(L, "getline", hlua_applet_http_getline);
11565 hlua_class_function(L, "receive", hlua_applet_http_recv);
11566 hlua_class_function(L, "send", hlua_applet_http_send);
11567 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
11568 hlua_class_function(L, "set_status", hlua_applet_http_status);
11569 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011570
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011571 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011572
11573 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011574 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011575
11576 /*
11577 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011578 * Register class TXN
11579 *
11580 */
11581
11582 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011583 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011584
Ilya Shipitsind4259502020-04-08 01:07:56 +050011585 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011586 lua_pushstring(L, "__index");
11587 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011588
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011589 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011590 hlua_class_function(L, "set_priv", hlua_set_priv);
11591 hlua_class_function(L, "get_priv", hlua_get_priv);
11592 hlua_class_function(L, "set_var", hlua_set_var);
11593 hlua_class_function(L, "unset_var", hlua_unset_var);
11594 hlua_class_function(L, "get_var", hlua_get_var);
11595 hlua_class_function(L, "done", hlua_txn_done);
11596 hlua_class_function(L, "reply", hlua_txn_reply_new);
11597 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
11598 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
11599 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
11600 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
11601 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
11602 hlua_class_function(L, "deflog", hlua_txn_deflog);
11603 hlua_class_function(L, "log", hlua_txn_log);
11604 hlua_class_function(L, "Debug", hlua_txn_log_debug);
11605 hlua_class_function(L, "Info", hlua_txn_log_info);
11606 hlua_class_function(L, "Warning", hlua_txn_log_warning);
11607 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011608
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011609 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011610
11611 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011612 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011613
11614 /*
11615 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010011616 * Register class reply
11617 *
11618 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011619 lua_newtable(L);
11620 lua_pushstring(L, "__index");
11621 lua_newtable(L);
11622 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
11623 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
11624 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
11625 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
11626 lua_settable(L, -3); /* Sets the __index entry. */
11627 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010011628
11629
11630 /*
11631 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011632 * Register class Socket
11633 *
11634 */
11635
11636 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011637 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011638
Ilya Shipitsind4259502020-04-08 01:07:56 +050011639 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011640 lua_pushstring(L, "__index");
11641 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011642
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011643#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011644 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011645#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011646 hlua_class_function(L, "connect", hlua_socket_connect);
11647 hlua_class_function(L, "send", hlua_socket_send);
11648 hlua_class_function(L, "receive", hlua_socket_receive);
11649 hlua_class_function(L, "close", hlua_socket_close);
11650 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
11651 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
11652 hlua_class_function(L, "setoption", hlua_socket_setoption);
11653 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011654
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011655 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011656
11657 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011658 lua_pushstring(L, "__gc");
11659 lua_pushcclosure(L, hlua_socket_gc, 0);
11660 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011661
11662 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011663 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011664
Thierry Fournieraafc7772020-12-04 11:47:47 +010011665 lua_atpanic(L, hlua_panic_safe);
11666
11667 return L;
11668}
11669
11670void hlua_init(void) {
11671 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011672 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010011673#ifdef USE_OPENSSL
11674 struct srv_kw *kw;
11675 int tmp_error;
11676 char *error;
11677 char *args[] = { /* SSL client configuration. */
11678 "ssl",
11679 "verify",
11680 "none",
11681 NULL
11682 };
11683#endif
11684
11685 /* Init post init function list head */
11686 for (i = 0; i < MAX_THREADS + 1; i++)
11687 LIST_INIT(&hlua_init_functions[i]);
11688
11689 /* Init state for common/shared lua parts */
11690 hlua_state_id = 0;
11691 ha_set_tid(0);
11692 hlua_states[0] = hlua_init_state(0);
11693
11694 /* Init state 1 for thread 0. We have at least one thread. */
11695 hlua_state_id = 1;
11696 ha_set_tid(0);
11697 hlua_states[1] = hlua_init_state(1);
11698
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011699 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020011700 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011701 if (!socket_proxy) {
11702 fprintf(stderr, "Lua init: %s\n", errmsg);
11703 exit(1);
11704 }
11705 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011706
11707 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011708 socket_tcp = new_server(socket_proxy);
11709 if (!socket_tcp) {
11710 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
11711 exit(1);
11712 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011713
11714#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011715 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011716 socket_ssl = new_server(socket_proxy);
11717 if (!socket_ssl) {
11718 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
11719 exit(1);
11720 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011721
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011722 socket_ssl->use_ssl = 1;
11723 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011724
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011725 for (i = 0; args[i] != NULL; i++) {
11726 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011727 /*
11728 *
11729 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011730 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011731 * features like client certificates and ssl_verify.
11732 *
11733 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011734 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011735 if (tmp_error != 0) {
11736 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
11737 abort(); /* This must be never arrives because the command line
11738 not editable by the user. */
11739 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011740 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011741 }
11742 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011743#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010011744
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011745}
Willy Tarreaubb57d942016-12-21 19:04:56 +010011746
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011747static void hlua_deinit()
11748{
Willy Tarreau186f3762020-12-04 11:48:12 +010011749 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011750 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
11751
11752 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
11753 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010011754
11755 for (thr = 0; thr < MAX_THREADS+1; thr++) {
11756 if (hlua_states[thr])
11757 lua_close(hlua_states[thr]);
11758 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011759
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020011760 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011761
Willy Tarreau0f143af2021-03-05 10:41:48 +010011762#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020011763 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010011764#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011765
11766 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011767}
11768
11769REGISTER_POST_DEINIT(hlua_deinit);
11770
Willy Tarreau80713382018-11-26 10:19:54 +010011771static void hlua_register_build_options(void)
11772{
Willy Tarreaubb57d942016-12-21 19:04:56 +010011773 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010011774
Willy Tarreaubb57d942016-12-21 19:04:56 +010011775 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
11776 hap_register_build_opts(ptr, 1);
11777}
Willy Tarreau80713382018-11-26 10:19:54 +010011778
11779INITCALL0(STG_REGISTER, hlua_register_build_options);