blob: 4bce23f760d45072ba88089c2f1313d8481b4892 [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 Tarreaue6124462021-09-13 10:07:38 +02002943 appctx = appctx_new(&update_applet);
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);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004385 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004386 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);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004872 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004873 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);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006318 v = istadv(v, offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006319 if (v.len > len)
6320 v.len = len;
6321
6322 luaL_addlstring(&b, v.ptr, v.len);
6323 ret += v.len;
6324 break;
6325
6326 default:
6327 if (!ret) {
6328 /* Remove the empty string and push nil on the stack */
6329 lua_pop(L, 1);
6330 lua_pushnil(L);
6331 }
6332 goto end;
6333 }
6334 offset = 0;
6335 }
6336
6337 luaL_pushresult(&b);
6338
6339end:
6340 return ret;
6341}
6342
6343/* Copies the string <str> to the HTTP message <msg> at the offset
6344 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006345 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006346 * the filter context.
6347 */
6348static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6349{
6350 struct htx *htx = htx_from_buf(&msg->chn->buf);
6351 struct htx_ret htxret;
6352 int /*max, */ret = 0;
6353
6354 /* Nothing to do, just return */
6355 if (unlikely(istlen(str) == 0))
6356 goto end;
6357
6358 if (istlen(str) > htx_free_data_space(htx)) {
6359 ret = -1;
6360 goto end;
6361 }
6362
6363 htxret = htx_find_offset(htx, offset);
6364 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6365 if (!htx_add_last_data(htx, str))
6366 goto end;
6367 }
6368 else {
6369 struct ist v = htx_get_blk_value(htx, htxret.blk);
6370 v.ptr += htxret.ret;
6371 v.len = 0;
6372 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6373 goto end;
6374 }
6375 ret = str.len;
6376 if (ret) {
6377 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6378 flt_update_offsets(filter, msg->chn, ret);
6379 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6380 }
6381
6382 end:
6383 htx_to_buf(htx, &msg->chn->buf);
6384 return ret;
6385}
6386
6387/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6388 * position <offset>. It stops on the first non-DATA HTX block. This function is
6389 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006390 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006391 * update the filter context.
6392 */
6393static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6394{
6395 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6396 struct htx *htx = htx_from_buf(&msg->chn->buf);
6397 struct htx_blk *blk;
6398 struct htx_ret htxret;
6399 size_t ret = 0;
6400
6401 /* Be sure <len> is always the amount of DATA to remove */
6402 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6403 htx_truncate(htx, offset);
6404 ret = len;
6405 goto end;
6406 }
6407
6408 htxret = htx_find_offset(htx, offset);
6409 blk = htxret.blk;
6410 if (htxret.ret) {
6411 struct ist v;
6412
6413 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6414 goto end;
6415 v = htx_get_blk_value(htx, blk);
6416 v.ptr += htxret.ret;
6417 if (v.len > len)
6418 v.len = len;
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006419 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006420 len -= v.len;
6421 ret += v.len;
6422 }
6423
6424
6425 while (blk && len) {
6426 enum htx_blk_type type = htx_get_blk_type(blk);
6427 uint32_t sz = htx_get_blksz(blk);
6428
6429 switch (type) {
6430 case HTX_BLK_UNUSED:
6431 break;
6432
6433 case HTX_BLK_DATA:
6434 if (len < sz) {
6435 htx_cut_data_blk(htx, blk, len);
6436 ret += len;
6437 goto end;
6438 }
6439 break;
6440
6441 default:
6442 goto end;
6443 }
6444
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006445 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006446 len -= sz;
6447 ret += sz;
6448 blk = htx_remove_blk(htx, blk);
6449 }
6450
6451end:
6452 flt_update_offsets(filter, msg->chn, -ret);
6453 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6454 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6455 * to loose the EOM flag if the message is empty.
6456 */
6457}
6458
6459/* Copies input data found in an HTTP message. Unlike the channel function used
6460 * to duplicate raw data, this one can only be called inside a filter, from
6461 * http_payload callback. So it cannot yield. An exception is returned if it is
6462 * called from another callback. If nothing was copied, a nil value is pushed on
6463 * the stack.
6464 */
6465__LJMP static int hlua_http_msg_get_body(lua_State *L)
6466{
6467 struct http_msg *msg;
6468 struct filter *filter;
6469 size_t output, input;
6470 int offset, len;
6471
6472 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6473 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6474 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6475
6476 if (msg->msg_state < HTTP_MSG_DATA)
6477 WILL_LJMP(lua_error(L));
6478
6479 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6480 if (!filter || !hlua_filter_from_payload(filter))
6481 WILL_LJMP(lua_error(L));
6482
6483 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6484 lua_pushnil(L);
6485 return 1;
6486 }
6487
6488 offset = output;
6489 if (lua_gettop(L) > 1) {
6490 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6491 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006492 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006493 offset += output;
6494 if (offset < output || offset > input + output) {
6495 lua_pushfstring(L, "offset out of range.");
6496 WILL_LJMP(lua_error(L));
6497 }
6498 }
6499 len = output + input - offset;
6500 if (lua_gettop(L) == 3) {
6501 len = MAY_LJMP(luaL_checkinteger(L, 3));
6502 if (!len)
6503 goto dup;
6504 if (len == -1)
6505 len = global.tune.bufsize;
6506 if (len < 0) {
6507 lua_pushfstring(L, "length out of range.");
6508 WILL_LJMP(lua_error(L));
6509 }
6510 }
6511
6512 dup:
6513 _hlua_http_msg_dup(msg, L, offset, len);
6514 return 1;
6515}
6516
6517/* Appends a string to the HTTP message, after all existing DATA blocks but
6518 * before the trailers, if any. It returns the amount of data written or -1 if
6519 * nothing was copied. Unlike the channel function used to append data, this one
6520 * can only be called inside a filter, from http_payload callback. So it cannot
6521 * yield. An exception is returned if it is called from another callback.
6522 */
6523__LJMP static int hlua_http_msg_append(lua_State *L)
6524{
6525 struct http_msg *msg;
6526 struct filter *filter;
6527 const char *str;
6528 size_t offset, len, sz;
6529 int ret;
6530
6531 MAY_LJMP(check_args(L, 2, "append"));
6532 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6533
6534 if (msg->msg_state < HTTP_MSG_DATA)
6535 WILL_LJMP(lua_error(L));
6536
6537 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6538 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6539 if (!filter || !hlua_filter_from_payload(filter))
6540 WILL_LJMP(lua_error(L));
6541
6542 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6543 lua_pushinteger(L, ret);
6544 return 1;
6545}
6546
6547/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6548 * returns the amount of data written or -1 if nothing was copied. Unlike the
6549 * channel function used to prepend data, this one can only be called inside a
6550 * filter, from http_payload callback. So it cannot yield. An exception is
6551 * returned if it is called from another callback.
6552 */
6553__LJMP static int hlua_http_msg_prepend(lua_State *L)
6554{
6555 struct http_msg *msg;
6556 struct filter *filter;
6557 const char *str;
6558 size_t offset, len, sz;
6559 int ret;
6560
6561 MAY_LJMP(check_args(L, 2, "prepend"));
6562 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006563
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006564 if (msg->msg_state < HTTP_MSG_DATA)
6565 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006566
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006567 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6568 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6569 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006570 WILL_LJMP(lua_error(L));
6571
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006572 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6573 lua_pushinteger(L, ret);
6574 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006575}
6576
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006577/* Inserts a string to the HTTP message at a given offset. By default the string
6578 * is appended at the end of DATA blocks. It returns the amount of data written
6579 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6580 * this one can only be called inside a filter, from http_payload callback. So
6581 * it cannot yield. An exception is returned if it is called from another
6582 * callback.
6583 */
6584__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006585{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006586 struct http_msg *msg;
6587 struct filter *filter;
6588 const char *str;
6589 size_t input, output, sz;
6590 int offset;
6591 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006592
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006593 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6594 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6595 MAY_LJMP(check_args(L, 2, "insert"));
6596 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006597
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006598 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006599 WILL_LJMP(lua_error(L));
6600
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006601 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6602 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6603 if (!filter || !hlua_filter_from_payload(filter))
6604 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006605
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006606 offset = input + output;
6607 if (lua_gettop(L) > 2) {
6608 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6609 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006610 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006611 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006612 if (offset < output || offset > output + input) {
6613 lua_pushfstring(L, "offset out of range.");
6614 WILL_LJMP(lua_error(L));
6615 }
6616 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006617
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006618 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6619 lua_pushinteger(L, ret);
6620 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006621}
6622
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006623/* Removes a given amount of data from the HTTP message at a given offset. By
6624 * default all DATA blocks are removed. It returns the amount of data
6625 * removed. Unlike the channel function used to remove data, this one can only
6626 * be called inside a filter, from http_payload callback. So it cannot yield. An
6627 * exception is returned if it is called from another callback.
6628 */
6629__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006630{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006631 struct http_msg *msg;
6632 struct filter *filter;
6633 size_t input, output;
6634 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006635
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006636 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6637 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6638 MAY_LJMP(check_args(L, 2, "insert"));
6639 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006640
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006641 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006642 WILL_LJMP(lua_error(L));
6643
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006644 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6645 if (!filter || !hlua_filter_from_payload(filter))
6646 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006647
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006648 offset = input + output;
6649 if (lua_gettop(L) > 2) {
6650 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6651 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006652 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006653 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006654 if (offset < output || offset > output + input) {
6655 lua_pushfstring(L, "offset out of range.");
6656 WILL_LJMP(lua_error(L));
6657 }
6658 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006659
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006660 len = output + input - offset;
6661 if (lua_gettop(L) == 4) {
6662 len = MAY_LJMP(luaL_checkinteger(L, 4));
6663 if (!len)
6664 goto end;
6665 if (len == -1)
6666 len = output + input - offset;
6667 if (len < 0 || offset + len > output + input) {
6668 lua_pushfstring(L, "length out of range.");
6669 WILL_LJMP(lua_error(L));
6670 }
6671 }
6672
6673 _hlua_http_msg_delete(msg, filter, offset, len);
6674
6675 end:
6676 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006677 return 1;
6678}
6679
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006680/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006681 * all remaining data are removed, accordingly to the filter context. It returns
6682 * the amount of data written or -1 if nothing was copied. Unlike the channel
6683 * function used to replace data, this one can only be called inside a filter,
6684 * from http_payload callback. So it cannot yield. An exception is returned if
6685 * it is called from another callback.
6686 */
6687__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006688{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006689 struct http_msg *msg;
6690 struct filter *filter;
6691 struct htx *htx;
6692 const char *str;
6693 size_t input, output, sz;
6694 int offset, len;
6695 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006696
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006697 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6698 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6699 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6700
6701 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006702 WILL_LJMP(lua_error(L));
6703
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006704 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6705 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6706 if (!filter || !hlua_filter_from_payload(filter))
6707 WILL_LJMP(lua_error(L));
6708
6709 offset = output;
6710 if (lua_gettop(L) > 2) {
6711 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6712 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006713 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006714 offset += output;
6715 if (offset < output || offset > input + output) {
6716 lua_pushfstring(L, "offset out of range.");
6717 WILL_LJMP(lua_error(L));
6718 }
6719 }
6720
6721 len = output + input - offset;
6722 if (lua_gettop(L) == 4) {
6723 len = MAY_LJMP(luaL_checkinteger(L, 4));
6724 if (!len)
6725 goto set;
6726 if (len == -1)
6727 len = output + input - offset;
6728 if (len < 0 || offset + len > output + input) {
6729 lua_pushfstring(L, "length out of range.");
6730 WILL_LJMP(lua_error(L));
6731 }
6732 }
6733
6734 set:
6735 /* Be sure we can copied the string once input data will be removed. */
6736 htx = htx_from_buf(&msg->chn->buf);
6737 if (sz > htx_free_data_space(htx) + len)
6738 lua_pushinteger(L, -1);
6739 else {
6740 _hlua_http_msg_delete(msg, filter, offset, len);
6741 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6742 lua_pushinteger(L, ret);
6743 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006744 return 1;
6745}
6746
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006747/* Prepends data into an HTTP message and forward it, from the filter point of
6748 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6749 * the channel function used to send data, this one can only be called inside a
6750 * filter, from http_payload callback. So it cannot yield. An exception is
6751 * returned if it is called from another callback.
6752 */
6753__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006754{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006755 struct http_msg *msg;
6756 struct filter *filter;
6757 struct htx *htx;
6758 const char *str;
6759 size_t offset, len, sz;
6760 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006761
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006762 MAY_LJMP(check_args(L, 2, "send"));
6763 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6764
6765 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006766 WILL_LJMP(lua_error(L));
6767
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006768 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6769 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6770 if (!filter || !hlua_filter_from_payload(filter))
6771 WILL_LJMP(lua_error(L));
6772
6773 /* Return an error if the channel's output is closed */
6774 if (unlikely(channel_output_closed(msg->chn))) {
6775 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006776 return 1;
6777 }
6778
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006779 htx = htx_from_buf(&msg->chn->buf);
6780 if (sz > htx_free_data_space(htx)) {
6781 lua_pushinteger(L, -1);
6782 return 1;
6783 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006784
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006785 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6786 if (ret > 0) {
6787 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6788
6789 FLT_OFF(filter, msg->chn) += ret;
6790 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6791 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6792 }
6793
6794 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006795 return 1;
6796}
6797
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006798/* Forwards a given amount of bytes. It return -1 if the channel's output is
6799 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6800 * channel function used to forward data, this one can only be called inside a
6801 * filter, from http_payload callback. So it cannot yield. An exception is
6802 * returned if it is called from another callback. All other functions deal with
6803 * DATA block, this one not.
6804*/
6805__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006806{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006807 struct http_msg *msg;
6808 struct filter *filter;
6809 size_t offset, len;
6810 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006811
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006812 MAY_LJMP(check_args(L, 2, "forward"));
6813 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6814
6815 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006816 WILL_LJMP(lua_error(L));
6817
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006818 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6819 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6820 if (!filter || !hlua_filter_from_payload(filter))
6821 WILL_LJMP(lua_error(L));
6822
6823 /* Nothing to do, just return */
6824 if (!fwd)
6825 goto end;
6826
6827 /* Return an error if the channel's output is closed */
6828 if (unlikely(channel_output_closed(msg->chn))) {
6829 ret = -1;
6830 goto end;
6831 }
6832
6833 ret = fwd;
6834 if (ret > len)
6835 ret = len;
6836
6837 if (ret) {
6838 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6839
6840 FLT_OFF(filter, msg->chn) += ret;
6841 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6842 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6843 }
6844
6845 end:
6846 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006847 return 1;
6848}
6849
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006850/* Set EOM flag on the HTX message.
6851 *
6852 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6853 * really know how to do without this feature.
6854 */
6855__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006856{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006857 struct http_msg *msg;
6858 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006859
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006860 MAY_LJMP(check_args(L, 1, "set_eom"));
6861 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6862 htx = htxbuf(&msg->chn->buf);
6863 htx->flags |= HTX_FL_EOM;
6864 return 0;
6865}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006866
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006867/* Unset EOM flag on the HTX message.
6868 *
6869 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6870 * really know how to do without this feature.
6871 */
6872__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6873{
6874 struct http_msg *msg;
6875 struct htx *htx;
6876
6877 MAY_LJMP(check_args(L, 1, "set_eom"));
6878 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6879 htx = htxbuf(&msg->chn->buf);
6880 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006881 return 0;
6882}
6883
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006884/*
6885 *
6886 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006887 * Class TXN
6888 *
6889 *
6890 */
6891
6892/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02006893 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006894 */
6895__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
6896{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006897 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006898}
6899
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006900__LJMP static int hlua_set_var(lua_State *L)
6901{
6902 struct hlua_txn *htxn;
6903 const char *name;
6904 size_t len;
6905 struct sample smp;
6906
Tim Duesterhus4e172c92020-05-19 13:49:42 +02006907 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6908 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006909
6910 /* It is useles to retrieve the stream, but this function
6911 * runs only in a stream context.
6912 */
6913 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6914 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6915
6916 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01006917 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006918 hlua_lua2smp(L, 3, &smp);
6919
6920 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01006921 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02006922
6923 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
6924 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
6925 else
6926 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
6927
Tim Duesterhus84ebc132020-05-19 13:49:41 +02006928 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006929}
6930
Christopher Faulet85d79c92016-11-09 16:54:56 +01006931__LJMP static int hlua_unset_var(lua_State *L)
6932{
6933 struct hlua_txn *htxn;
6934 const char *name;
6935 size_t len;
6936 struct sample smp;
6937
6938 MAY_LJMP(check_args(L, 2, "unset_var"));
6939
6940 /* It is useles to retrieve the stream, but this function
6941 * runs only in a stream context.
6942 */
6943 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6944 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6945
6946 /* Unset the variable. */
6947 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02006948 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
6949 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01006950}
6951
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006952__LJMP static int hlua_get_var(lua_State *L)
6953{
6954 struct hlua_txn *htxn;
6955 const char *name;
6956 size_t len;
6957 struct sample smp;
6958
6959 MAY_LJMP(check_args(L, 2, "get_var"));
6960
6961 /* It is useles to retrieve the stream, but this function
6962 * runs only in a stream context.
6963 */
6964 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6965 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
6966
Willy Tarreau7560dd42016-03-10 16:28:58 +01006967 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02006968 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006969 lua_pushnil(L);
6970 return 1;
6971 }
6972
6973 return hlua_smp2lua(L, &smp);
6974}
6975
Willy Tarreau59551662015-03-10 14:23:13 +01006976__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006977{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006978 struct hlua *hlua;
6979
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006980 MAY_LJMP(check_args(L, 2, "set_priv"));
6981
Willy Tarreau87b09662015-04-03 00:22:06 +02006982 /* It is useles to retrieve the stream, but this function
6983 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006984 */
6985 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006986
6987 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006988 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006989 if (!hlua)
6990 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006991
6992 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02006993 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006994
6995 /* Get and store new value. */
6996 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
6997 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
6998
6999 return 0;
7000}
7001
Willy Tarreau59551662015-03-10 14:23:13 +01007002__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007003{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007004 struct hlua *hlua;
7005
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007006 MAY_LJMP(check_args(L, 1, "get_priv"));
7007
Willy Tarreau87b09662015-04-03 00:22:06 +02007008 /* It is useles to retrieve the stream, but this function
7009 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007010 */
7011 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007012
7013 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007014 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007015 if (!hlua) {
7016 lua_pushnil(L);
7017 return 1;
7018 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007019
7020 /* Push configuration index in the stack. */
7021 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7022
7023 return 1;
7024}
7025
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007026/* Create stack entry containing a class TXN. This function
7027 * return 0 if the stack does not contains free slots,
7028 * otherwise it returns 1.
7029 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007030static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007031{
Willy Tarreaude491382015-04-06 11:04:28 +02007032 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007033
7034 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007035 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007036 return 0;
7037
7038 /* NOTE: The allocation never fails. The failure
7039 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007040 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007041 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007042 /* Create the object: obj[0] = userdata. */
7043 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007044 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007045 lua_rawseti(L, -2, 0);
7046
Willy Tarreaude491382015-04-06 11:04:28 +02007047 htxn->s = s;
7048 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007049 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007050 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007051
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007052 /* Create the "f" field that contains a list of fetches. */
7053 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007054 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007055 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007056 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007057
7058 /* Create the "sf" field that contains a list of stringsafe fetches. */
7059 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007060 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007061 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007062 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007063
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007064 /* Create the "c" field that contains a list of converters. */
7065 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007066 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007067 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007068 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007069
7070 /* Create the "sc" field that contains a list of stringsafe converters. */
7071 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007072 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007073 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007074 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007075
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007076 /* Create the "req" field that contains the request channel object. */
7077 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007078 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007079 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007080 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007081
7082 /* Create the "res" field that contains the response channel object. */
7083 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007084 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007085 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007086 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007087
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007088 /* Creates the HTTP object is the current proxy allows http. */
7089 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007090 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007091 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007092 return 0;
7093 }
7094 else
7095 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007096 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007097
Christopher Faulet78c35472020-02-26 17:14:08 +01007098 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7099 /* HTTPMessage object are created when a lua TXN is created from
7100 * a filter context only
7101 */
7102
7103 /* Creates the HTTP-Request object is the current proxy allows http. */
7104 lua_pushstring(L, "http_req");
7105 if (p->mode == PR_MODE_HTTP) {
7106 if (!hlua_http_msg_new(L, &s->txn->req))
7107 return 0;
7108 }
7109 else
7110 lua_pushnil(L);
7111 lua_rawset(L, -3);
7112
7113 /* Creates the HTTP-Response object is the current proxy allows http. */
7114 lua_pushstring(L, "http_res");
7115 if (p->mode == PR_MODE_HTTP) {
7116 if (!hlua_http_msg_new(L, &s->txn->rsp))
7117 return 0;
7118 }
7119 else
7120 lua_pushnil(L);
7121 lua_rawset(L, -3);
7122 }
7123
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007124 /* Pop a class sesison metatable and affect it to the userdata. */
7125 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7126 lua_setmetatable(L, -2);
7127
7128 return 1;
7129}
7130
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007131__LJMP static int hlua_txn_deflog(lua_State *L)
7132{
7133 const char *msg;
7134 struct hlua_txn *htxn;
7135
7136 MAY_LJMP(check_args(L, 2, "deflog"));
7137 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7138 msg = MAY_LJMP(luaL_checkstring(L, 2));
7139
7140 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7141 return 0;
7142}
7143
7144__LJMP static int hlua_txn_log(lua_State *L)
7145{
7146 int level;
7147 const char *msg;
7148 struct hlua_txn *htxn;
7149
7150 MAY_LJMP(check_args(L, 3, "log"));
7151 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7152 level = MAY_LJMP(luaL_checkinteger(L, 2));
7153 msg = MAY_LJMP(luaL_checkstring(L, 3));
7154
7155 if (level < 0 || level >= NB_LOG_LEVELS)
7156 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7157
7158 hlua_sendlog(htxn->s->be, level, msg);
7159 return 0;
7160}
7161
7162__LJMP static int hlua_txn_log_debug(lua_State *L)
7163{
7164 const char *msg;
7165 struct hlua_txn *htxn;
7166
7167 MAY_LJMP(check_args(L, 2, "Debug"));
7168 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7169 msg = MAY_LJMP(luaL_checkstring(L, 2));
7170 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7171 return 0;
7172}
7173
7174__LJMP static int hlua_txn_log_info(lua_State *L)
7175{
7176 const char *msg;
7177 struct hlua_txn *htxn;
7178
7179 MAY_LJMP(check_args(L, 2, "Info"));
7180 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7181 msg = MAY_LJMP(luaL_checkstring(L, 2));
7182 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7183 return 0;
7184}
7185
7186__LJMP static int hlua_txn_log_warning(lua_State *L)
7187{
7188 const char *msg;
7189 struct hlua_txn *htxn;
7190
7191 MAY_LJMP(check_args(L, 2, "Warning"));
7192 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7193 msg = MAY_LJMP(luaL_checkstring(L, 2));
7194 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7195 return 0;
7196}
7197
7198__LJMP static int hlua_txn_log_alert(lua_State *L)
7199{
7200 const char *msg;
7201 struct hlua_txn *htxn;
7202
7203 MAY_LJMP(check_args(L, 2, "Alert"));
7204 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7205 msg = MAY_LJMP(luaL_checkstring(L, 2));
7206 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7207 return 0;
7208}
7209
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007210__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7211{
7212 struct hlua_txn *htxn;
7213 int ll;
7214
7215 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7216 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7217 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7218
7219 if (ll < 0 || ll > 7)
7220 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7221
7222 htxn->s->logs.level = ll;
7223 return 0;
7224}
7225
7226__LJMP static int hlua_txn_set_tos(lua_State *L)
7227{
7228 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007229 int tos;
7230
7231 MAY_LJMP(check_args(L, 2, "set_tos"));
7232 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7233 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7234
Willy Tarreau1a18b542018-12-11 16:37:42 +01007235 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007236 return 0;
7237}
7238
7239__LJMP static int hlua_txn_set_mark(lua_State *L)
7240{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007241 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007242 int mark;
7243
7244 MAY_LJMP(check_args(L, 2, "set_mark"));
7245 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7246 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7247
Lukas Tribus579e3e32019-08-11 18:03:45 +02007248 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007249 return 0;
7250}
7251
Patrick Hemmer268a7072018-05-11 12:52:31 -04007252__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7253{
7254 struct hlua_txn *htxn;
7255
7256 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7257 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7258 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7259 return 0;
7260}
7261
7262__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7263{
7264 struct hlua_txn *htxn;
7265
7266 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7267 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7268 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7269 return 0;
7270}
7271
Christopher Faulet700d9e82020-01-31 12:21:52 +01007272/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007273 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007274 * message and terminate the transaction. It returns 1 on success and 0 on
7275 * error. The Reply must be on top of the stack.
7276 */
7277__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7278{
7279 struct htx *htx;
7280 struct htx_sl *sl;
7281 struct h1m h1m;
7282 const char *status, *reason, *body;
7283 size_t status_len, reason_len, body_len;
7284 int ret, code, flags;
7285
7286 code = 200;
7287 status = "200";
7288 status_len = 3;
7289 ret = lua_getfield(L, -1, "status");
7290 if (ret == LUA_TNUMBER) {
7291 code = lua_tointeger(L, -1);
7292 status = lua_tolstring(L, -1, &status_len);
7293 }
7294 lua_pop(L, 1);
7295
7296 reason = http_get_reason(code);
7297 reason_len = strlen(reason);
7298 ret = lua_getfield(L, -1, "reason");
7299 if (ret == LUA_TSTRING)
7300 reason = lua_tolstring(L, -1, &reason_len);
7301 lua_pop(L, 1);
7302
7303 body = NULL;
7304 body_len = 0;
7305 ret = lua_getfield(L, -1, "body");
7306 if (ret == LUA_TSTRING)
7307 body = lua_tolstring(L, -1, &body_len);
7308 lua_pop(L, 1);
7309
7310 /* Prepare the response before inserting the headers */
7311 h1m_init_res(&h1m);
7312 htx = htx_from_buf(&s->res.buf);
7313 channel_htx_truncate(&s->res, htx);
7314 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7315 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7316 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7317 ist2(status, status_len), ist2(reason, reason_len));
7318 }
7319 else {
7320 flags = HTX_SL_F_IS_RESP;
7321 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7322 ist2(status, status_len), ist2(reason, reason_len));
7323 }
7324 if (!sl)
7325 goto fail;
7326 sl->info.res.status = code;
7327
7328 /* Push in the stack the "headers" entry. */
7329 ret = lua_getfield(L, -1, "headers");
7330 if (ret != LUA_TTABLE)
7331 goto skip_headers;
7332
7333 lua_pushnil(L);
7334 while (lua_next(L, -2) != 0) {
7335 struct ist name, value;
7336 const char *n, *v;
7337 size_t nlen, vlen;
7338
7339 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7340 /* Skip element if the key is not a string or if the value is not a table */
7341 goto next_hdr;
7342 }
7343
7344 n = lua_tolstring(L, -2, &nlen);
7345 name = ist2(n, nlen);
7346 if (isteqi(name, ist("content-length"))) {
7347 /* Always skip content-length header. It will be added
7348 * later with the correct len
7349 */
7350 goto next_hdr;
7351 }
7352
7353 /* Loop on header's values */
7354 lua_pushnil(L);
7355 while (lua_next(L, -2)) {
7356 if (!lua_isstring(L, -1)) {
7357 /* Skip the value if it is not a string */
7358 goto next_value;
7359 }
7360
7361 v = lua_tolstring(L, -1, &vlen);
7362 value = ist2(v, vlen);
7363
7364 if (isteqi(name, ist("transfer-encoding")))
7365 h1_parse_xfer_enc_header(&h1m, value);
7366 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7367 goto fail;
7368
7369 next_value:
7370 lua_pop(L, 1);
7371 }
7372
7373 next_hdr:
7374 lua_pop(L, 1);
7375 }
7376 skip_headers:
7377 lua_pop(L, 1);
7378
7379 /* Update h1m flags: CLEN is set if CHNK is not present */
7380 if (!(h1m.flags & H1_MF_CHNK)) {
7381 const char *clen = ultoa(body_len);
7382
7383 h1m.flags |= H1_MF_CLEN;
7384 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7385 goto fail;
7386 }
7387 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7388 h1m.flags |= H1_MF_XFER_LEN;
7389
7390 /* Update HTX start-line flags */
7391 if (h1m.flags & H1_MF_XFER_ENC)
7392 flags |= HTX_SL_F_XFER_ENC;
7393 if (h1m.flags & H1_MF_XFER_LEN) {
7394 flags |= HTX_SL_F_XFER_LEN;
7395 if (h1m.flags & H1_MF_CHNK)
7396 flags |= HTX_SL_F_CHNK;
7397 else if (h1m.flags & H1_MF_CLEN)
7398 flags |= HTX_SL_F_CLEN;
7399 if (h1m.body_len == 0)
7400 flags |= HTX_SL_F_BODYLESS;
7401 }
7402 sl->flags |= flags;
7403
7404
7405 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007406 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007407 goto fail;
7408
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007409 htx->flags |= HTX_FL_EOM;
7410
Christopher Faulet700d9e82020-01-31 12:21:52 +01007411 /* Now, forward the response and terminate the transaction */
7412 s->txn->status = code;
7413 htx_to_buf(htx, &s->res.buf);
7414 if (!http_forward_proxy_resp(s, 1))
7415 goto fail;
7416
7417 return 1;
7418
7419 fail:
7420 channel_htx_truncate(&s->res, htx);
7421 return 0;
7422}
7423
7424/* Terminate a transaction if called from a lua action. For TCP streams,
7425 * processing is just aborted. Nothing is returned to the client and all
7426 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7427 * is forwarded to the client before terminating the transaction. On success,
7428 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7429 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7430 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007431 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007432__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007433{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007434 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007435 struct stream *s;
7436 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007437
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007438 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007439
Christopher Faulet700d9e82020-01-31 12:21:52 +01007440 /* If the flags NOTERM is set, we cannot terminate the session, so we
7441 * just end the execution of the current lua code. */
7442 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007443 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007444
Christopher Faulet700d9e82020-01-31 12:21:52 +01007445 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007446 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007447 struct channel *req = &s->req;
7448 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007449
Christopher Faulet700d9e82020-01-31 12:21:52 +01007450 channel_auto_read(req);
7451 channel_abort(req);
7452 channel_auto_close(req);
7453 channel_erase(req);
7454
7455 res->wex = tick_add_ifset(now_ms, res->wto);
7456 channel_auto_read(res);
7457 channel_auto_close(res);
7458 channel_shutr_now(res);
7459
7460 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7461 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007462 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007463
Christopher Faulet700d9e82020-01-31 12:21:52 +01007464 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7465 /* No reply or invalid reply */
7466 s->txn->status = 0;
7467 http_reply_and_close(s, 0, NULL);
7468 }
7469 else {
7470 /* Remove extra args to have the reply on top of the stack */
7471 if (lua_gettop(L) > 2)
7472 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007473
Christopher Faulet700d9e82020-01-31 12:21:52 +01007474 if (!hlua_txn_forward_reply(L, s)) {
7475 if (!(s->flags & SF_ERR_MASK))
7476 s->flags |= SF_ERR_PRXCOND;
7477 lua_pushinteger(L, ACT_RET_ERR);
7478 WILL_LJMP(hlua_done(L));
7479 return 0; /* Never reached */
7480 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007481 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007482
Christopher Faulet700d9e82020-01-31 12:21:52 +01007483 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7484 if (htxn->dir == SMP_OPT_DIR_REQ) {
7485 /* let's log the request time */
7486 s->logs.tv_request = now;
7487 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007488 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007489 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007490
Christopher Faulet700d9e82020-01-31 12:21:52 +01007491 done:
7492 if (!(s->flags & SF_ERR_MASK))
7493 s->flags |= SF_ERR_LOCAL;
7494 if (!(s->flags & SF_FINST_MASK))
7495 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007496
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007497 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7498 lua_pushinteger(L, -1);
7499 else
7500 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007501 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007502 return 0;
7503}
7504
Christopher Faulet700d9e82020-01-31 12:21:52 +01007505/*
7506 *
7507 *
7508 * Class REPLY
7509 *
7510 *
7511 */
7512
7513/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
7514 * free slots, the function fails and returns 0;
7515 */
7516static int hlua_txn_reply_new(lua_State *L)
7517{
7518 struct hlua_txn *htxn;
7519 const char *reason, *body = NULL;
7520 int ret, status;
7521
7522 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007523 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007524 hlua_pusherror(L, "txn object is not an HTTP transaction.");
7525 WILL_LJMP(lua_error(L));
7526 }
7527
7528 /* Default value */
7529 status = 200;
7530 reason = http_get_reason(status);
7531
7532 if (lua_istable(L, 2)) {
7533 /* load status and reason from the table argument at index 2 */
7534 ret = lua_getfield(L, 2, "status");
7535 if (ret == LUA_TNIL)
7536 goto reason;
7537 else if (ret != LUA_TNUMBER) {
7538 /* invalid status: ignore the reason */
7539 goto body;
7540 }
7541 status = lua_tointeger(L, -1);
7542
7543 reason:
7544 lua_pop(L, 1); /* restore the stack: remove status */
7545 ret = lua_getfield(L, 2, "reason");
7546 if (ret == LUA_TSTRING)
7547 reason = lua_tostring(L, -1);
7548
7549 body:
7550 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
7551 ret = lua_getfield(L, 2, "body");
7552 if (ret == LUA_TSTRING)
7553 body = lua_tostring(L, -1);
7554 lua_pop(L, 1); /* restore the stack: remove body */
7555 }
7556
7557 /* Create the Reply table */
7558 lua_newtable(L);
7559
7560 /* Add status element */
7561 lua_pushstring(L, "status");
7562 lua_pushinteger(L, status);
7563 lua_settable(L, -3);
7564
7565 /* Add reason element */
7566 reason = http_get_reason(status);
7567 lua_pushstring(L, "reason");
7568 lua_pushstring(L, reason);
7569 lua_settable(L, -3);
7570
7571 /* Add body element, nil if undefined */
7572 lua_pushstring(L, "body");
7573 if (body)
7574 lua_pushstring(L, body);
7575 else
7576 lua_pushnil(L);
7577 lua_settable(L, -3);
7578
7579 /* Add headers element */
7580 lua_pushstring(L, "headers");
7581 lua_newtable(L);
7582
7583 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7584 if (lua_istable(L, 2)) {
7585 /* load headers from the table argument at index 2. If it is a table, copy it. */
7586 ret = lua_getfield(L, 2, "headers");
7587 if (ret == LUA_TTABLE) {
7588 /* stack: [ ... <headers:table>, <table> ] */
7589 lua_pushnil(L);
7590 while (lua_next(L, -2) != 0) {
7591 /* stack: [ ... <headers:table>, <table>, k, v] */
7592 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
7593 /* invalid value type, skip it */
7594 lua_pop(L, 1);
7595 continue;
7596 }
7597
7598
7599 /* Duplicate the key and swap it with the value. */
7600 lua_pushvalue(L, -2);
7601 lua_insert(L, -2);
7602 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
7603
7604 lua_newtable(L);
7605 lua_insert(L, -2);
7606 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
7607
7608 if (lua_isstring(L, -1)) {
7609 /* push the value in the inner table */
7610 lua_rawseti(L, -2, 1);
7611 }
7612 else { /* table */
7613 lua_pushnil(L);
7614 while (lua_next(L, -2) != 0) {
7615 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
7616 if (!lua_isstring(L, -1)) {
7617 /* invalid value type, skip it*/
7618 lua_pop(L, 1);
7619 continue;
7620 }
7621 /* push the value in the inner table */
7622 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
7623 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
7624 }
7625 lua_pop(L, 1);
7626 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
7627 }
7628
7629 /* push (k,v) on the stack in the headers table:
7630 * stack: [ ... <headers:table>, <table>, k, k, v ]
7631 */
7632 lua_settable(L, -5);
7633 /* stack: [ ... <headers:table>, <table>, k ] */
7634 }
7635 }
7636 lua_pop(L, 1);
7637 }
7638 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7639 lua_settable(L, -3);
7640 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
7641
7642 /* Pop a class sesison metatable and affect it to the userdata. */
7643 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
7644 lua_setmetatable(L, -2);
7645 return 1;
7646}
7647
7648/* Set the reply status code, and optionally the reason. If no reason is
7649 * provided, the default one corresponding to the status code is used.
7650 */
7651__LJMP static int hlua_txn_reply_set_status(lua_State *L)
7652{
7653 int status = MAY_LJMP(luaL_checkinteger(L, 2));
7654 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
7655
7656 /* First argument (self) must be a table */
7657 luaL_checktype(L, 1, LUA_TTABLE);
7658
7659 if (status < 100 || status > 599) {
7660 lua_pushboolean(L, 0);
7661 return 1;
7662 }
7663 if (!reason)
7664 reason = http_get_reason(status);
7665
7666 lua_pushinteger(L, status);
7667 lua_setfield(L, 1, "status");
7668
7669 lua_pushstring(L, reason);
7670 lua_setfield(L, 1, "reason");
7671
7672 lua_pushboolean(L, 1);
7673 return 1;
7674}
7675
7676/* Add a header into the reply object. Each header name is associated to an
7677 * array of values in the "headers" table. If the header name is not found, a
7678 * new entry is created.
7679 */
7680__LJMP static int hlua_txn_reply_add_header(lua_State *L)
7681{
7682 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7683 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
7684 int ret;
7685
7686 /* First argument (self) must be a table */
7687 luaL_checktype(L, 1, LUA_TTABLE);
7688
7689 /* Push in the stack the "headers" entry. */
7690 ret = lua_getfield(L, 1, "headers");
7691 if (ret != LUA_TTABLE) {
7692 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
7693 WILL_LJMP(lua_error(L));
7694 }
7695
7696 /* check if the header is already registered. If not, register it. */
7697 ret = lua_getfield(L, -1, name);
7698 if (ret == LUA_TNIL) {
7699 /* Entry not found. */
7700 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
7701
7702 /* Insert the new header name in the array in the top of the stack.
7703 * It left the new array in the top of the stack.
7704 */
7705 lua_newtable(L);
7706 lua_pushstring(L, name);
7707 lua_pushvalue(L, -2);
7708 lua_settable(L, -4);
7709 }
7710 else if (ret != LUA_TTABLE) {
7711 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
7712 WILL_LJMP(lua_error(L));
7713 }
7714
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07007715 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01007716 * the header value as new entry.
7717 */
7718 lua_pushstring(L, value);
7719 ret = lua_rawlen(L, -2);
7720 lua_rawseti(L, -2, ret + 1);
7721
7722 lua_pushboolean(L, 1);
7723 return 1;
7724}
7725
7726/* Remove all occurrences of a given header name. */
7727__LJMP static int hlua_txn_reply_del_header(lua_State *L)
7728{
7729 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7730 int ret;
7731
7732 /* First argument (self) must be a table */
7733 luaL_checktype(L, 1, LUA_TTABLE);
7734
7735 /* Push in the stack the "headers" entry. */
7736 ret = lua_getfield(L, 1, "headers");
7737 if (ret != LUA_TTABLE) {
7738 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
7739 WILL_LJMP(lua_error(L));
7740 }
7741
7742 lua_pushstring(L, name);
7743 lua_pushnil(L);
7744 lua_settable(L, -3);
7745
7746 lua_pushboolean(L, 1);
7747 return 1;
7748}
7749
7750/* Set the reply's body. Overwrite any existing entry. */
7751__LJMP static int hlua_txn_reply_set_body(lua_State *L)
7752{
7753 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
7754
7755 /* First argument (self) must be a table */
7756 luaL_checktype(L, 1, LUA_TTABLE);
7757
7758 lua_pushstring(L, payload);
7759 lua_setfield(L, 1, "body");
7760
7761 lua_pushboolean(L, 1);
7762 return 1;
7763}
7764
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007765__LJMP static int hlua_log(lua_State *L)
7766{
7767 int level;
7768 const char *msg;
7769
7770 MAY_LJMP(check_args(L, 2, "log"));
7771 level = MAY_LJMP(luaL_checkinteger(L, 1));
7772 msg = MAY_LJMP(luaL_checkstring(L, 2));
7773
7774 if (level < 0 || level >= NB_LOG_LEVELS)
7775 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7776
7777 hlua_sendlog(NULL, level, msg);
7778 return 0;
7779}
7780
7781__LJMP static int hlua_log_debug(lua_State *L)
7782{
7783 const char *msg;
7784
7785 MAY_LJMP(check_args(L, 1, "debug"));
7786 msg = MAY_LJMP(luaL_checkstring(L, 1));
7787 hlua_sendlog(NULL, LOG_DEBUG, msg);
7788 return 0;
7789}
7790
7791__LJMP static int hlua_log_info(lua_State *L)
7792{
7793 const char *msg;
7794
7795 MAY_LJMP(check_args(L, 1, "info"));
7796 msg = MAY_LJMP(luaL_checkstring(L, 1));
7797 hlua_sendlog(NULL, LOG_INFO, msg);
7798 return 0;
7799}
7800
7801__LJMP static int hlua_log_warning(lua_State *L)
7802{
7803 const char *msg;
7804
7805 MAY_LJMP(check_args(L, 1, "warning"));
7806 msg = MAY_LJMP(luaL_checkstring(L, 1));
7807 hlua_sendlog(NULL, LOG_WARNING, msg);
7808 return 0;
7809}
7810
7811__LJMP static int hlua_log_alert(lua_State *L)
7812{
7813 const char *msg;
7814
7815 MAY_LJMP(check_args(L, 1, "alert"));
7816 msg = MAY_LJMP(luaL_checkstring(L, 1));
7817 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007818 return 0;
7819}
7820
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007821__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007822{
7823 int wakeup_ms = lua_tointeger(L, -1);
7824 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02007825 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007826 return 0;
7827}
7828
7829__LJMP static int hlua_sleep(lua_State *L)
7830{
7831 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007832 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007833
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007834 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007835
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007836 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007837 wakeup_ms = tick_add(now_ms, delay);
7838 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007839
Willy Tarreau9635e032018-10-16 17:52:55 +02007840 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007841 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007842}
7843
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007844__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007845{
7846 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007847 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007848
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007849 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007850
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007851 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007852 wakeup_ms = tick_add(now_ms, delay);
7853 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007854
Willy Tarreau9635e032018-10-16 17:52:55 +02007855 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007856 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007857}
7858
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007859/* This functionis an LUA binding. it permits to give back
7860 * the hand at the HAProxy scheduler. It is used when the
7861 * LUA processing consumes a lot of time.
7862 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007863__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007864{
7865 return 0;
7866}
7867
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007868__LJMP static int hlua_yield(lua_State *L)
7869{
Willy Tarreau9635e032018-10-16 17:52:55 +02007870 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007871 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007872}
7873
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007874/* This function change the nice of the currently executed
7875 * task. It is used set low or high priority at the current
7876 * task.
7877 */
Willy Tarreau59551662015-03-10 14:23:13 +01007878__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007879{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007880 struct hlua *hlua;
7881 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007882
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007883 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007884 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007885
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007886 /* Get hlua struct, or NULL if we execute from main lua state */
7887 hlua = hlua_gethlua(L);
7888
7889 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007890 if (!hlua || !hlua->task)
7891 return 0;
7892
7893 if (nice < -1024)
7894 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007895 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01007896 nice = 1024;
7897
7898 hlua->task->nice = nice;
7899 return 0;
7900}
7901
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007902/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007903 * HAProxy task subsystem when the task is awaked. The LUA runtime can
7904 * return an E_AGAIN signal, the emmiter of this signal must set a
7905 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007906 *
7907 * Task wrapper are longjmp safe because the only one Lua code
7908 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007909 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01007910struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007911{
Olivier Houchard9f6af332018-05-25 14:04:04 +02007912 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007913 enum hlua_exec status;
7914
Christopher Faulet5bc99722018-04-25 10:34:45 +02007915 if (task->thread_mask == MAX_THREADS_MASK)
7916 task_set_affinity(task, tid_bit);
7917
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007918 /* If it is the first call to the task, we must initialize the
7919 * execution timeouts.
7920 */
7921 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007922 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007923
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007924 /* Execute the Lua code. */
7925 status = hlua_ctx_resume(hlua, 1);
7926
7927 switch (status) {
7928 /* finished or yield */
7929 case HLUA_E_OK:
7930 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007931 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02007932 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007933 break;
7934
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01007935 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01007936 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02007937 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007938 break;
7939
7940 /* finished with error. */
7941 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007942 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007943 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007944 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007945 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007946 break;
7947
7948 case HLUA_E_ERR:
7949 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007950 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007951 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02007952 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02007953 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007954 break;
7955 }
Emeric Brun253e53e2017-10-17 18:58:40 +02007956 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007957}
7958
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007959/* This function is an LUA binding that register LUA function to be
7960 * executed after the HAProxy configuration parsing and before the
7961 * HAProxy scheduler starts. This function expect only one LUA
7962 * argument that is a function. This function returns nothing, but
7963 * throws if an error is encountered.
7964 */
7965__LJMP static int hlua_register_init(lua_State *L)
7966{
7967 struct hlua_init_function *init;
7968 int ref;
7969
7970 MAY_LJMP(check_args(L, 1, "register_init"));
7971
7972 ref = MAY_LJMP(hlua_checkfunction(L, 1));
7973
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007974 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007975 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007976 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007977
7978 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02007979 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007980 return 0;
7981}
7982
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007983/* This functio is an LUA binding. It permits to register a task
7984 * executed in parallel of the main HAroxy activity. The task is
7985 * created and it is set in the HAProxy scheduler. It can be called
7986 * from the "init" section, "post init" or during the runtime.
7987 *
7988 * Lua prototype:
7989 *
7990 * <none> core.register_task(<function>)
7991 */
7992static int hlua_register_task(lua_State *L)
7993{
Christopher Faulet5294ec02021-04-12 12:24:47 +02007994 struct hlua *hlua = NULL;
7995 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007996 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01007997 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007998
7999 MAY_LJMP(check_args(L, 1, "register_task"));
8000
8001 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8002
Thierry Fournier75fc0292020-11-28 13:18:56 +01008003 /* Get the reference state. If the reference is NULL, L is the master
8004 * state, otherwise hlua->T is.
8005 */
8006 hlua = hlua_gethlua(L);
8007 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008008 /* we are in runtime processing */
8009 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008010 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008011 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008012 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008013
Willy Tarreaubafbe012017-11-24 17:34:44 +01008014 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008015 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008016 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008017 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008018
Thierry Fournier59f11be2020-11-29 00:37:41 +01008019 /* We are in the common lua state, execute the task anywhere,
8020 * otherwise, inherit the current thread identifier
8021 */
8022 if (state_id == 0)
8023 task = task_new(MAX_THREADS_MASK);
8024 else
8025 task = task_new(tid_bit);
Willy Tarreaue09101e2018-10-16 17:37:12 +02008026 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008027 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008028
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008029 task->context = hlua;
8030 task->process = hlua_process_task;
8031
Thierry Fournier021d9862020-11-28 23:42:03 +01008032 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008033 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008034
8035 /* Restore the function in the stack. */
8036 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8037 hlua->nargs = 0;
8038
8039 /* Schedule task. */
8040 task_schedule(task, now_ms);
8041
8042 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008043
8044 alloc_error:
8045 task_destroy(task);
8046 hlua_ctx_destroy(hlua);
8047 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8048 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008049}
8050
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008051/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8052 * doesn't allow "yield" functions because the HAProxy engine cannot
8053 * resume converters.
8054 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008055static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008056{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008057 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008058 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008059 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008060
Willy Tarreaube508f12016-03-10 11:47:01 +01008061 if (!stream)
8062 return 0;
8063
Willy Tarreau87b09662015-04-03 00:22:06 +02008064 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008065 * Lua context can be not initialized. This behavior
8066 * permits to save performances because a systematic
8067 * Lua initialization cause 5% performances loss.
8068 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008069 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008070 struct hlua *hlua;
8071
8072 hlua = pool_alloc(pool_head_hlua);
8073 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008074 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8075 return 0;
8076 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008077 HLUA_INIT(hlua);
8078 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008079 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008080 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8081 return 0;
8082 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008083 }
8084
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008085 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008086 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008087
8088 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008089 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008090 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8091 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008092 else
8093 error = "critical error";
8094 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008095 return 0;
8096 }
8097
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008098 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008099 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008100 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008101 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008102 return 0;
8103 }
8104
8105 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008106 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008107
8108 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008109 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008110 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008111 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008112 return 0;
8113 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008114 hlua_smp2lua(stream->hlua->T, smp);
8115 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008116
8117 /* push keywords in the stack. */
8118 if (arg_p) {
8119 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008120 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008121 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008122 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008123 return 0;
8124 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008125 hlua_arg2lua(stream->hlua->T, arg_p);
8126 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008127 }
8128 }
8129
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008130 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008131 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008132
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008133 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008134 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008135 }
8136
8137 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008138 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008139 /* finished. */
8140 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008141 /* If the stack is empty, the function fails. */
8142 if (lua_gettop(stream->hlua->T) <= 0)
8143 return 0;
8144
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008145 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008146 hlua_lua2smp(stream->hlua->T, -1, smp);
8147 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008148 return 1;
8149
8150 /* yield. */
8151 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008152 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008153 return 0;
8154
8155 /* finished with error. */
8156 case HLUA_E_ERRMSG:
8157 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008158 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008159 fcn->name, lua_tostring(stream->hlua->T, -1));
8160 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008161 return 0;
8162
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008163 case HLUA_E_ETMOUT:
8164 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8165 return 0;
8166
8167 case HLUA_E_NOMEM:
8168 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8169 return 0;
8170
8171 case HLUA_E_YIELD:
8172 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8173 return 0;
8174
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008175 case HLUA_E_ERR:
8176 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008177 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008178 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008179
8180 default:
8181 return 0;
8182 }
8183}
8184
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008185/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8186 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008187 * resume sample-fetches. This function will be called by the sample
8188 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008189 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008190static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8191 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008192{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008193 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008194 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008195 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008196 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008197
Willy Tarreaube508f12016-03-10 11:47:01 +01008198 if (!stream)
8199 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008200
Willy Tarreau87b09662015-04-03 00:22:06 +02008201 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008202 * Lua context can be not initialized. This behavior
8203 * permits to save performances because a systematic
8204 * Lua initialization cause 5% performances loss.
8205 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008206 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008207 struct hlua *hlua;
8208
8209 hlua = pool_alloc(pool_head_hlua);
8210 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008211 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8212 return 0;
8213 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008214 hlua->T = NULL;
8215 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008216 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008217 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8218 return 0;
8219 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008220 }
8221
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008222 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008223 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008224
8225 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008226 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008227 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8228 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008229 else
8230 error = "critical error";
8231 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008232 return 0;
8233 }
8234
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008235 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008236 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008237 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008238 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008239 return 0;
8240 }
8241
8242 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008243 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008244
8245 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008246 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008247 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008248 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008249 return 0;
8250 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008251 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008252
8253 /* push keywords in the stack. */
8254 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8255 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008256 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008257 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008258 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008259 return 0;
8260 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008261 hlua_arg2lua(stream->hlua->T, arg_p);
8262 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008263 }
8264
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008265 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008266 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008267
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008268 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008269 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008270 }
8271
8272 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008273 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008274 /* finished. */
8275 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008276 /* If the stack is empty, the function fails. */
8277 if (lua_gettop(stream->hlua->T) <= 0)
8278 return 0;
8279
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008280 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008281 hlua_lua2smp(stream->hlua->T, -1, smp);
8282 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008283
8284 /* Set the end of execution flag. */
8285 smp->flags &= ~SMP_F_MAY_CHANGE;
8286 return 1;
8287
8288 /* yield. */
8289 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008290 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008291 return 0;
8292
8293 /* finished with error. */
8294 case HLUA_E_ERRMSG:
8295 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008296 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008297 fcn->name, lua_tostring(stream->hlua->T, -1));
8298 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008299 return 0;
8300
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008301 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008302 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8303 return 0;
8304
8305 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008306 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8307 return 0;
8308
8309 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008310 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8311 return 0;
8312
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008313 case HLUA_E_ERR:
8314 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008315 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008316 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008317
8318 default:
8319 return 0;
8320 }
8321}
8322
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008323/* This function is an LUA binding used for registering
8324 * "sample-conv" functions. It expects a converter name used
8325 * in the haproxy configuration file, and an LUA function.
8326 */
8327__LJMP static int hlua_register_converters(lua_State *L)
8328{
8329 struct sample_conv_kw_list *sck;
8330 const char *name;
8331 int ref;
8332 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008333 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008334 struct sample_conv *sc;
8335 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008336
8337 MAY_LJMP(check_args(L, 2, "register_converters"));
8338
8339 /* First argument : converter name. */
8340 name = MAY_LJMP(luaL_checkstring(L, 1));
8341
8342 /* Second argument : lua function. */
8343 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8344
Thierry Fournierf67442e2020-11-28 20:41:07 +01008345 /* Check if the converter is already registered */
8346 trash = get_trash_chunk();
8347 chunk_printf(trash, "lua.%s", name);
8348 sc = find_sample_conv(trash->area, trash->data);
8349 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008350 fcn = sc->private;
8351 if (fcn->function_ref[hlua_state_id] != -1) {
8352 ha_warning("Trying to register converter 'lua.%s' more than once. "
8353 "This will become a hard error in version 2.5.\n", name);
8354 }
8355 fcn->function_ref[hlua_state_id] = ref;
8356 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008357 }
8358
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008359 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008360 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008361 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008362 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008363 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008364 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008365 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008366
8367 /* Fill fcn. */
8368 fcn->name = strdup(name);
8369 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008370 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008371 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008372
8373 /* List head */
8374 sck->list.n = sck->list.p = NULL;
8375
8376 /* converter keyword. */
8377 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008378 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008379 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008380 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008381
8382 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8383 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008384 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 +01008385 sck->kw[0].val_args = NULL;
8386 sck->kw[0].in_type = SMP_T_STR;
8387 sck->kw[0].out_type = SMP_T_STR;
8388 sck->kw[0].private = fcn;
8389
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008390 /* Register this new converter */
8391 sample_register_convs(sck);
8392
8393 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008394
8395 alloc_error:
8396 release_hlua_function(fcn);
8397 ha_free(&sck);
8398 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8399 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008400}
8401
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008402/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008403 * "sample-fetch" functions. It expects a converter name used
8404 * in the haproxy configuration file, and an LUA function.
8405 */
8406__LJMP static int hlua_register_fetches(lua_State *L)
8407{
8408 const char *name;
8409 int ref;
8410 int len;
8411 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008412 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008413 struct sample_fetch *sf;
8414 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008415
8416 MAY_LJMP(check_args(L, 2, "register_fetches"));
8417
8418 /* First argument : sample-fetch name. */
8419 name = MAY_LJMP(luaL_checkstring(L, 1));
8420
8421 /* Second argument : lua function. */
8422 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8423
Thierry Fournierf67442e2020-11-28 20:41:07 +01008424 /* Check if the sample-fetch is already registered */
8425 trash = get_trash_chunk();
8426 chunk_printf(trash, "lua.%s", name);
8427 sf = find_sample_fetch(trash->area, trash->data);
8428 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008429 fcn = sf->private;
8430 if (fcn->function_ref[hlua_state_id] != -1) {
8431 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8432 "This will become a hard error in version 2.5.\n", name);
8433 }
8434 fcn->function_ref[hlua_state_id] = ref;
8435 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008436 }
8437
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008438 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008439 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008440 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008441 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008442 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008443 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008444 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008445
8446 /* Fill fcn. */
8447 fcn->name = strdup(name);
8448 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008449 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008450 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008451
8452 /* List head */
8453 sfk->list.n = sfk->list.p = NULL;
8454
8455 /* sample-fetch keyword. */
8456 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008457 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008458 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008459 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008460
8461 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8462 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008463 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 +01008464 sfk->kw[0].val_args = NULL;
8465 sfk->kw[0].out_type = SMP_T_STR;
8466 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8467 sfk->kw[0].val = 0;
8468 sfk->kw[0].private = fcn;
8469
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008470 /* Register this new fetch. */
8471 sample_register_fetches(sfk);
8472
8473 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008474
8475 alloc_error:
8476 release_hlua_function(fcn);
8477 ha_free(&sfk);
8478 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8479 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008480}
8481
Christopher Faulet501465d2020-02-26 14:54:16 +01008482/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008483 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008484__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008485{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008486 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008487 unsigned int delay;
8488 unsigned int wakeup_ms;
8489
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008490 /* Get hlua struct, or NULL if we execute from main lua state */
8491 hlua = hlua_gethlua(L);
8492 if (!hlua) {
8493 return 0;
8494 }
8495
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008496 MAY_LJMP(check_args(L, 1, "wake_time"));
8497
8498 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8499 wakeup_ms = tick_add(now_ms, delay);
8500 hlua->wake_time = wakeup_ms;
8501 return 0;
8502}
8503
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008504/* This function is a wrapper to execute each LUA function declared as an action
8505 * wrapper during the initialisation period. This function may return any
8506 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8507 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8508 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008509 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008510static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02008511 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008512{
8513 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008514 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008515 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008516 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008517
8518 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008519 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
8520 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
8521 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
8522 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008523 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008524 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008525 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008526 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008527
Willy Tarreau87b09662015-04-03 00:22:06 +02008528 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008529 * Lua context can be not initialized. This behavior
8530 * permits to save performances because a systematic
8531 * Lua initialization cause 5% performances loss.
8532 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008533 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008534 struct hlua *hlua;
8535
8536 hlua = pool_alloc(pool_head_hlua);
8537 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008538 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008539 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008540 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008541 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008542 HLUA_INIT(hlua);
8543 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008544 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 +01008545 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008546 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008547 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008548 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008549 }
8550
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008551 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008552 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008553
8554 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008555 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008556 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
8557 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008558 else
8559 error = "critical error";
8560 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008561 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008562 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008563 }
8564
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008565 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008566 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008567 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008568 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008569 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008570 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008571 }
8572
8573 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008574 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 +01008575
Willy Tarreau87b09662015-04-03 00:22:06 +02008576 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008577 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008578 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008579 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008580 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008581 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008582 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008583 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008584
8585 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008586 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008587 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008588 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008589 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008590 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008591 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008592 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008593 lua_pushstring(s->hlua->T, *arg);
8594 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008595 }
8596
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008597 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008598 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008599
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008600 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008601 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008602 }
8603
8604 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01008605 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008606 /* finished. */
8607 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008608 /* Catch the return value */
8609 if (lua_gettop(s->hlua->T) > 0)
8610 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008611
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008612 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02008613 if (act_ret == ACT_RET_YIELD) {
8614 if (flags & ACT_OPT_FINAL)
8615 goto err_yield;
8616
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008617 if (dir == SMP_OPT_DIR_REQ)
8618 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8619 s->hlua->wake_time);
8620 else
8621 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8622 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008623 }
8624 goto end;
8625
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008626 /* yield. */
8627 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008628 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008629 if (dir == SMP_OPT_DIR_REQ)
8630 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8631 s->hlua->wake_time);
8632 else
8633 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8634 s->hlua->wake_time);
8635
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008636 /* Some actions can be wake up when a "write" event
8637 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008638 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008639 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02008640 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008641 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008642 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008643 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008644 act_ret = ACT_RET_YIELD;
8645 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008646
8647 /* finished with error. */
8648 case HLUA_E_ERRMSG:
8649 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008650 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008651 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008652 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008653 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008654
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008655 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008656 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008657 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008658
8659 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008660 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008661 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008662
8663 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02008664 err_yield:
8665 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008666 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008667 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008668 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008669
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008670 case HLUA_E_ERR:
8671 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008672 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008673 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008674
8675 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008676 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008677 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008678
8679 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02008680 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008681 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008682 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008683}
8684
Willy Tarreau144f84a2021-03-02 16:09:26 +01008685struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008686{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008687 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008688
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008689 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02008690 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02008691 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008692}
8693
8694static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8695{
8696 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008697 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008698 struct task *task;
8699 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008700 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008701
Willy Tarreaubafbe012017-11-24 17:34:44 +01008702 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008703 if (!hlua) {
8704 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008705 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008706 return 0;
8707 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008708 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008709 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008710 ctx->ctx.hlua_apptcp.flags = 0;
8711
8712 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008713 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008714 if (!task) {
8715 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008716 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008717 return 0;
8718 }
8719 task->nice = 0;
8720 task->context = ctx;
8721 task->process = hlua_applet_wakeup;
8722 ctx->ctx.hlua_apptcp.task = task;
8723
8724 /* In the execution wrappers linked with a stream, the
8725 * Lua context can be not initialized. This behavior
8726 * permits to save performances because a systematic
8727 * Lua initialization cause 5% performances loss.
8728 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008729 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 +02008730 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008731 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008732 return 0;
8733 }
8734
8735 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008736 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008737
8738 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008739 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008740 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8741 error = lua_tostring(hlua->T, -1);
8742 else
8743 error = "critical error";
8744 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008745 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008746 return 0;
8747 }
8748
8749 /* Check stack available size. */
8750 if (!lua_checkstack(hlua->T, 1)) {
8751 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008752 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008753 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008754 return 0;
8755 }
8756
8757 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008758 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008759
8760 /* Create and and push object stream in the stack. */
8761 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
8762 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008763 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008764 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008765 return 0;
8766 }
8767 hlua->nargs = 1;
8768
8769 /* push keywords in the stack. */
8770 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8771 if (!lua_checkstack(hlua->T, 1)) {
8772 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008773 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008774 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008775 return 0;
8776 }
8777 lua_pushstring(hlua->T, *arg);
8778 hlua->nargs++;
8779 }
8780
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008781 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008782
8783 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008784 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01008785 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008786
8787 return 1;
8788}
8789
Willy Tarreau60409db2019-08-21 14:14:50 +02008790void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008791{
8792 struct stream_interface *si = ctx->owner;
8793 struct stream *strm = si_strm(si);
8794 struct channel *res = si_ic(si);
8795 struct act_rule *rule = ctx->rule;
8796 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008797 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008798
8799 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02008800 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
8801 /* eat the whole request */
8802 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008803 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02008804 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008805
8806 /* If the stream is disconnect or closed, ldo nothing. */
8807 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8808 return;
8809
8810 /* Execute the function. */
8811 switch (hlua_ctx_resume(hlua, 1)) {
8812 /* finished. */
8813 case HLUA_E_OK:
8814 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8815
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008816 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02008817 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008818 res->flags |= CF_READ_NULL;
8819 si_shutr(si);
8820 return;
8821
8822 /* yield. */
8823 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01008824 if (hlua->wake_time != TICK_ETERNITY)
8825 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008826 return;
8827
8828 /* finished with error. */
8829 case HLUA_E_ERRMSG:
8830 /* Display log. */
8831 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008832 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008833 lua_pop(hlua->T, 1);
8834 goto error;
8835
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008836 case HLUA_E_ETMOUT:
8837 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008838 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008839 goto error;
8840
8841 case HLUA_E_NOMEM:
8842 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008843 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008844 goto error;
8845
8846 case HLUA_E_YIELD: /* unexpected */
8847 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008848 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008849 goto error;
8850
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008851 case HLUA_E_ERR:
8852 /* Display log. */
8853 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008854 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008855 goto error;
8856
8857 default:
8858 goto error;
8859 }
8860
8861error:
8862
8863 /* For all other cases, just close the stream. */
8864 si_shutw(si);
8865 si_shutr(si);
8866 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8867}
8868
8869static void hlua_applet_tcp_release(struct appctx *ctx)
8870{
Olivier Houchard3f795f72019-04-17 22:51:06 +02008871 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008872 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008873 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008874 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008875}
8876
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008877/* The function returns 1 if the initialisation is complete, 0 if
8878 * an errors occurs and -1 if more data are required for initializing
8879 * the applet.
8880 */
8881static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8882{
8883 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008884 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008885 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008886 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008887 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008888 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008889
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008890 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01008891 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008892 if (!hlua) {
8893 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008894 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008895 return 0;
8896 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008897 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008898 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008899 ctx->ctx.hlua_apphttp.left_bytes = -1;
8900 ctx->ctx.hlua_apphttp.flags = 0;
8901
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01008902 if (txn->req.flags & HTTP_MSGF_VER_11)
8903 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
8904
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008905 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008906 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008907 if (!task) {
8908 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008909 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008910 return 0;
8911 }
8912 task->nice = 0;
8913 task->context = ctx;
8914 task->process = hlua_applet_wakeup;
8915 ctx->ctx.hlua_apphttp.task = task;
8916
8917 /* In the execution wrappers linked with a stream, the
8918 * Lua context can be not initialized. This behavior
8919 * permits to save performances because a systematic
8920 * Lua initialization cause 5% performances loss.
8921 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008922 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 +02008923 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008924 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008925 return 0;
8926 }
8927
8928 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008929 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008930
8931 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008932 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008933 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8934 error = lua_tostring(hlua->T, -1);
8935 else
8936 error = "critical error";
8937 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008938 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008939 return 0;
8940 }
8941
8942 /* Check stack available size. */
8943 if (!lua_checkstack(hlua->T, 1)) {
8944 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008945 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008946 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008947 return 0;
8948 }
8949
8950 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008951 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008952
8953 /* Create and and push object stream in the stack. */
8954 if (!hlua_applet_http_new(hlua->T, ctx)) {
8955 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008956 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008957 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008958 return 0;
8959 }
8960 hlua->nargs = 1;
8961
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008962 /* push keywords in the stack. */
8963 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8964 if (!lua_checkstack(hlua->T, 1)) {
8965 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008966 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008967 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008968 return 0;
8969 }
8970 lua_pushstring(hlua->T, *arg);
8971 hlua->nargs++;
8972 }
8973
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008974 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008975
8976 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008977 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008978
8979 return 1;
8980}
8981
Willy Tarreau60409db2019-08-21 14:14:50 +02008982void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01008983{
8984 struct stream_interface *si = ctx->owner;
8985 struct stream *strm = si_strm(si);
8986 struct channel *req = si_oc(si);
8987 struct channel *res = si_ic(si);
8988 struct act_rule *rule = ctx->rule;
8989 struct proxy *px = strm->be;
8990 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
8991 struct htx *req_htx, *res_htx;
8992
8993 res_htx = htx_from_buf(&res->buf);
8994
8995 /* If the stream is disconnect or closed, ldo nothing. */
8996 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8997 goto out;
8998
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008999 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009000 if (!b_size(&res->buf)) {
9001 si_rx_room_blk(si);
9002 goto out;
9003 }
9004 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009005 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009006 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9007
9008 /* Set the currently running flag. */
9009 if (!HLUA_IS_RUNNING(hlua) &&
9010 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009011 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009012 si_cant_get(si);
9013 goto out;
9014 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009015 }
9016
9017 /* Executes The applet if it is not done. */
9018 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9019
9020 /* Execute the function. */
9021 switch (hlua_ctx_resume(hlua, 1)) {
9022 /* finished. */
9023 case HLUA_E_OK:
9024 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9025 break;
9026
9027 /* yield. */
9028 case HLUA_E_AGAIN:
9029 if (hlua->wake_time != TICK_ETERNITY)
9030 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009031 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009032
9033 /* finished with error. */
9034 case HLUA_E_ERRMSG:
9035 /* Display log. */
9036 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009037 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009038 lua_pop(hlua->T, 1);
9039 goto error;
9040
9041 case HLUA_E_ETMOUT:
9042 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009043 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009044 goto error;
9045
9046 case HLUA_E_NOMEM:
9047 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009048 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009049 goto error;
9050
9051 case HLUA_E_YIELD: /* unexpected */
9052 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009053 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009054 goto error;
9055
9056 case HLUA_E_ERR:
9057 /* Display log. */
9058 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009059 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009060 goto error;
9061
9062 default:
9063 goto error;
9064 }
9065 }
9066
9067 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009068 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9069 goto done;
9070
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009071 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9072 goto error;
9073
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009074 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
9075 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009076 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9077 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009078 }
9079
9080 done:
9081 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009082 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009083 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009084 si_shutr(si);
9085 }
9086
9087 /* eat the whole request */
9088 if (co_data(req)) {
9089 req_htx = htx_from_buf(&req->buf);
9090 co_htx_skip(req, req_htx, co_data(req));
9091 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009092 }
9093 }
9094
9095 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009096 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009097 return;
9098
9099 error:
9100
9101 /* If we are in HTTP mode, and we are not send any
9102 * data, return a 500 server error in best effort:
9103 * if there is no room available in the buffer,
9104 * just close the connection.
9105 */
9106 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009107 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009108
9109 channel_erase(res);
9110 res->buf.data = b_data(err);
9111 memcpy(res->buf.area, b_head(err), b_data(err));
9112 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009113 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009114 }
9115 if (!(strm->flags & SF_ERR_MASK))
9116 strm->flags |= SF_ERR_RESOURCE;
9117 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9118 goto done;
9119}
9120
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009121static void hlua_applet_http_release(struct appctx *ctx)
9122{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009123 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009124 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009125 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009126 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009127}
9128
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009129/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009130 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009131 *
9132 * This function can fail with an abort() due to an Lua critical error.
9133 * We are in the configuration parsing process of HAProxy, this abort() is
9134 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009135 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009136static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9137 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009138{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009139 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009140 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009141
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009142 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009143 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009144 if (!rule->arg.hlua_rule) {
9145 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009146 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009147 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009148
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009149 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009150 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9151 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009152 if (!rule->arg.hlua_rule->args) {
9153 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009154 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009155 }
9156
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009157 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009158 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009159
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009160 /* Expect some arguments */
9161 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009162 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009163 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009164 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009165 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009166 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009167 if (!rule->arg.hlua_rule->args[i]) {
9168 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009169 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009170 }
9171 (*cur_arg)++;
9172 }
9173 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009174
Thierry FOURNIER42148732015-09-02 17:17:33 +02009175 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009176 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009177 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009178
9179 error:
9180 if (rule->arg.hlua_rule) {
9181 if (rule->arg.hlua_rule->args) {
9182 for (i = 0; i < fcn->nargs; i++)
9183 ha_free(&rule->arg.hlua_rule->args[i]);
9184 ha_free(&rule->arg.hlua_rule->args);
9185 }
9186 ha_free(&rule->arg.hlua_rule);
9187 }
9188 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009189}
9190
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009191static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9192 struct act_rule *rule, char **err)
9193{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009194 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009195
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009196 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009197 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009198 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009199 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009200 * the call of this analyzer.
9201 */
9202 if (rule->from != ACT_F_HTTP_REQ) {
9203 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9204 return ACT_RET_PRS_ERR;
9205 }
9206
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009207 /* Memory for the rule. */
9208 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9209 if (!rule->arg.hlua_rule) {
9210 memprintf(err, "out of memory error");
9211 return ACT_RET_PRS_ERR;
9212 }
9213
9214 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009215 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009216
9217 /* TODO: later accept arguments. */
9218 rule->arg.hlua_rule->args = NULL;
9219
9220 /* Add applet pointer in the rule. */
9221 rule->applet.obj_type = OBJ_TYPE_APPLET;
9222 rule->applet.name = fcn->name;
9223 rule->applet.init = hlua_applet_http_init;
9224 rule->applet.fct = hlua_applet_http_fct;
9225 rule->applet.release = hlua_applet_http_release;
9226 rule->applet.timeout = hlua_timeout_applet;
9227
9228 return ACT_RET_PRS_OK;
9229}
9230
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009231/* This function is an LUA binding used for registering
9232 * "sample-conv" functions. It expects a converter name used
9233 * in the haproxy configuration file, and an LUA function.
9234 */
9235__LJMP static int hlua_register_action(lua_State *L)
9236{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009237 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009238 const char *name;
9239 int ref;
9240 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009241 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009242 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009243 struct buffer *trash;
9244 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009245
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009246 /* Initialise the number of expected arguments at 0. */
9247 nargs = 0;
9248
9249 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9250 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009251
9252 /* First argument : converter name. */
9253 name = MAY_LJMP(luaL_checkstring(L, 1));
9254
9255 /* Second argument : environment. */
9256 if (lua_type(L, 2) != LUA_TTABLE)
9257 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9258
9259 /* Third argument : lua function. */
9260 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9261
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009262 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009263 if (lua_gettop(L) >= 4)
9264 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9265
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009266 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009267 lua_pushnil(L);
9268 while (lua_next(L, 2) != 0) {
9269 if (lua_type(L, -1) != LUA_TSTRING)
9270 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9271
Thierry Fournierf67442e2020-11-28 20:41:07 +01009272 /* Check if action exists */
9273 trash = get_trash_chunk();
9274 chunk_printf(trash, "lua.%s", name);
9275 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9276 akw = tcp_req_cont_action(trash->area);
9277 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9278 akw = tcp_res_cont_action(trash->area);
9279 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9280 akw = action_http_req_custom(trash->area);
9281 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9282 akw = action_http_res_custom(trash->area);
9283 } else {
9284 akw = NULL;
9285 }
9286 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009287 fcn = akw->private;
9288 if (fcn->function_ref[hlua_state_id] != -1) {
9289 ha_warning("Trying to register action 'lua.%s' more than once. "
9290 "This will become a hard error in version 2.5.\n", name);
9291 }
9292 fcn->function_ref[hlua_state_id] = ref;
9293
9294 /* pop the environment string. */
9295 lua_pop(L, 1);
9296 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009297 }
9298
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009299 /* Check required environment. Only accepted "http" or "tcp". */
9300 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009301 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009302 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009303 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009304 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009305 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009306 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009307
9308 /* Fill fcn. */
9309 fcn->name = strdup(name);
9310 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009311 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009312 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009313
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009314 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009315 fcn->nargs = nargs;
9316
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009317 /* List head */
9318 akl->list.n = akl->list.p = NULL;
9319
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009320 /* action keyword. */
9321 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009322 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009323 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009324 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009325
9326 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9327
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009328 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009329 akl->kw[0].private = fcn;
9330 akl->kw[0].parse = action_register_lua;
9331
9332 /* select the action registering point. */
9333 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9334 tcp_req_cont_keywords_register(akl);
9335 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9336 tcp_res_cont_keywords_register(akl);
9337 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9338 http_req_keywords_register(akl);
9339 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9340 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009341 else {
9342 release_hlua_function(fcn);
9343 if (akl)
9344 ha_free((char **)&(akl->kw[0].kw));
9345 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009346 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009347 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9348 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009349 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009350
9351 /* pop the environment string. */
9352 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009353
9354 /* reset for next loop */
9355 akl = NULL;
9356 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009357 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009358 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009359
9360 alloc_error:
9361 release_hlua_function(fcn);
9362 ha_free(&akl);
9363 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9364 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009365}
9366
9367static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9368 struct act_rule *rule, char **err)
9369{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009370 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009371
Christopher Faulet280f85b2019-07-15 15:02:04 +02009372 if (px->mode == PR_MODE_HTTP) {
9373 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009374 return ACT_RET_PRS_ERR;
9375 }
9376
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009377 /* Memory for the rule. */
9378 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9379 if (!rule->arg.hlua_rule) {
9380 memprintf(err, "out of memory error");
9381 return ACT_RET_PRS_ERR;
9382 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009383
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009384 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009385 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009386
9387 /* TODO: later accept arguments. */
9388 rule->arg.hlua_rule->args = NULL;
9389
9390 /* Add applet pointer in the rule. */
9391 rule->applet.obj_type = OBJ_TYPE_APPLET;
9392 rule->applet.name = fcn->name;
9393 rule->applet.init = hlua_applet_tcp_init;
9394 rule->applet.fct = hlua_applet_tcp_fct;
9395 rule->applet.release = hlua_applet_tcp_release;
9396 rule->applet.timeout = hlua_timeout_applet;
9397
9398 return 0;
9399}
9400
9401/* This function is an LUA binding used for registering
9402 * "sample-conv" functions. It expects a converter name used
9403 * in the haproxy configuration file, and an LUA function.
9404 */
9405__LJMP static int hlua_register_service(lua_State *L)
9406{
9407 struct action_kw_list *akl;
9408 const char *name;
9409 const char *env;
9410 int ref;
9411 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009412 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009413 struct buffer *trash;
9414 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009415
9416 MAY_LJMP(check_args(L, 3, "register_service"));
9417
9418 /* First argument : converter name. */
9419 name = MAY_LJMP(luaL_checkstring(L, 1));
9420
9421 /* Second argument : environment. */
9422 env = MAY_LJMP(luaL_checkstring(L, 2));
9423
9424 /* Third argument : lua function. */
9425 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9426
Thierry Fournierf67442e2020-11-28 20:41:07 +01009427 /* Check for service already registered */
9428 trash = get_trash_chunk();
9429 chunk_printf(trash, "lua.%s", name);
9430 akw = service_find(trash->area);
9431 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009432 fcn = akw->private;
9433 if (fcn->function_ref[hlua_state_id] != -1) {
9434 ha_warning("Trying to register service 'lua.%s' more than once. "
9435 "This will become a hard error in version 2.5.\n", name);
9436 }
9437 fcn->function_ref[hlua_state_id] = ref;
9438 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009439 }
9440
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009441 /* Allocate and fill the sample fetch keyword struct. */
9442 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9443 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009444 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009445 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009446 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009447 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009448
9449 /* Fill fcn. */
9450 len = strlen("<lua.>") + strlen(name) + 1;
9451 fcn->name = calloc(1, len);
9452 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009453 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009454 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009455 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009456
9457 /* List head */
9458 akl->list.n = akl->list.p = NULL;
9459
9460 /* converter keyword. */
9461 len = strlen("lua.") + strlen(name) + 1;
9462 akl->kw[0].kw = calloc(1, len);
9463 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009464 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009465
9466 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9467
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009468 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009469 if (strcmp(env, "tcp") == 0)
9470 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009471 else if (strcmp(env, "http") == 0)
9472 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009473 else {
9474 release_hlua_function(fcn);
9475 if (akl)
9476 ha_free((char **)&(akl->kw[0].kw));
9477 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009478 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009479 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009480 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009481
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009482 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009483 akl->kw[0].private = fcn;
9484
9485 /* End of array. */
9486 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9487
9488 /* Register this new converter */
9489 service_keywords_register(akl);
9490
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009491 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009492
9493 alloc_error:
9494 release_hlua_function(fcn);
9495 ha_free(&akl);
9496 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9497 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009498}
9499
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009500/* This function initialises Lua cli handler. It copies the
9501 * arguments in the Lua stack and create channel IO objects.
9502 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02009503static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009504{
9505 struct hlua *hlua;
9506 struct hlua_function *fcn;
9507 int i;
9508 const char *error;
9509
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009510 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009511 appctx->ctx.hlua_cli.fcn = private;
9512
Willy Tarreaubafbe012017-11-24 17:34:44 +01009513 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009514 if (!hlua) {
9515 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009516 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009517 }
9518 HLUA_INIT(hlua);
9519 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009520
9521 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05009522 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009523 * applet_http. It is absolutely compatible.
9524 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01009525 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009526 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01009527 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009528 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009529 }
9530 appctx->ctx.hlua_cli.task->nice = 0;
9531 appctx->ctx.hlua_cli.task->context = appctx;
9532 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
9533
9534 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +01009535 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 +01009536 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009537 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009538 }
9539
9540 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009541 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009542 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9543 error = lua_tostring(hlua->T, -1);
9544 else
9545 error = "critical error";
9546 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
9547 goto error;
9548 }
9549
9550 /* Check stack available size. */
9551 if (!lua_checkstack(hlua->T, 2)) {
9552 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9553 goto error;
9554 }
9555
9556 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009557 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009558
9559 /* Once the arguments parsed, the CLI is like an AppletTCP,
9560 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009561 */
9562 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
9563 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9564 goto error;
9565 }
9566 hlua->nargs = 1;
9567
9568 /* push keywords in the stack. */
9569 for (i = 0; *args[i]; i++) {
9570 /* Check stack available size. */
9571 if (!lua_checkstack(hlua->T, 1)) {
9572 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9573 goto error;
9574 }
9575 lua_pushstring(hlua->T, args[i]);
9576 hlua->nargs++;
9577 }
9578
9579 /* We must initialize the execution timeouts. */
9580 hlua->max_time = hlua_timeout_session;
9581
9582 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009583 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009584
9585 /* It's ok */
9586 return 0;
9587
9588 /* It's not ok. */
9589error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009590 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009591 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009592 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009593 return 1;
9594}
9595
9596static int hlua_cli_io_handler_fct(struct appctx *appctx)
9597{
9598 struct hlua *hlua;
9599 struct stream_interface *si;
9600 struct hlua_function *fcn;
9601
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009602 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009603 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01009604 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009605
9606 /* If the stream is disconnect or closed, ldo nothing. */
9607 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9608 return 1;
9609
9610 /* Execute the function. */
9611 switch (hlua_ctx_resume(hlua, 1)) {
9612
9613 /* finished. */
9614 case HLUA_E_OK:
9615 return 1;
9616
9617 /* yield. */
9618 case HLUA_E_AGAIN:
9619 /* We want write. */
9620 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01009621 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009622 /* Set the timeout. */
9623 if (hlua->wake_time != TICK_ETERNITY)
9624 task_schedule(hlua->task, hlua->wake_time);
9625 return 0;
9626
9627 /* finished with error. */
9628 case HLUA_E_ERRMSG:
9629 /* Display log. */
9630 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
9631 fcn->name, lua_tostring(hlua->T, -1));
9632 lua_pop(hlua->T, 1);
9633 return 1;
9634
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009635 case HLUA_E_ETMOUT:
9636 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
9637 fcn->name);
9638 return 1;
9639
9640 case HLUA_E_NOMEM:
9641 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
9642 fcn->name);
9643 return 1;
9644
9645 case HLUA_E_YIELD: /* unexpected */
9646 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
9647 fcn->name);
9648 return 1;
9649
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009650 case HLUA_E_ERR:
9651 /* Display log. */
9652 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
9653 fcn->name);
9654 return 1;
9655
9656 default:
9657 return 1;
9658 }
9659
9660 return 1;
9661}
9662
9663static void hlua_cli_io_release_fct(struct appctx *appctx)
9664{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009665 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009666 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009667}
9668
9669/* This function is an LUA binding used for registering
9670 * new keywords in the cli. It expects a list of keywords
9671 * which are the "path". It is limited to 5 keywords. A
9672 * description of the command, a function to be executed
9673 * for the parsing and a function for io handlers.
9674 */
9675__LJMP static int hlua_register_cli(lua_State *L)
9676{
9677 struct cli_kw_list *cli_kws;
9678 const char *message;
9679 int ref_io;
9680 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009681 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009682 int index;
9683 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009684 struct buffer *trash;
9685 const char *kw[5];
9686 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009687 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009688
9689 MAY_LJMP(check_args(L, 3, "register_cli"));
9690
9691 /* First argument : an array of maximum 5 keywords. */
9692 if (!lua_istable(L, 1))
9693 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
9694
9695 /* Second argument : string with contextual message. */
9696 message = MAY_LJMP(luaL_checkstring(L, 2));
9697
9698 /* Third and fourth argument : lua function. */
9699 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
9700
Thierry Fournierf67442e2020-11-28 20:41:07 +01009701 /* Check for CLI service already registered */
9702 trash = get_trash_chunk();
9703 index = 0;
9704 lua_pushnil(L);
9705 memset(kw, 0, sizeof(kw));
9706 while (lua_next(L, 1) != 0) {
9707 if (index >= CLI_PREFIX_KW_NB)
9708 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
9709 if (lua_type(L, -1) != LUA_TSTRING)
9710 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
9711 kw[index] = lua_tostring(L, -1);
9712 if (index == 0)
9713 chunk_printf(trash, "%s", kw[index]);
9714 else
9715 chunk_appendf(trash, " %s", kw[index]);
9716 index++;
9717 lua_pop(L, 1);
9718 }
9719 cli_kw = cli_find_kw_exact((char **)kw);
9720 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009721 fcn = cli_kw->private;
9722 if (fcn->function_ref[hlua_state_id] != -1) {
9723 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
9724 "This will become a hard error in version 2.5.\n", trash->area);
9725 }
9726 fcn->function_ref[hlua_state_id] = ref_io;
9727 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009728 }
9729
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009730 /* Allocate and fill the sample fetch keyword struct. */
9731 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009732 if (!cli_kws) {
9733 errmsg = "Lua out of memory error.";
9734 goto error;
9735 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009736 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009737 if (!fcn) {
9738 errmsg = "Lua out of memory error.";
9739 goto error;
9740 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009741
9742 /* Fill path. */
9743 index = 0;
9744 lua_pushnil(L);
9745 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009746 if (index >= 5) {
9747 errmsg = "1st argument must be a table with a maximum of 5 entries";
9748 goto error;
9749 }
9750 if (lua_type(L, -1) != LUA_TSTRING) {
9751 errmsg = "1st argument must be a table filled with strings";
9752 goto error;
9753 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009754 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009755 if (!cli_kws->kw[0].str_kw[index]) {
9756 errmsg = "Lua out of memory error.";
9757 goto error;
9758 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009759 index++;
9760 lua_pop(L, 1);
9761 }
9762
9763 /* Copy help message. */
9764 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009765 if (!cli_kws->kw[0].usage) {
9766 errmsg = "Lua out of memory error.";
9767 goto error;
9768 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009769
9770 /* Fill fcn io handler. */
9771 len = strlen("<lua.cli>") + 1;
9772 for (i = 0; i < index; i++)
9773 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
9774 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009775 if (!fcn->name) {
9776 errmsg = "Lua out of memory error.";
9777 goto error;
9778 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009779 strncat((char *)fcn->name, "<lua.cli", len);
9780 for (i = 0; i < index; i++) {
9781 strncat((char *)fcn->name, ".", len);
9782 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
9783 }
9784 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +01009785 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009786
9787 /* Fill last entries. */
9788 cli_kws->kw[0].private = fcn;
9789 cli_kws->kw[0].parse = hlua_cli_parse_fct;
9790 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
9791 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
9792
9793 /* Register this new converter */
9794 cli_register_kw(cli_kws);
9795
9796 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009797
9798 error:
9799 release_hlua_function(fcn);
9800 if (cli_kws) {
9801 for (i = 0; i < index; i++)
9802 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
9803 ha_free((char **)&(cli_kws->kw[0].usage));
9804 }
9805 ha_free(&cli_kws);
9806 WILL_LJMP(luaL_error(L, errmsg));
9807 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009808}
9809
Christopher Faulet69c581a2021-05-31 08:54:04 +02009810static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
9811{
9812 struct hlua_flt_config *conf = fconf->conf;
9813 lua_State *L;
9814 int error, pos, state_id, flt_ref;
9815
9816 state_id = reg_flt_to_stack_id(conf->reg);
9817 L = hlua_states[state_id];
9818 pos = lua_gettop(L);
9819
9820 /* The filter parsing function */
9821 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
9822
9823 /* Push the filter class on the stack and resolve all callbacks */
9824 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
9825
9826 /* Duplicate the filter class so each filter will have its own copy */
9827 lua_newtable(L);
9828 lua_pushnil(L);
9829
9830 while (lua_next(L, pos+2)) {
9831 lua_pushvalue(L, -2);
9832 lua_insert(L, -2);
9833 lua_settable(L, -4);
9834 }
9835 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
9836
9837 /* Remove the original lua filter class from the stack */
9838 lua_pop(L, 1);
9839
9840 /* Push the copy on the stack */
9841 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
9842
9843 /* extra args are pushed in a table */
9844 lua_newtable(L);
9845 for (pos = 0; conf->args[pos]; pos++) {
9846 /* Check stack available size. */
9847 if (!lua_checkstack(L, 1)) {
9848 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
9849 goto error;
9850 }
9851 lua_pushstring(L, conf->args[pos]);
9852 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
9853 }
9854
9855 error = lua_pcall(L, 2, LUA_MULTRET, 0);
9856 switch (error) {
9857 case LUA_OK:
9858 /* replace the filter ref */
9859 conf->ref[state_id] = flt_ref;
9860 break;
9861 case LUA_ERRRUN:
9862 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
9863 goto error;
9864 case LUA_ERRMEM:
9865 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
9866 goto error;
9867 case LUA_ERRERR:
9868 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
9869 goto error;
9870#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
9871 case LUA_ERRGCMM:
9872 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
9873 goto error;
9874#endif
9875 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05009876 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +02009877 goto error;
9878 }
9879
9880 lua_settop(L, 0);
9881 return 0;
9882
9883 error:
9884 lua_settop(L, 0);
9885 return -1;
9886}
9887
9888static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
9889{
9890 struct hlua_flt_config *conf = fconf->conf;
9891 lua_State *L;
9892 int state_id;
9893
9894 if (!conf)
9895 return;
9896
9897 state_id = reg_flt_to_stack_id(conf->reg);
9898 L = hlua_states[state_id];
9899 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
9900}
9901
9902static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
9903{
9904 struct hlua_flt_config *conf = fconf->conf;
9905 int state_id = reg_flt_to_stack_id(conf->reg);
9906
9907 /* Rely on per-thread init for global scripts */
9908 if (!state_id)
9909 return hlua_filter_init_per_thread(px, fconf);
9910 return 0;
9911}
9912
9913static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
9914{
9915
9916 if (fconf->conf) {
9917 struct hlua_flt_config *conf = fconf->conf;
9918 int state_id = reg_flt_to_stack_id(conf->reg);
9919 int pos;
9920
9921 /* Rely on per-thread deinit for global scripts */
9922 if (!state_id)
9923 hlua_filter_deinit_per_thread(px, fconf);
9924
9925 for (pos = 0; conf->args[pos]; pos++)
9926 free(conf->args[pos]);
9927 free(conf->args);
9928 }
9929 ha_free(&fconf->conf);
9930 ha_free((char **)&fconf->id);
9931 ha_free(&fconf->ops);
9932}
9933
9934static int hlua_filter_new(struct stream *s, struct filter *filter)
9935{
9936 struct hlua_flt_config *conf = FLT_CONF(filter);
9937 struct hlua_flt_ctx *flt_ctx = NULL;
9938 int ret = 1;
9939
9940 /* In the execution wrappers linked with a stream, the
9941 * Lua context can be not initialized. This behavior
9942 * permits to save performances because a systematic
9943 * Lua initialization cause 5% performances loss.
9944 */
9945 if (!s->hlua) {
9946 struct hlua *hlua;
9947
9948 hlua = pool_alloc(pool_head_hlua);
9949 if (!hlua) {
9950 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9951 conf->reg->name);
9952 ret = 0;
9953 goto end;
9954 }
9955 HLUA_INIT(hlua);
9956 s->hlua = hlua;
9957 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9958 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
9959 conf->reg->name);
9960 ret = 0;
9961 goto end;
9962 }
9963 }
9964
9965 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
9966 if (!flt_ctx) {
9967 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9968 conf->reg->name);
9969 ret = 0;
9970 goto end;
9971 }
9972 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
9973 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
9974 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
9975 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9976 conf->reg->name);
9977 ret = 0;
9978 goto end;
9979 }
9980 HLUA_INIT(flt_ctx->hlua[0]);
9981 HLUA_INIT(flt_ctx->hlua[1]);
9982 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
9983 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
9984 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
9985 conf->reg->name);
9986 ret = 0;
9987 goto end;
9988 }
9989
9990 if (!HLUA_IS_RUNNING(s->hlua)) {
9991 /* The following Lua calls can fail. */
9992 if (!SET_SAFE_LJMP(s->hlua)) {
9993 const char *error;
9994
9995 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9996 error = lua_tostring(s->hlua->T, -1);
9997 else
9998 error = "critical error";
9999 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10000 ret = 0;
10001 goto end;
10002 }
10003
10004 /* Check stack size. */
10005 if (!lua_checkstack(s->hlua->T, 1)) {
10006 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010007 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010008 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);