blob: ee48323d55551eab4b8215f7086206b92deffd23 [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 Tarreau55542642021-10-08 09:33:24 +020035#include <haproxy/clock.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020036#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020037#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020038#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020039#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020040#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020041#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020042#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020043#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020044#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020045#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020046#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020047#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020048#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020049#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020050#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020051#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020052#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020053#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010054#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020055#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020056#include <haproxy/ssl_ckch.h>
57#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020058#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020059#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020060#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020061#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020062#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020063#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020064#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020065#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020066#include <haproxy/xref.h>
67
Thierry FOURNIER380d0932015-01-23 14:27:52 +010068
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010069/* Lua uses longjmp to perform yield or throwing errors. This
70 * macro is used only for identifying the function that can
71 * not return because a longjmp is executed.
72 * __LJMP marks a prototype of hlua file that can use longjmp.
73 * WILL_LJMP() marks an lua function that will use longjmp.
74 * MAY_LJMP() marks an lua function that may use longjmp.
75 */
76#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020077#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010078#define MAY_LJMP(func) func
79
Thierry FOURNIERbabae282015-09-17 11:36:37 +020080/* This couple of function executes securely some Lua calls outside of
81 * the lua runtime environment. Each Lua call can return a longjmp
82 * if it encounter a memory error.
83 *
84 * Lua documentation extract:
85 *
86 * If an error happens outside any protected environment, Lua calls
87 * a panic function (see lua_atpanic) and then calls abort, thus
88 * exiting the host application. Your panic function can avoid this
89 * exit by never returning (e.g., doing a long jump to your own
90 * recovery point outside Lua).
91 *
92 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010093 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020094 * stack. However, there is no guarantee about stack space. To push
95 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010096 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020097 *
98 * We must check all the Lua entry point. This includes:
99 * - The include/proto/hlua.h exported functions
100 * - the task wrapper function
101 * - The action wrapper function
102 * - The converters wrapper function
103 * - The sample-fetch wrapper functions
104 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500105 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800106 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200107 *
108 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
109 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
110 * because they must be exists in the program stack when the longjmp
111 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200112 *
113 * Note that the Lua processing is not really thread safe. It provides
114 * heavy system which consists to add our own lock function in the Lua
115 * code and recompile the library. This system will probably not accepted
116 * by maintainers of various distribs.
117 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500118 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200119 * quick looking on the Lua sources displays a lua_lock() a the start
120 * of function and a lua_unlock() at the end of the function. So I
121 * conclude that the Lua thread safe mode just perform a mutex around
122 * all execution. So I prefer to do this in the HAProxy code, it will be
123 * easier for distro maintainers.
124 *
125 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
126 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
127 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200128 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100129__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200130THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200131static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200132static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200133
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100134/* This is the chained list of struct hlua_function referenced
135 * for haproxy action, sample-fetches, converters, cli and
136 * applet bindings. It is used for a post-initialisation control.
137 */
138static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
139
Thierry Fournierc7492592020-11-28 23:57:24 +0100140/* This variable is used only during initialization to identify the Lua state
141 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
142 * states dedicated to each thread (in this case hlua_state_id==tid+1).
143 */
144static int hlua_state_id;
145
Thierry Fournier59f11be2020-11-29 00:37:41 +0100146/* This is a NULL-terminated list of lua file which are referenced to load per thread */
147static char **per_thread_load = NULL;
148
149lua_State *hlua_init_state(int thread_id);
150
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200151/* This function takes the Lua global lock. Keep this function's visibility
152 * global so that it can appear in stack dumps and performance profiles!
153 */
154void lua_take_global_lock()
155{
156 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
157}
158
159static inline void lua_drop_global_lock()
160{
161 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
162}
163
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100164#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200165 ({ \
166 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100167 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200168 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200169 if (setjmp(safe_ljmp_env) != 0) { \
170 lua_atpanic(__L, hlua_panic_safe); \
171 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100172 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200173 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200174 } else { \
175 lua_atpanic(__L, hlua_panic_ljmp); \
176 ret = 1; \
177 } \
178 ret; \
179 })
180
181/* If we are the last function catching Lua errors, we
182 * must reset the panic function.
183 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100184#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200185 do { \
186 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100187 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200188 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200189 } while(0)
190
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100191#define SET_SAFE_LJMP(__HLUA) \
192 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
193
194#define RESET_SAFE_LJMP(__HLUA) \
195 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
196
197#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100198 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100199
200#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100201 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100202
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200203/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200204#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100205/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200206#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200207/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100208#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100209#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200210
Thierry Fournierafc63e22020-11-28 17:06:51 +0100211/* The main Lua execution context. The 0 index is the
212 * common state shared by all threads.
213 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100214static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100215
Christopher Fauletc404f112020-02-26 15:03:09 +0100216#define HLUA_FLT_CB_FINAL 0x00000001
217#define HLUA_FLT_CB_RETVAL 0x00000002
218#define HLUA_FLT_CB_ARG_CHN 0x00000004
219#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
220
Christopher Faulet9f55a502020-02-25 15:21:02 +0100221#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
222
Christopher Faulet69c581a2021-05-31 08:54:04 +0200223struct hlua_reg_filter {
224 char *name;
225 int flt_ref[MAX_THREADS + 1];
226 int fun_ref[MAX_THREADS + 1];
227 struct list l;
228};
229
230struct hlua_flt_config {
231 struct hlua_reg_filter *reg;
232 int ref[MAX_THREADS + 1];
233 char **args;
234};
235
236struct hlua_flt_ctx {
237 int ref; /* ref to the filter lua object */
238 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
239 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
240 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
241 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
242};
243
244DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
245
Christopher Faulet9f55a502020-02-25 15:21:02 +0100246static int hlua_filter_from_payload(struct filter *filter);
247
Christopher Faulet69c581a2021-05-31 08:54:04 +0200248/* This is the chained list of struct hlua_flt referenced
249 * for haproxy filters. It is used for a post-initialisation control.
250 */
251static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
252
253
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100254/* This is the memory pool containing struct lua for applets
255 * (including cli).
256 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100257DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100258
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100259/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100260static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100261static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100262#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100263static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100264#endif
265
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100266/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100267struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100268
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100269/* The following variables contains the reference of the different
270 * Lua classes. These references are useful for identify metadata
271 * associated with an object.
272 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100273static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100274static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100275static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100276static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100277static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100278static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100279static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200280static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200281static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200282static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200283static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100284static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100285
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100286/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200287 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100288 * short timeout. Lua linked with tasks doesn't have a timeout
289 * because a task may remain alive during all the haproxy execution.
290 */
291static unsigned int hlua_timeout_session = 4000; /* session timeout. */
292static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200293static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100294
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100295/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
296 * it is used for preventing infinite loops.
297 *
298 * I test the scheer with an infinite loop containing one incrementation
299 * and one test. I run this loop between 10 seconds, I raise a ceil of
300 * 710M loops from one interrupt each 9000 instructions, so I fix the value
301 * to one interrupt each 10 000 instructions.
302 *
303 * configured | Number of
304 * instructions | loops executed
305 * between two | in milions
306 * forced yields |
307 * ---------------+---------------
308 * 10 | 160
309 * 500 | 670
310 * 1000 | 680
311 * 5000 | 700
312 * 7000 | 700
313 * 8000 | 700
314 * 9000 | 710 <- ceil
315 * 10000 | 710
316 * 100000 | 710
317 * 1000000 | 710
318 *
319 */
320static unsigned int hlua_nb_instruction = 10000;
321
Willy Tarreaucdb53462020-12-02 12:12:00 +0100322/* Descriptor for the memory allocation state. The limit is pre-initialised to
323 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
324 * is replaced with ~0 during post_init after everything was loaded. This way
325 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
326 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100327 */
328struct hlua_mem_allocator {
329 size_t allocated;
330 size_t limit;
331};
332
Willy Tarreaucdb53462020-12-02 12:12:00 +0100333static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100334
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100335/* These functions converts types between HAProxy internal args or
336 * sample and LUA types. Another function permits to check if the
337 * LUA stack contains arguments according with an required ARG_T
338 * format.
339 */
340static int hlua_arg2lua(lua_State *L, const struct arg *arg);
341static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100342__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100343 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100344static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100345static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100346static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
347
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100348__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200349
Thierry Fournier59f11be2020-11-29 00:37:41 +0100350struct prepend_path {
351 struct list l;
352 char *type;
353 char *path;
354};
355
356static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
357
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200358#define SEND_ERR(__be, __fmt, __args...) \
359 do { \
360 send_log(__be, LOG_ERR, __fmt, ## __args); \
361 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100362 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200363 } while (0)
364
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100365static inline struct hlua_function *new_hlua_function()
366{
367 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100368 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100369
370 fcn = calloc(1, sizeof(*fcn));
371 if (!fcn)
372 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200373 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100374 for (i = 0; i < MAX_THREADS + 1; i++)
375 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100376 return fcn;
377}
378
Christopher Fauletdda44442021-04-12 14:05:43 +0200379static inline void release_hlua_function(struct hlua_function *fcn)
380{
381 if (!fcn)
382 return;
383 if (fcn->name)
384 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200385 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200386 ha_free(&fcn);
387}
388
Thierry Fournierc7492592020-11-28 23:57:24 +0100389/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
390static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
391{
392 if (fcn->function_ref[0] == -1)
393 return tid + 1;
394 return 0;
395}
396
Christopher Faulet69c581a2021-05-31 08:54:04 +0200397/* Create a new registered filter. Only its name is filled */
398static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
399{
400 struct hlua_reg_filter *reg_flt;
401 int i;
402
403 reg_flt = calloc(1, sizeof(*reg_flt));
404 if (!reg_flt)
405 return NULL;
406 reg_flt->name = strdup(name);
407 if (!reg_flt->name) {
408 free(reg_flt);
409 return NULL;
410 }
411 LIST_APPEND(&referenced_filters, &reg_flt->l);
412 for (i = 0; i < MAX_THREADS + 1; i++) {
413 reg_flt->flt_ref[i] = -1;
414 reg_flt->fun_ref[i] = -1;
415 }
416 return reg_flt;
417}
418
419/* Release a registered filter */
420static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
421{
422 if (!reg_flt)
423 return;
424 if (reg_flt->name)
425 ha_free(&reg_flt->name);
426 LIST_DELETE(&reg_flt->l);
427 ha_free(&reg_flt);
428}
429
430/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
431static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
432{
433 if (reg_flt->fun_ref[0] == -1)
434 return tid + 1;
435 return 0;
436}
437
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100438/* Used to check an Lua function type in the stack. It creates and
439 * returns a reference of the function. This function throws an
440 * error if the rgument is not a "function".
441 */
442__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
443{
444 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100445 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100446 WILL_LJMP(luaL_argerror(L, argno, msg));
447 }
448 lua_pushvalue(L, argno);
449 return luaL_ref(L, LUA_REGISTRYINDEX);
450}
451
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100452/* Used to check an Lua table type in the stack. It creates and
453 * returns a reference of the table. This function throws an
454 * error if the rgument is not a "table".
455 */
456__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
457{
458 if (!lua_istable(L, argno)) {
459 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
460 WILL_LJMP(luaL_argerror(L, argno, msg));
461 }
462 lua_pushvalue(L, argno);
463 return luaL_ref(L, LUA_REGISTRYINDEX);
464}
465
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200466/* Return the string that is of the top of the stack. */
467const char *hlua_get_top_error_string(lua_State *L)
468{
469 if (lua_gettop(L) < 1)
470 return "unknown error";
471 if (lua_type(L, -1) != LUA_TSTRING)
472 return "unknown error";
473 return lua_tostring(L, -1);
474}
475
Christopher Fauletd09cc512021-03-24 14:48:45 +0100476__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200477{
478 lua_Debug ar;
479 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200480 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200481
482 while (lua_getstack(L, level++, &ar)) {
483
484 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100485 if (b_data(msg))
486 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200487
488 /* Fill fields:
489 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
490 * 'l': fills in the field currentline;
491 * 'n': fills in the field name and namewhat;
492 * 't': fills in the field istailcall;
493 */
494 lua_getinfo(L, "Slnt", &ar);
495
496 /* Append code localisation */
497 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100498 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200499 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100500 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200501
502 /*
503 * Get function name
504 *
505 * if namewhat is no empty, name is defined.
506 * what contains "Lua" for Lua function, "C" for C function,
507 * or "main" for main code.
508 */
509 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100510 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200511
512 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100513 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200514
515 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100516 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200517
518 else /* nothing left... */
519 chunk_appendf(msg, "?");
520
521
522 /* Display tailed call */
523 if (ar.istailcall)
524 chunk_appendf(msg, " ...");
525 }
526
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200527 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200528}
529
530
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100531/* This function check the number of arguments available in the
532 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500533 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100534 */
535__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
536{
537 if (lua_gettop(L) == nb)
538 return;
539 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
540}
541
Mark Lakes22154b42018-01-29 14:38:40 -0800542/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100543 * and the line number where the error is encountered.
544 */
545static int hlua_pusherror(lua_State *L, const char *fmt, ...)
546{
547 va_list argp;
548 va_start(argp, fmt);
549 luaL_where(L, 1);
550 lua_pushvfstring(L, fmt, argp);
551 va_end(argp);
552 lua_concat(L, 2);
553 return 1;
554}
555
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100556/* This functions is used with sample fetch and converters. It
557 * converts the HAProxy configuration argument in a lua stack
558 * values.
559 *
560 * It takes an array of "arg", and each entry of the array is
561 * converted and pushed in the LUA stack.
562 */
563static int hlua_arg2lua(lua_State *L, const struct arg *arg)
564{
565 switch (arg->type) {
566 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100567 case ARGT_TIME:
568 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100569 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100570 break;
571
572 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200573 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100574 break;
575
576 case ARGT_IPV4:
577 case ARGT_IPV6:
578 case ARGT_MSK4:
579 case ARGT_MSK6:
580 case ARGT_FE:
581 case ARGT_BE:
582 case ARGT_TAB:
583 case ARGT_SRV:
584 case ARGT_USR:
585 case ARGT_MAP:
586 default:
587 lua_pushnil(L);
588 break;
589 }
590 return 1;
591}
592
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500593/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100594 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500595 * with sample fetch wrappers. The input arguments are given to the
596 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100597 */
598static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
599{
600 switch (lua_type(L, ud)) {
601
602 case LUA_TNUMBER:
603 case LUA_TBOOLEAN:
604 arg->type = ARGT_SINT;
605 arg->data.sint = lua_tointeger(L, ud);
606 break;
607
608 case LUA_TSTRING:
609 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200610 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200611 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200612 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200613 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100614 break;
615
616 case LUA_TUSERDATA:
617 case LUA_TNIL:
618 case LUA_TTABLE:
619 case LUA_TFUNCTION:
620 case LUA_TTHREAD:
621 case LUA_TLIGHTUSERDATA:
622 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200623 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100624 break;
625 }
626 return 1;
627}
628
629/* the following functions are used to convert a struct sample
630 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500631 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100632 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100633static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100634{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200635 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100636 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100637 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200638 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100639 break;
640
641 case SMP_T_BIN:
642 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200643 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100644 break;
645
646 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200647 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100648 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
649 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
650 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
651 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
652 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
653 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
654 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
655 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
656 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200657 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100658 break;
659 default:
660 lua_pushnil(L);
661 break;
662 }
663 break;
664
665 case SMP_T_IPV4:
666 case SMP_T_IPV6:
667 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200668 if (sample_casts[smp->data.type][SMP_T_STR] &&
669 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200670 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100671 else
672 lua_pushnil(L);
673 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100674 default:
675 lua_pushnil(L);
676 break;
677 }
678 return 1;
679}
680
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100681/* the following functions are used to convert a struct sample
682 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500683 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100684 */
685static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
686{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200687 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100688
689 case SMP_T_BIN:
690 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200691 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100692 break;
693
694 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200695 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100696 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
697 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
698 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
699 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
700 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
701 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
702 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
703 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
704 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200705 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100706 break;
707 default:
708 lua_pushstring(L, "");
709 break;
710 }
711 break;
712
713 case SMP_T_SINT:
714 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100715 case SMP_T_IPV4:
716 case SMP_T_IPV6:
717 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200718 if (sample_casts[smp->data.type][SMP_T_STR] &&
719 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200720 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100721 else
722 lua_pushstring(L, "");
723 break;
724 default:
725 lua_pushstring(L, "");
726 break;
727 }
728 return 1;
729}
730
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100731/* the following functions are used to convert an Lua type in a
732 * struct sample. This is useful to provide data from a converter
733 * to the LUA code.
734 */
735static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
736{
737 switch (lua_type(L, ud)) {
738
739 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200740 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200741 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100742 break;
743
744
745 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200746 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200747 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100748 break;
749
750 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200751 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100752 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200753 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200754 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200755 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200756 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100757 break;
758
759 case LUA_TUSERDATA:
760 case LUA_TNIL:
761 case LUA_TTABLE:
762 case LUA_TFUNCTION:
763 case LUA_TTHREAD:
764 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200765 case LUA_TNONE:
766 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200767 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200768 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100769 break;
770 }
771 return 1;
772}
773
Ilya Shipitsind4259502020-04-08 01:07:56 +0500774/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800775 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100776 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100777 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500778 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200779 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100781__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100782 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100783{
784 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200785 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100786 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200787 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200788 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200789 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200790 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100791
792 idx = 0;
793 min_arg = ARGM(mask);
794 mask >>= ARGM_BITS;
795
796 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200797 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100798
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100799 /* Check for mandatory arguments. */
800 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100801 if (idx < min_arg) {
802
803 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200804 if (idx > 0) {
805 msg = "Mandatory argument expected";
806 goto error;
807 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100808
809 /* If first argument have a certain type, some default values
810 * may be used. See the function smp_resolve_args().
811 */
812 switch (mask & ARGT_MASK) {
813
814 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200815 if (!(p->cap & PR_CAP_FE)) {
816 msg = "Mandatory argument expected";
817 goto error;
818 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100819 argp[idx].data.prx = p;
820 argp[idx].type = ARGT_FE;
821 argp[idx+1].type = ARGT_STOP;
822 break;
823
824 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200825 if (!(p->cap & PR_CAP_BE)) {
826 msg = "Mandatory argument expected";
827 goto error;
828 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100829 argp[idx].data.prx = p;
830 argp[idx].type = ARGT_BE;
831 argp[idx+1].type = ARGT_STOP;
832 break;
833
834 case ARGT_TAB:
835 argp[idx].data.prx = p;
836 argp[idx].type = ARGT_TAB;
837 argp[idx+1].type = ARGT_STOP;
838 break;
839
840 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200841 msg = "Mandatory argument expected";
842 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100843 break;
844 }
845 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200846 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100847 }
848
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500849 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100850 if ((mask & ARGT_MASK) == ARGT_STOP &&
851 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200852 msg = "Last argument expected";
853 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100854 }
855
856 if ((mask & ARGT_MASK) == ARGT_STOP &&
857 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200858 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100859 }
860
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200861 /* Convert some argument types. All string in argp[] are for not
862 * duplicated yet.
863 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100864 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100865 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200866 if (argp[idx].type != ARGT_SINT) {
867 msg = "integer expected";
868 goto error;
869 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100870 argp[idx].type = ARGT_SINT;
871 break;
872
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100873 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200874 if (argp[idx].type != ARGT_SINT) {
875 msg = "integer expected";
876 goto error;
877 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200878 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100879 break;
880
881 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200882 if (argp[idx].type != ARGT_SINT) {
883 msg = "integer expected";
884 goto error;
885 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200886 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100887 break;
888
889 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200890 if (argp[idx].type != ARGT_STR) {
891 msg = "string expected";
892 goto error;
893 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200894 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200895 if (!argp[idx].data.prx) {
896 msg = "frontend doesn't exist";
897 goto error;
898 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100899 argp[idx].type = ARGT_FE;
900 break;
901
902 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200903 if (argp[idx].type != ARGT_STR) {
904 msg = "string expected";
905 goto error;
906 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200907 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200908 if (!argp[idx].data.prx) {
909 msg = "backend doesn't exist";
910 goto error;
911 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100912 argp[idx].type = ARGT_BE;
913 break;
914
915 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200916 if (argp[idx].type != ARGT_STR) {
917 msg = "string expected";
918 goto error;
919 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200920 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200921 if (!argp[idx].data.t) {
922 msg = "table doesn't exist";
923 goto error;
924 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100925 argp[idx].type = ARGT_TAB;
926 break;
927
928 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200929 if (argp[idx].type != ARGT_STR) {
930 msg = "string expected";
931 goto error;
932 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200933 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100934 if (sname) {
935 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200936 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200937 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200938 if (!px) {
939 msg = "backend doesn't exist";
940 goto error;
941 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100942 }
943 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200944 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100945 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100946 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100947 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200948 if (!argp[idx].data.srv) {
949 msg = "server doesn't exist";
950 goto error;
951 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100952 argp[idx].type = ARGT_SRV;
953 break;
954
955 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200956 if (argp[idx].type != ARGT_STR) {
957 msg = "string expected";
958 goto error;
959 }
960 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
961 msg = "invalid IPv4 address";
962 goto error;
963 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100964 argp[idx].type = ARGT_IPV4;
965 break;
966
967 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200968 if (argp[idx].type == ARGT_SINT)
969 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
970 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200971 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
972 msg = "invalid IPv4 mask";
973 goto error;
974 }
975 }
976 else {
977 msg = "integer or string expected";
978 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200979 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100980 argp[idx].type = ARGT_MSK4;
981 break;
982
983 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200984 if (argp[idx].type != ARGT_STR) {
985 msg = "string expected";
986 goto error;
987 }
988 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
989 msg = "invalid IPv6 address";
990 goto error;
991 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100992 argp[idx].type = ARGT_IPV6;
993 break;
994
995 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200996 if (argp[idx].type == ARGT_SINT)
997 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
998 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200999 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1000 msg = "invalid IPv6 mask";
1001 goto error;
1002 }
1003 }
1004 else {
1005 msg = "integer or string expected";
1006 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001007 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001008 argp[idx].type = ARGT_MSK6;
1009 break;
1010
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001011 case ARGT_REG:
1012 if (argp[idx].type != ARGT_STR) {
1013 msg = "string expected";
1014 goto error;
1015 }
1016 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1017 if (!reg) {
1018 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1019 argp[idx].data.str.area, err);
1020 free(err);
1021 goto error;
1022 }
1023 argp[idx].type = ARGT_REG;
1024 argp[idx].data.reg = reg;
1025 break;
1026
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001027 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001028 if (argp[idx].type != ARGT_STR) {
1029 msg = "string expected";
1030 goto error;
1031 }
1032 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001033 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001034 ul = p->uri_auth->userlist;
1035 else
1036 ul = auth_find_userlist(argp[idx].data.str.area);
1037
1038 if (!ul) {
1039 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1040 goto error;
1041 }
1042 argp[idx].type = ARGT_USR;
1043 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001044 break;
1045
1046 case ARGT_STR:
1047 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1048 msg = "unable to duplicate string arg";
1049 goto error;
1050 }
1051 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001052 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001053
Christopher Fauletd25d9262020-08-06 11:04:46 +02001054 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001055 msg = "type not yet supported";
1056 goto error;
1057 break;
1058
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001059 }
1060
1061 /* Check for type of argument. */
1062 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001063 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1064 arg_type_names[(mask & ARGT_MASK)],
1065 arg_type_names[argp[idx].type & ARGT_MASK]);
1066 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001067 }
1068
1069 /* Next argument. */
1070 mask >>= ARGT_BITS;
1071 idx++;
1072 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001073 return 0;
1074
1075 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001076 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001077 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1078 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001079}
1080
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001081/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001082 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001083 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001084 *
1085 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001086 * - hlua_sethlua : create the association between hlua context and lua_state.
1087 */
1088static inline struct hlua *hlua_gethlua(lua_State *L)
1089{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001090 struct hlua **hlua = lua_getextraspace(L);
1091 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001092}
1093static inline void hlua_sethlua(struct hlua *hlua)
1094{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001095 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1096 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001097}
1098
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001099/* This function is used to send logs. It try to send on screen (stderr)
1100 * and on the default syslog server.
1101 */
1102static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1103{
1104 struct tm tm;
1105 char *p;
1106
1107 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001108 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001109 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001110 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001111 /* Break the message if exceed the buffer size. */
1112 *(p-4) = ' ';
1113 *(p-3) = '.';
1114 *(p-2) = '.';
1115 *(p-1) = '.';
1116 break;
1117 }
Willy Tarreau90807112020-02-25 08:16:33 +01001118 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001119 *p = *msg;
1120 else
1121 *p = '.';
1122 }
1123 *p = '\0';
1124
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001125 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001126 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001127 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1128 return;
1129
Willy Tarreaua678b432015-08-28 10:14:59 +02001130 get_localtime(date.tv_sec, &tm);
1131 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001132 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001133 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001134 fflush(stderr);
1135 }
1136}
1137
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001138/* This function just ensure that the yield will be always
1139 * returned with a timeout and permit to set some flags
1140 */
1141__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001142 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001143{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001144 struct hlua *hlua;
1145
1146 /* Get hlua struct, or NULL if we execute from main lua state */
1147 hlua = hlua_gethlua(L);
1148 if (!hlua) {
1149 return;
1150 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001151
1152 /* Set the wake timeout. If timeout is required, we set
1153 * the expiration time.
1154 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001155 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001156
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001157 hlua->flags |= flags;
1158
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001159 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001160 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001161}
1162
Willy Tarreau87b09662015-04-03 00:22:06 +02001163/* This function initialises the Lua environment stored in the stream.
1164 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001165 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001166 *
1167 * This function is particular. it initialises a new Lua thread. If the
1168 * initialisation fails (example: out of memory error), the lua function
1169 * throws an error (longjmp).
1170 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001171 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001172 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001173 * threads appear, the safe environment set a lock to ensure only one
1174 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001175 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001176 *
1177 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001178 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001179 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001180 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001181 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001182 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001183 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001184 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001185int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001186{
1187 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001188 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001189 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001190 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001191 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001192 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001193 if (!already_safe) {
1194 if (!SET_SAFE_LJMP_PARENT(lua)) {
1195 lua->Tref = LUA_REFNIL;
1196 return 0;
1197 }
1198 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001199 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001200 if (!lua->T) {
1201 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001202 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001203 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001204 return 0;
1205 }
1206 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001207 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001208 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001209 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001210 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001211 return 1;
1212}
1213
Willy Tarreau87b09662015-04-03 00:22:06 +02001214/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001215 * is destroyed. The destroy also the memory context. The struct "lua"
1216 * is not freed.
1217 */
1218void hlua_ctx_destroy(struct hlua *lua)
1219{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001220 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001221 return;
1222
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001223 if (!lua->T)
1224 goto end;
1225
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001226 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001227 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001228
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001229 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001230 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001231 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001232 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001233
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001234 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001235 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001236 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001237 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001238 /* Forces a garbage collecting process. If the Lua program is finished
1239 * without error, we run the GC on the thread pointer. Its freed all
1240 * the unused memory.
1241 * If the thread is finnish with an error or is currently yielded,
1242 * it seems that the GC applied on the thread doesn't clean anything,
1243 * so e run the GC on the main thread.
1244 * NOTE: maybe this action locks all the Lua threads untiml the en of
1245 * the garbage collection.
1246 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001247 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001248 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001249 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001250 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001251 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001252 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001253
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001254 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001255
1256end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001257 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001258}
1259
1260/* This function is used to restore the Lua context when a coroutine
1261 * fails. This function copy the common memory between old coroutine
1262 * and the new coroutine. The old coroutine is destroyed, and its
1263 * replaced by the new coroutine.
1264 * If the flag "keep_msg" is set, the last entry of the old is assumed
1265 * as string error message and it is copied in the new stack.
1266 */
1267static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1268{
1269 lua_State *T;
1270 int new_ref;
1271
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001272 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001273 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001274 if (!T)
1275 return 0;
1276
1277 /* Copy last error message. */
1278 if (keep_msg)
1279 lua_xmove(lua->T, T, 1);
1280
1281 /* Copy data between the coroutines. */
1282 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1283 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001284 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001285
1286 /* Destroy old data. */
1287 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1288
1289 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001290 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001291
1292 /* Fill the struct with the new coroutine values. */
1293 lua->Mref = new_ref;
1294 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001295 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001296
1297 /* Set context. */
1298 hlua_sethlua(lua);
1299
1300 return 1;
1301}
1302
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001303void hlua_hook(lua_State *L, lua_Debug *ar)
1304{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001305 struct hlua *hlua;
1306
1307 /* Get hlua struct, or NULL if we execute from main lua state */
1308 hlua = hlua_gethlua(L);
1309 if (!hlua)
1310 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001311
1312 /* Lua cannot yield when its returning from a function,
1313 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001314 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001315 */
1316 if (lua_gethookmask(L) & LUA_MASKRET) {
1317 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1318 return;
1319 }
1320
1321 /* restore the interrupt condition. */
1322 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1323
1324 /* If we interrupt the Lua processing in yieldable state, we yield.
1325 * If the state is not yieldable, trying yield causes an error.
1326 */
1327 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001328 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001329
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001330 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001331 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001332 hlua->run_time += now_ms - hlua->start_time;
1333 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001334 lua_pushfstring(L, "execution timeout");
1335 WILL_LJMP(lua_error(L));
1336 }
1337
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001338 /* Update the start time. */
1339 hlua->start_time = now_ms;
1340
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001341 /* Try to interrupt the process at the end of the current
1342 * unyieldable function.
1343 */
1344 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001345}
1346
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001347/* This function start or resumes the Lua stack execution. If the flag
1348 * "yield_allowed" if no set and the LUA stack execution returns a yield
1349 * The function return an error.
1350 *
1351 * The function can returns 4 values:
1352 * - HLUA_E_OK : The execution is terminated without any errors.
1353 * - HLUA_E_AGAIN : The execution must continue at the next associated
1354 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001355 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001356 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001357 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001358 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001359 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001360 * LUA code.
1361 */
1362static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1363{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001364#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1365 int nres;
1366#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001367 int ret;
1368 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001369 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001370
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001371 /* Initialise run time counter. */
1372 if (!HLUA_IS_RUNNING(lua))
1373 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001374
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001375 /* Lock the whole Lua execution. This lock must be before the
1376 * label "resume_execution".
1377 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001378 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001379 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001380
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001381resume_execution:
1382
1383 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1384 * instructions. it is used for preventing infinite loops.
1385 */
1386 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1387
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001388 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001389 HLUA_SET_RUN(lua);
1390 HLUA_CLR_CTRLYIELD(lua);
1391 HLUA_CLR_WAKERESWR(lua);
1392 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001393 HLUA_CLR_NOYIELD(lua);
1394 if (!yield_allowed)
1395 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001396
Christopher Fauletbc275a92020-02-26 14:55:16 +01001397 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001398 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001399 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001400
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001401 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001402#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001403 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001404#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001405 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001406#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001407 switch (ret) {
1408
1409 case LUA_OK:
1410 ret = HLUA_E_OK;
1411 break;
1412
1413 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001414 /* Check if the execution timeout is expired. It it is the case, we
1415 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001416 */
Willy Tarreau55542642021-10-08 09:33:24 +02001417 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001418 lua->run_time += now_ms - lua->start_time;
1419 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001420 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001421 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001422 break;
1423 }
1424 /* Process the forced yield. if the general yield is not allowed or
1425 * if no task were associated this the current Lua execution
1426 * coroutine, we resume the execution. Else we want to return in the
1427 * scheduler and we want to be waked up again, to continue the
1428 * current Lua execution. So we schedule our own task.
1429 */
1430 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001431 if (!yield_allowed || !lua->task)
1432 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001433 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001434 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001435 if (!yield_allowed) {
1436 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001437 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001438 break;
1439 }
1440 ret = HLUA_E_AGAIN;
1441 break;
1442
1443 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001444
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001445 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001446 * because the errors ares the only one mean to return immediately
1447 * from and lua execution.
1448 */
1449 if (lua->flags & HLUA_EXIT) {
1450 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001451 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001452 break;
1453 }
1454
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001455 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001456 if (!lua_checkstack(lua->T, 1)) {
1457 ret = HLUA_E_ERR;
1458 break;
1459 }
1460 msg = lua_tostring(lua->T, -1);
1461 lua_settop(lua->T, 0); /* Empty the stack. */
1462 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001463 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001464 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001465 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001466 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001467 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001468 ret = HLUA_E_ERRMSG;
1469 break;
1470
1471 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001472 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001473 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001474 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001475 break;
1476
1477 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001478 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001479 if (!lua_checkstack(lua->T, 1)) {
1480 ret = HLUA_E_ERR;
1481 break;
1482 }
1483 msg = lua_tostring(lua->T, -1);
1484 lua_settop(lua->T, 0); /* Empty the stack. */
1485 lua_pop(lua->T, 1);
1486 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001487 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001488 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001489 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001490 ret = HLUA_E_ERRMSG;
1491 break;
1492
1493 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001494 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001495 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001496 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001497 break;
1498 }
1499
1500 switch (ret) {
1501 case HLUA_E_AGAIN:
1502 break;
1503
1504 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001505 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001506 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001507 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001508 break;
1509
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001510 case HLUA_E_ETMOUT:
1511 case HLUA_E_NOMEM:
1512 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001513 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001514 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001515 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001516 hlua_ctx_renew(lua, 0);
1517 break;
1518
1519 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001520 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001521 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001522 break;
1523 }
1524
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001525 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001526 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001527 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001528
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001529 return ret;
1530}
1531
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001532/* This function exit the current code. */
1533__LJMP static int hlua_done(lua_State *L)
1534{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001535 struct hlua *hlua;
1536
1537 /* Get hlua struct, or NULL if we execute from main lua state */
1538 hlua = hlua_gethlua(L);
1539 if (!hlua)
1540 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001541
1542 hlua->flags |= HLUA_EXIT;
1543 WILL_LJMP(lua_error(L));
1544
1545 return 0;
1546}
1547
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001548/* This function is an LUA binding. It provides a function
1549 * for deleting ACL from a referenced ACL file.
1550 */
1551__LJMP static int hlua_del_acl(lua_State *L)
1552{
1553 const char *name;
1554 const char *key;
1555 struct pat_ref *ref;
1556
1557 MAY_LJMP(check_args(L, 2, "del_acl"));
1558
1559 name = MAY_LJMP(luaL_checkstring(L, 1));
1560 key = MAY_LJMP(luaL_checkstring(L, 2));
1561
1562 ref = pat_ref_lookup(name);
1563 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001564 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001565
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001566 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001567 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001568 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001569 return 0;
1570}
1571
1572/* This function is an LUA binding. It provides a function
1573 * for deleting map entry from a referenced map file.
1574 */
1575static int hlua_del_map(lua_State *L)
1576{
1577 const char *name;
1578 const char *key;
1579 struct pat_ref *ref;
1580
1581 MAY_LJMP(check_args(L, 2, "del_map"));
1582
1583 name = MAY_LJMP(luaL_checkstring(L, 1));
1584 key = MAY_LJMP(luaL_checkstring(L, 2));
1585
1586 ref = pat_ref_lookup(name);
1587 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001588 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001589
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001590 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001591 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001592 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001593 return 0;
1594}
1595
1596/* This function is an LUA binding. It provides a function
1597 * for adding ACL pattern from a referenced ACL file.
1598 */
1599static int hlua_add_acl(lua_State *L)
1600{
1601 const char *name;
1602 const char *key;
1603 struct pat_ref *ref;
1604
1605 MAY_LJMP(check_args(L, 2, "add_acl"));
1606
1607 name = MAY_LJMP(luaL_checkstring(L, 1));
1608 key = MAY_LJMP(luaL_checkstring(L, 2));
1609
1610 ref = pat_ref_lookup(name);
1611 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001612 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001613
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001614 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001615 if (pat_ref_find_elt(ref, key) == NULL)
1616 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001617 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001618 return 0;
1619}
1620
1621/* This function is an LUA binding. It provides a function
1622 * for setting map pattern and sample from a referenced map
1623 * file.
1624 */
1625static int hlua_set_map(lua_State *L)
1626{
1627 const char *name;
1628 const char *key;
1629 const char *value;
1630 struct pat_ref *ref;
1631
1632 MAY_LJMP(check_args(L, 3, "set_map"));
1633
1634 name = MAY_LJMP(luaL_checkstring(L, 1));
1635 key = MAY_LJMP(luaL_checkstring(L, 2));
1636 value = MAY_LJMP(luaL_checkstring(L, 3));
1637
1638 ref = pat_ref_lookup(name);
1639 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001640 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001641
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001642 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001643 if (pat_ref_find_elt(ref, key) != NULL)
1644 pat_ref_set(ref, key, value, NULL);
1645 else
1646 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001647 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001648 return 0;
1649}
1650
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001651/* A class is a lot of memory that contain data. This data can be a table,
1652 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001653 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001654 * the name of the object (_G[<name>] = <metable> ).
1655 *
1656 * A metable is a table that modify the standard behavior of a standard
1657 * access to the associated data. The entries of this new metatable are
1658 * defined as is:
1659 *
1660 * http://lua-users.org/wiki/MetatableEvents
1661 *
1662 * __index
1663 *
1664 * we access an absent field in a table, the result is nil. This is
1665 * true, but it is not the whole truth. Actually, such access triggers
1666 * the interpreter to look for an __index metamethod: If there is no
1667 * such method, as usually happens, then the access results in nil;
1668 * otherwise, the metamethod will provide the result.
1669 *
1670 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1671 * the key does not appear in the table, but the metatable has an __index
1672 * property:
1673 *
1674 * - if the value is a function, the function is called, passing in the
1675 * table and the key; the return value of that function is returned as
1676 * the result.
1677 *
1678 * - if the value is another table, the value of the key in that table is
1679 * asked for and returned (and if it doesn't exist in that table, but that
1680 * table's metatable has an __index property, then it continues on up)
1681 *
1682 * - Use "rawget(myTable,key)" to skip this metamethod.
1683 *
1684 * http://www.lua.org/pil/13.4.1.html
1685 *
1686 * __newindex
1687 *
1688 * Like __index, but control property assignment.
1689 *
1690 * __mode - Control weak references. A string value with one or both
1691 * of the characters 'k' and 'v' which specifies that the the
1692 * keys and/or values in the table are weak references.
1693 *
1694 * __call - Treat a table like a function. When a table is followed by
1695 * parenthesis such as "myTable( 'foo' )" and the metatable has
1696 * a __call key pointing to a function, that function is invoked
1697 * (passing any specified arguments) and the return value is
1698 * returned.
1699 *
1700 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1701 * called, if the metatable for myTable has a __metatable
1702 * key, the value of that key is returned instead of the
1703 * actual metatable.
1704 *
1705 * __tostring - Control string representation. When the builtin
1706 * "tostring( myTable )" function is called, if the metatable
1707 * for myTable has a __tostring property set to a function,
1708 * that function is invoked (passing myTable to it) and the
1709 * return value is used as the string representation.
1710 *
1711 * __len - Control table length. When the table length is requested using
1712 * the length operator ( '#' ), if the metatable for myTable has
1713 * a __len key pointing to a function, that function is invoked
1714 * (passing myTable to it) and the return value used as the value
1715 * of "#myTable".
1716 *
1717 * __gc - Userdata finalizer code. When userdata is set to be garbage
1718 * collected, if the metatable has a __gc field pointing to a
1719 * function, that function is first invoked, passing the userdata
1720 * to it. The __gc metamethod is not called for tables.
1721 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1722 *
1723 * Special metamethods for redefining standard operators:
1724 * http://www.lua.org/pil/13.1.html
1725 *
1726 * __add "+"
1727 * __sub "-"
1728 * __mul "*"
1729 * __div "/"
1730 * __unm "!"
1731 * __pow "^"
1732 * __concat ".."
1733 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001734 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001735 * http://www.lua.org/pil/13.2.html
1736 *
1737 * __eq "=="
1738 * __lt "<"
1739 * __le "<="
1740 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001741
1742/*
1743 *
1744 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001745 * Class Map
1746 *
1747 *
1748 */
1749
1750/* Returns a struct hlua_map if the stack entry "ud" is
1751 * a class session, otherwise it throws an error.
1752 */
1753__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1754{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001755 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001756}
1757
1758/* This function is the map constructor. It don't need
1759 * the class Map object. It creates and return a new Map
1760 * object. It must be called only during "body" or "init"
1761 * context because it process some filesystem accesses.
1762 */
1763__LJMP static int hlua_map_new(struct lua_State *L)
1764{
1765 const char *fn;
1766 int match = PAT_MATCH_STR;
1767 struct sample_conv conv;
1768 const char *file = "";
1769 int line = 0;
1770 lua_Debug ar;
1771 char *err = NULL;
1772 struct arg args[2];
1773
1774 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1775 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1776
1777 fn = MAY_LJMP(luaL_checkstring(L, 1));
1778
1779 if (lua_gettop(L) >= 2) {
1780 match = MAY_LJMP(luaL_checkinteger(L, 2));
1781 if (match < 0 || match >= PAT_MATCH_NUM)
1782 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1783 }
1784
1785 /* Get Lua filename and line number. */
1786 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1787 lua_getinfo(L, "Sl", &ar); /* get info about it */
1788 if (ar.currentline > 0) { /* is there info? */
1789 file = ar.short_src;
1790 line = ar.currentline;
1791 }
1792 }
1793
1794 /* fill fake sample_conv struct. */
1795 conv.kw = ""; /* unused. */
1796 conv.process = NULL; /* unused. */
1797 conv.arg_mask = 0; /* unused. */
1798 conv.val_args = NULL; /* unused. */
1799 conv.out_type = SMP_T_STR;
1800 conv.private = (void *)(long)match;
1801 switch (match) {
1802 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1803 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1804 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1805 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1806 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1807 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1808 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001809 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001810 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1811 default:
1812 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1813 }
1814
1815 /* fill fake args. */
1816 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001817 args[0].data.str.area = strdup(fn);
1818 args[0].data.str.data = strlen(fn);
1819 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001820 args[1].type = ARGT_STOP;
1821
1822 /* load the map. */
1823 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001824 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001825 * free the err variable.
1826 */
1827 luaL_where(L, 1);
1828 lua_pushfstring(L, "'new': %s.", err);
1829 lua_concat(L, 2);
1830 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001831 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001832 WILL_LJMP(lua_error(L));
1833 }
1834
1835 /* create the lua object. */
1836 lua_newtable(L);
1837 lua_pushlightuserdata(L, args[0].data.map);
1838 lua_rawseti(L, -2, 0);
1839
1840 /* Pop a class Map metatable and affect it to the userdata. */
1841 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1842 lua_setmetatable(L, -2);
1843
1844
1845 return 1;
1846}
1847
1848__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1849{
1850 struct map_descriptor *desc;
1851 struct pattern *pat;
1852 struct sample smp;
1853
1854 MAY_LJMP(check_args(L, 2, "lookup"));
1855 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001856 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001857 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001858 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001859 }
1860 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001861 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001862 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001863 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 +01001864 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001865 }
1866
1867 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001868 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001869 if (str)
1870 lua_pushstring(L, "");
1871 else
1872 lua_pushnil(L);
1873 return 1;
1874 }
1875
1876 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001877 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001878 return 1;
1879}
1880
1881__LJMP static int hlua_map_lookup(struct lua_State *L)
1882{
1883 return _hlua_map_lookup(L, 0);
1884}
1885
1886__LJMP static int hlua_map_slookup(struct lua_State *L)
1887{
1888 return _hlua_map_lookup(L, 1);
1889}
1890
1891/*
1892 *
1893 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001894 * Class Socket
1895 *
1896 *
1897 */
1898
1899__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1900{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001901 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902}
1903
1904/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001905 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001906 * received.
1907 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001908static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001909{
Christopher Faulet86e1c332021-12-20 17:09:39 +01001910 struct stream_interface *si = cs_si(appctx->owner);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001911
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001912 if (appctx->ctx.hlua_cosocket.die) {
1913 si_shutw(si);
1914 si_shutr(si);
1915 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001916 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1917 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001918 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1919 }
1920
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001921 /* If we can't write, wakeup the pending write signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001922 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001923 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001924
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001925 /* If we can't read, wakeup the pending read signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001926 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001927 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001928
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001929 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001930 * to be notified whenever the connection completes.
1931 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001932 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001933 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001934 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001935 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001936 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001937 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001938
1939 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001940 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001942 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001943 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001944 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001945
1946 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001947 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001948 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001949
1950 /* Some data were injected in the buffer, notify the stream
1951 * interface.
1952 */
1953 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001954 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001955
1956 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001957 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001958 */
1959 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001960 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001961}
1962
Willy Tarreau87b09662015-04-03 00:22:06 +02001963/* This function is called when the "struct stream" is destroyed.
1964 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965 * Wake all the pending signals.
1966 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001967static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001968{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001969 struct xref *peer;
1970
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001971 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001972 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1973 if (peer)
1974 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001975
1976 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001977 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1978 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001979}
1980
1981/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001982 * uses this object. If the stream does not exists, just quit.
1983 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984 * pending signal can rest in the read and write lists. destroy
1985 * it.
1986 */
1987__LJMP static int hlua_socket_gc(lua_State *L)
1988{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001989 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001990 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001991 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001993 MAY_LJMP(check_args(L, 1, "__gc"));
1994
1995 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001996 peer = xref_get_peer_and_lock(&socket->xref);
1997 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001999 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002000
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002001 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002002 appctx->ctx.hlua_cosocket.die = 1;
2003 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002004
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002005 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002006 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002007 return 0;
2008}
2009
2010/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002011 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012 */
sada05ed3302018-05-11 11:48:18 -07002013__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002014{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002015 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002016 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002017 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002018 struct hlua *hlua;
2019
2020 /* Get hlua struct, or NULL if we execute from main lua state */
2021 hlua = hlua_gethlua(L);
2022 if (!hlua)
2023 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002024
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002025 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002026
2027 /* Check if we run on the same thread than the xreator thread.
2028 * We cannot access to the socket if the thread is different.
2029 */
2030 if (socket->tid != tid)
2031 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2032
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002033 peer = xref_get_peer_and_lock(&socket->xref);
2034 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002036
2037 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002038 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002039
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002040 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002041 appctx->ctx.hlua_cosocket.die = 1;
2042 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002044 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002045 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046 return 0;
2047}
2048
sada05ed3302018-05-11 11:48:18 -07002049/* The close function calls close_helper.
2050 */
2051__LJMP static int hlua_socket_close(lua_State *L)
2052{
2053 MAY_LJMP(check_args(L, 1, "close"));
2054 return hlua_socket_close_helper(L);
2055}
2056
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002057/* This Lua function assumes that the stack contain three parameters.
2058 * 1 - USERDATA containing a struct socket
2059 * 2 - INTEGER with values of the macro defined below
2060 * If the integer is -1, we must read at most one line.
2061 * If the integer is -2, we ust read all the data until the
2062 * end of the stream.
2063 * If the integer is positive value, we must read a number of
2064 * bytes corresponding to this value.
2065 */
2066#define HLSR_READ_LINE (-1)
2067#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002068__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002069{
2070 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2071 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002072 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002073 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002074 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002075 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002076 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002077 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002078 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002079 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002080 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002081 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002082 struct stream_interface *si;
2083 struct stream *s;
2084 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002085 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002087 /* Get hlua struct, or NULL if we execute from main lua state */
2088 hlua = hlua_gethlua(L);
2089
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090 /* Check if this lua stack is schedulable. */
2091 if (!hlua || !hlua->task)
2092 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2093 "'frontend', 'backend' or 'task'"));
2094
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002095 /* Check if we run on the same thread than the xreator thread.
2096 * We cannot access to the socket if the thread is different.
2097 */
2098 if (socket->tid != tid)
2099 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2100
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002101 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002102 peer = xref_get_peer_and_lock(&socket->xref);
2103 if (!peer)
2104 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002105 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002106 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002107 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002108
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002109 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002110 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002112 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002113 if (nblk < 0) /* Connection close. */
2114 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002115 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002116 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002117
2118 /* remove final \r\n. */
2119 if (nblk == 1) {
2120 if (blk1[len1-1] == '\n') {
2121 len1--;
2122 skip_at_end++;
2123 if (blk1[len1-1] == '\r') {
2124 len1--;
2125 skip_at_end++;
2126 }
2127 }
2128 }
2129 else {
2130 if (blk2[len2-1] == '\n') {
2131 len2--;
2132 skip_at_end++;
2133 if (blk2[len2-1] == '\r') {
2134 len2--;
2135 skip_at_end++;
2136 }
2137 }
2138 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002139 }
2140
2141 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002143 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144 if (nblk < 0) /* Connection close. */
2145 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002146 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002147 goto connection_empty;
2148 }
2149
2150 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002152 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002153 if (nblk < 0) /* Connection close. */
2154 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002155 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002156 goto connection_empty;
2157
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002158 missing_bytes = wanted - socket->b.n;
2159 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002160 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002161 len1 = missing_bytes;
2162 } if (nblk == 2 && len1 + len2 > missing_bytes)
2163 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164 }
2165
2166 len = len1;
2167
2168 luaL_addlstring(&socket->b, blk1, len1);
2169 if (nblk == 2) {
2170 len += len2;
2171 luaL_addlstring(&socket->b, blk2, len2);
2172 }
2173
2174 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002175 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176
2177 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002178 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002179
2180 /* If the pattern reclaim to read all the data
2181 * in the connection, got out.
2182 */
2183 if (wanted == HLSR_READ_ALL)
2184 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002185 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 goto connection_empty;
2187
2188 /* Return result. */
2189 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002190 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191 return 1;
2192
2193connection_closed:
2194
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002195 xref_unlock(&socket->xref, peer);
2196
2197no_peer:
2198
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199 /* If the buffer containds data. */
2200 if (socket->b.n > 0) {
2201 luaL_pushresult(&socket->b);
2202 return 1;
2203 }
2204 lua_pushnil(L);
2205 lua_pushstring(L, "connection closed.");
2206 return 2;
2207
2208connection_empty:
2209
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002210 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
2211 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002213 }
2214 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002215 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002216 return 0;
2217}
2218
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002219/* This Lua function gets two parameters. The first one can be string
2220 * or a number. If the string is "*l", the user requires one line. If
2221 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002222 * If the value is a number, the user require a number of bytes equal
2223 * to the value. The default value is "*l" (a line).
2224 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002225 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 * integer takes this values:
2227 * -1 : read a line
2228 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002229 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002231 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002232 * concatenated with the read data.
2233 */
2234__LJMP static int hlua_socket_receive(struct lua_State *L)
2235{
2236 int wanted = HLSR_READ_LINE;
2237 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002238 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239 char *error;
2240 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002241 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242
2243 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2244 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2245
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002246 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002248 /* Check if we run on the same thread than the xreator thread.
2249 * We cannot access to the socket if the thread is different.
2250 */
2251 if (socket->tid != tid)
2252 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2253
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002254 /* check for pattern. */
2255 if (lua_gettop(L) >= 2) {
2256 type = lua_type(L, 2);
2257 if (type == LUA_TSTRING) {
2258 pattern = lua_tostring(L, 2);
2259 if (strcmp(pattern, "*a") == 0)
2260 wanted = HLSR_READ_ALL;
2261 else if (strcmp(pattern, "*l") == 0)
2262 wanted = HLSR_READ_LINE;
2263 else {
2264 wanted = strtoll(pattern, &error, 10);
2265 if (*error != '\0')
2266 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2267 }
2268 }
2269 else if (type == LUA_TNUMBER) {
2270 wanted = lua_tointeger(L, 2);
2271 if (wanted < 0)
2272 WILL_LJMP(luaL_error(L, "Unsupported size."));
2273 }
2274 }
2275
2276 /* Set pattern. */
2277 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002278
2279 /* Check if we would replace the top by itself. */
2280 if (lua_gettop(L) != 2)
2281 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282
Christopher Fauletc31b2002021-05-03 10:11:13 +02002283 /* Save index of the top of the stack because since buffers are used, it
2284 * may change
2285 */
2286 lastarg = lua_gettop(L);
2287
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002288 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002289 luaL_buffinit(L, &socket->b);
2290
2291 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002292 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 if (lua_type(L, 3) != LUA_TSTRING)
2294 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2295 pattern = lua_tolstring(L, 3, &len);
2296 luaL_addlstring(&socket->b, pattern, len);
2297 }
2298
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002299 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300}
2301
2302/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002303 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002305static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306{
2307 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002308 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309 struct appctx *appctx;
2310 size_t buf_len;
2311 const char *buf;
2312 int len;
2313 int send_len;
2314 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002315 struct xref *peer;
2316 struct stream_interface *si;
2317 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002318
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002319 /* Get hlua struct, or NULL if we execute from main lua state */
2320 hlua = hlua_gethlua(L);
2321
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322 /* Check if this lua stack is schedulable. */
2323 if (!hlua || !hlua->task)
2324 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2325 "'frontend', 'backend' or 'task'"));
2326
2327 /* Get object */
2328 socket = MAY_LJMP(hlua_checksocket(L, 1));
2329 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002330 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002332 /* Check if we run on the same thread than the xreator thread.
2333 * We cannot access to the socket if the thread is different.
2334 */
2335 if (socket->tid != tid)
2336 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2337
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002338 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002339 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002340 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002341 lua_pushinteger(L, -1);
2342 return 1;
2343 }
2344 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002345 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002346 s = si_strm(si);
2347
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002349 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002350 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351 lua_pushinteger(L, -1);
2352 return 1;
2353 }
2354
2355 /* Update the input buffer data. */
2356 buf += sent;
2357 send_len = buf_len - sent;
2358
2359 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002360 if (sent >= buf_len) {
2361 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002363 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002364
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002365 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002366 * the request buffer if its not required.
2367 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002368 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002369 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002370 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002371 }
2372
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002373 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002374 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002375 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002377 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378
2379 /* send data */
2380 if (len < send_len)
2381 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002382 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383
2384 /* "Not enough space" (-1), "Buffer too little to contain
2385 * the data" (-2) are not expected because the available length
2386 * is tested.
2387 * Other unknown error are also not expected.
2388 */
2389 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002390 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002391 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002392
sada05ed3302018-05-11 11:48:18 -07002393 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002395 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002396 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002397 return 1;
2398 }
2399
2400 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002401 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002402
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002403 s->req.rex = TICK_ETERNITY;
2404 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002405
2406 /* Update length sent. */
2407 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002408 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002409
2410 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002411 if (sent + len >= buf_len) {
2412 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002413 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002414 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002415
2416hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002417 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2418 xref_unlock(&socket->xref, peer);
2419 WILL_LJMP(luaL_error(L, "out of memory"));
2420 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002421 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002422 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002423 return 0;
2424}
2425
2426/* This function initiate the send of data. It just check the input
2427 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002428 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002429 * "hlua_socket_write_yield" that can yield.
2430 *
2431 * The Lua function gets between 3 and 4 parameters. The first one is
2432 * the associated object. The second is a string buffer. The third is
2433 * a facultative integer that represents where is the buffer position
2434 * of the start of the data that can send. The first byte is the
2435 * position "1". The default value is "1". The fourth argument is a
2436 * facultative integer that represents where is the buffer position
2437 * of the end of the data that can send. The default is the last byte.
2438 */
2439static int hlua_socket_send(struct lua_State *L)
2440{
2441 int i;
2442 int j;
2443 const char *buf;
2444 size_t buf_len;
2445
2446 /* Check number of arguments. */
2447 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2448 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2449
2450 /* Get the string. */
2451 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2452
2453 /* Get and check j. */
2454 if (lua_gettop(L) == 4) {
2455 j = MAY_LJMP(luaL_checkinteger(L, 4));
2456 if (j < 0)
2457 j = buf_len + j + 1;
2458 if (j > buf_len)
2459 j = buf_len + 1;
2460 lua_pop(L, 1);
2461 }
2462 else
2463 j = buf_len;
2464
2465 /* Get and check i. */
2466 if (lua_gettop(L) == 3) {
2467 i = MAY_LJMP(luaL_checkinteger(L, 3));
2468 if (i < 0)
2469 i = buf_len + i + 1;
2470 if (i > buf_len)
2471 i = buf_len + 1;
2472 lua_pop(L, 1);
2473 } else
2474 i = 1;
2475
2476 /* Check bth i and j. */
2477 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002478 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002479 return 1;
2480 }
2481 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002482 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002483 return 1;
2484 }
2485 if (i == 0)
2486 i = 1;
2487 if (j == 0)
2488 j = 1;
2489
2490 /* Pop the string. */
2491 lua_pop(L, 1);
2492
2493 /* Update the buffer length. */
2494 buf += i - 1;
2495 buf_len = j - i + 1;
2496 lua_pushlstring(L, buf, buf_len);
2497
2498 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002499 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002501 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502}
2503
Willy Tarreau22b0a682015-06-17 19:43:49 +02002504#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002505__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506{
2507 static char buffer[SOCKET_INFO_MAX_LEN];
2508 int ret;
2509 int len;
2510 char *p;
2511
2512 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2513 if (ret <= 0) {
2514 lua_pushnil(L);
2515 return 1;
2516 }
2517
2518 if (ret == AF_UNIX) {
2519 lua_pushstring(L, buffer+1);
2520 return 1;
2521 }
2522 else if (ret == AF_INET6) {
2523 buffer[0] = '[';
2524 len = strlen(buffer);
2525 buffer[len] = ']';
2526 len++;
2527 buffer[len] = ':';
2528 len++;
2529 p = buffer;
2530 }
2531 else if (ret == AF_INET) {
2532 p = buffer + 1;
2533 len = strlen(p);
2534 p[len] = ':';
2535 len++;
2536 }
2537 else {
2538 lua_pushnil(L);
2539 return 1;
2540 }
2541
2542 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2543 lua_pushnil(L);
2544 return 1;
2545 }
2546
2547 lua_pushstring(L, p);
2548 return 1;
2549}
2550
2551/* Returns information about the peer of the connection. */
2552__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2553{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002554 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002555 struct xref *peer;
2556 struct appctx *appctx;
2557 struct stream_interface *si;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002558 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002559 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002560
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002561 MAY_LJMP(check_args(L, 1, "getpeername"));
2562
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002563 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002564
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002565 /* Check if we run on the same thread than the xreator thread.
2566 * We cannot access to the socket if the thread is different.
2567 */
2568 if (socket->tid != tid)
2569 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2570
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002571 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002572 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002573 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002574 lua_pushnil(L);
2575 return 1;
2576 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002577 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002578 si = cs_si(appctx->owner);
Christopher Faulet16f16af2021-10-27 09:34:56 +02002579 dst = si_dst(si_opposite(si));
2580 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002581 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002582 lua_pushnil(L);
2583 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002584 }
2585
Christopher Faulet16f16af2021-10-27 09:34:56 +02002586 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002587 xref_unlock(&socket->xref, peer);
2588 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589}
2590
2591/* Returns information about my connection side. */
2592static int hlua_socket_getsockname(struct lua_State *L)
2593{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002594 struct hlua_socket *socket;
2595 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002596 struct appctx *appctx;
2597 struct xref *peer;
2598 struct stream_interface *si;
2599 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002600 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002601
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002602 MAY_LJMP(check_args(L, 1, "getsockname"));
2603
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002604 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002605
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002606 /* Check if we run on the same thread than the xreator thread.
2607 * We cannot access to the socket if the thread is different.
2608 */
2609 if (socket->tid != tid)
2610 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2611
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002612 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002613 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002614 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002615 lua_pushnil(L);
2616 return 1;
2617 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002618 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002619 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002620 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002621
Christopher Faulet95a61e82021-12-22 14:22:03 +01002622 conn = cs_conn(s->csb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002623 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002624 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002625 lua_pushnil(L);
2626 return 1;
2627 }
2628
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002629 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002630 xref_unlock(&socket->xref, peer);
2631 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632}
2633
2634/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002635static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002636 .obj_type = OBJ_TYPE_APPLET,
2637 .name = "<LUA_TCP>",
2638 .fct = hlua_socket_handler,
2639 .release = hlua_socket_release,
2640};
2641
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002642__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002643{
2644 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002645 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002646 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002648 struct stream_interface *si;
2649 struct stream *s;
2650
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002651 /* Get hlua struct, or NULL if we execute from main lua state */
2652 hlua = hlua_gethlua(L);
2653 if (!hlua)
2654 return 0;
2655
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002656 /* Check if we run on the same thread than the xreator thread.
2657 * We cannot access to the socket if the thread is different.
2658 */
2659 if (socket->tid != tid)
2660 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2661
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002662 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002663 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002664 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002665 lua_pushnil(L);
2666 lua_pushstring(L, "Can't connect");
2667 return 2;
2668 }
2669 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002670 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002671 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002672
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002673 /* Check if we run on the same thread than the xreator thread.
2674 * We cannot access to the socket if the thread is different.
2675 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002676 if (socket->tid != tid) {
2677 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002678 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002679 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002680
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002681 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002682 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002683 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002684 lua_pushnil(L);
2685 lua_pushstring(L, "Can't connect");
2686 return 2;
2687 }
2688
Christopher Faulet693b23b2022-02-28 09:09:05 +01002689 appctx = __cs_appctx(s->csf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002690
2691 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002692 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002693 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002694 lua_pushinteger(L, 1);
2695 return 1;
2696 }
2697
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002698 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2699 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002700 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002701 }
2702 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002703 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002704 return 0;
2705}
2706
2707/* This function fail or initite the connection. */
2708__LJMP static int hlua_socket_connect(struct lua_State *L)
2709{
2710 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002711 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002712 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002713 struct hlua *hlua;
2714 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002715 int low, high;
2716 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002717 struct xref *peer;
2718 struct stream_interface *si;
2719 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002720
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002721 if (lua_gettop(L) < 2)
2722 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002723
2724 /* Get args. */
2725 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002726
2727 /* Check if we run on the same thread than the xreator thread.
2728 * We cannot access to the socket if the thread is different.
2729 */
2730 if (socket->tid != tid)
2731 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2732
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002734 if (lua_gettop(L) >= 3) {
2735 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002736 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002737
Tim Duesterhus6edab862018-01-06 19:04:45 +01002738 /* Force the ip to end with a colon, to support IPv6 addresses
2739 * that are not enclosed within square brackets.
2740 */
2741 if (port > 0) {
2742 luaL_buffinit(L, &b);
2743 luaL_addstring(&b, ip);
2744 luaL_addchar(&b, ':');
2745 luaL_pushresult(&b);
2746 ip = lua_tolstring(L, lua_gettop(L), NULL);
2747 }
2748 }
2749
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002750 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002751 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002752 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002753 lua_pushnil(L);
2754 return 1;
2755 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002756
2757 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002758 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 +02002759 if (!addr) {
2760 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002761 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002762 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002763
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002764 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002765 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002766 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002767 if (port == -1) {
2768 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002769 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002770 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002771 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2772 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002773 if (port == -1) {
2774 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002775 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002776 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002777 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002778 }
2779 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002780
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002781 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002782 si = cs_si(appctx->owner);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002783 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002784
Christopher Faulet16f16af2021-10-27 09:34:56 +02002785 if (!sockaddr_alloc(&si_opposite(si)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002786 xref_unlock(&socket->xref, peer);
2787 WILL_LJMP(luaL_error(L, "connect: internal error"));
2788 }
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002789 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002790
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002791 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002792 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002793 if (!hlua)
2794 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002795
2796 /* inform the stream that we want to be notified whenever the
2797 * connection completes.
2798 */
Christopher Faulet436811f2021-12-23 13:39:38 +01002799 si_cant_get(cs_si(s->csf));
2800 si_rx_endp_more(cs_si(s->csf));
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002801 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002802
Willy Tarreauf31af932020-01-14 09:59:38 +01002803 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002804
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002805 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2806 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002807 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002808 }
2809 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002810
2811 task_wakeup(s->task, TASK_WOKEN_INIT);
2812 /* Return yield waiting for connection. */
2813
Willy Tarreau9635e032018-10-16 17:52:55 +02002814 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002815
2816 return 0;
2817}
2818
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002819#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002820__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2821{
2822 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002823 struct xref *peer;
2824 struct appctx *appctx;
2825 struct stream_interface *si;
2826 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002827
2828 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2829 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002830
2831 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002832 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002833 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002834 lua_pushnil(L);
2835 return 1;
2836 }
2837 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002838 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002839 s = si_strm(si);
2840
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002841 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002842 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002843 return MAY_LJMP(hlua_socket_connect(L));
2844}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002845#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002846
2847__LJMP static int hlua_socket_setoption(struct lua_State *L)
2848{
2849 return 0;
2850}
2851
2852__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2853{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002854 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002855 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002856 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002857 struct xref *peer;
2858 struct appctx *appctx;
2859 struct stream_interface *si;
2860 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002861
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002862 MAY_LJMP(check_args(L, 2, "settimeout"));
2863
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002864 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002865
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002866 /* convert the timeout to millis */
2867 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002868
Thierry Fournier17a921b2018-03-08 09:59:02 +01002869 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002870 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002871 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2872
Mark Lakes56cc1252018-03-27 09:48:06 +02002873 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002874 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002875
2876 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002877 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002878 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002879
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002880 /* Check if we run on the same thread than the xreator thread.
2881 * We cannot access to the socket if the thread is different.
2882 */
2883 if (socket->tid != tid)
2884 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2885
Mark Lakes56cc1252018-03-27 09:48:06 +02002886 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002887 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002888 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002889 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2890 WILL_LJMP(lua_error(L));
2891 return 0;
2892 }
2893 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Christopher Faulet86e1c332021-12-20 17:09:39 +01002894 si = cs_si(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002895 s = si_strm(si);
2896
Cyril Bonté7bb63452018-08-17 23:51:02 +02002897 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002898 s->req.rto = tmout;
2899 s->req.wto = tmout;
2900 s->res.rto = tmout;
2901 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002902 s->req.rex = tick_add_ifset(now_ms, tmout);
2903 s->req.wex = tick_add_ifset(now_ms, tmout);
2904 s->res.rex = tick_add_ifset(now_ms, tmout);
2905 s->res.wex = tick_add_ifset(now_ms, tmout);
2906
2907 s->task->expire = tick_add_ifset(now_ms, tmout);
2908 task_queue(s->task);
2909
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002910 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002911
Thierry Fourniere9636f12018-03-08 09:54:32 +01002912 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002913 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002914}
2915
2916__LJMP static int hlua_socket_new(lua_State *L)
2917{
2918 struct hlua_socket *socket;
2919 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002920 struct session *sess;
Christopher Faulet13a35e52021-12-20 15:34:16 +01002921 struct conn_stream *cs;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002922 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002923
2924 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002925 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002926 hlua_pusherror(L, "socket: full stack");
2927 goto out_fail_conf;
2928 }
2929
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002930 /* Create the object: obj[0] = userdata. */
2931 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002932 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002933 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002934 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002935 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002936
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002937 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002938 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002939 hlua_pusherror(L, "socket: uninitialized pools.");
2940 goto out_fail_conf;
2941 }
2942
Willy Tarreau87b09662015-04-03 00:22:06 +02002943 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002944 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2945 lua_setmetatable(L, -2);
2946
Willy Tarreaud420a972015-04-06 00:39:18 +02002947 /* Create the applet context */
Willy Tarreaue6124462021-09-13 10:07:38 +02002948 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002949 if (!appctx) {
2950 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002951 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002952 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002953
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002954 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002955 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002956 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2957 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002958
Willy Tarreaud420a972015-04-06 00:39:18 +02002959 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002960 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002961 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002962 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet13a35e52021-12-20 15:34:16 +01002963 goto out_fail_appctx;
2964 }
2965
Christopher Fauletcda94ac2021-12-23 17:28:17 +01002966 cs = cs_new();
Christopher Faulet13a35e52021-12-20 15:34:16 +01002967 if (!cs) {
2968 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002969 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970 }
Christopher Fauletcda94ac2021-12-23 17:28:17 +01002971 cs_attach_endp(cs, &appctx->obj_type, appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002972
Christopher Faulet13a35e52021-12-20 15:34:16 +01002973 strm = stream_new(sess, cs, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002974 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002975 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet13a35e52021-12-20 15:34:16 +01002976 goto out_fail_cs;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002977 }
2978
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002979 /* Initialise cross reference between stream and Lua socket object. */
2980 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002981
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002982 /* Configure "right" stream interface. this "si" is used to connect
2983 * and retrieve data from the server. The connection is initialized
2984 * with the "struct server".
2985 */
Christopher Fauletcda94ac2021-12-23 17:28:17 +01002986 si_set_state(strm->csb->si, SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002987
2988 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002989 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002990 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002991
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002992 return 1;
2993
Christopher Faulet13a35e52021-12-20 15:34:16 +01002994 out_fail_cs:
2995 cs_free(cs);
Willy Tarreaud420a972015-04-06 00:39:18 +02002996 out_fail_sess:
Christopher Faulet13a35e52021-12-20 15:34:16 +01002997 session_free(sess);
2998 out_fail_appctx:
Willy Tarreaud420a972015-04-06 00:39:18 +02002999 appctx_free(appctx);
3000 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003001 WILL_LJMP(lua_error(L));
3002 return 0;
3003}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003004
3005/*
3006 *
3007 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003008 * Class Channel
3009 *
3010 *
3011 */
3012
3013/* Returns the struct hlua_channel join to the class channel in the
3014 * stack entry "ud" or throws an argument error.
3015 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003016__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003017{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003018 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003019}
3020
Willy Tarreau47860ed2015-03-10 14:07:50 +01003021/* Pushes the channel onto the top of the stack. If the stask does not have a
3022 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003023 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003024static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003025{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003026 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003027 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003028 return 0;
3029
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003030 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003031 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003032 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003033
3034 /* Pop a class sesison metatable and affect it to the userdata. */
3035 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3036 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003037 return 1;
3038}
3039
Christopher Faulet9f55a502020-02-25 15:21:02 +01003040/* Helper function returning a filter attached to a channel at the position <ud>
3041 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003042 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003043 * initialized.
3044 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003045static 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 +01003046{
3047 struct filter *filter = NULL;
3048
3049 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3050 struct hlua_flt_ctx *flt_ctx;
3051
3052 filter = lua_touserdata (L, -1);
3053 flt_ctx = filter->ctx;
3054 if (hlua_filter_from_payload(filter)) {
3055 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3056 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3057 }
3058 }
3059
3060 lua_pop(L, 1);
3061 return filter;
3062}
3063
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003064/* Copies <len> bytes of data present in the channel's buffer, starting at the
3065* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003066* responsibility to ensure <len> and <offset> are valid. It always return the
3067* length of the built string. <len> may be 0, in this case, an empty string is
3068* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003069*/
3070static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003071{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003072 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003073 luaL_Buffer b;
3074
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003075 block1 = len;
3076 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3077 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3078 block2 = len - block1;
3079
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003080 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003081 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3082 if (block2)
3083 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003084 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003085 return len;
3086}
3087
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003088/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3089 * function returns -1 if data cannot be copied. Otherwise, it returns the
3090 * number of bytes copied.
3091 */
3092static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3093{
3094 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003095
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003096 /* Nothing to do, just return */
3097 if (unlikely(istlen(str) == 0))
3098 goto end;
3099
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003100 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003101 ret = -1;
3102 goto end;
3103 }
3104 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3105
3106 end:
3107 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003108}
3109
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003110/* Removes <len> bytes of data at the absolute position <offset>.
3111 */
3112static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3113{
3114 size_t end = offset + len;
3115
3116 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3117 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3118 b_data(&chn->buf) - end, -len);
3119 b_sub(&chn->buf, len);
3120}
3121
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003122/* Copies input data in the channel's buffer. It is possible to set a specific
3123 * offset (0 by default) and a length (all remaining input data starting for the
3124 * offset by default). If there is not enough input data and more data can be
3125 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003126 *
3127 * From an action, All input data are considered. For a filter, the offset and
3128 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003129 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003130__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003131{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003132 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003133 struct filter *filter;
3134 size_t input, output;
3135 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003136
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003137 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003138
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003139 output = co_data(chn);
3140 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003141
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003142 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3143 if (filter && !hlua_filter_from_payload(filter))
3144 WILL_LJMP(lua_error(L));
3145
3146 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003147 if (lua_gettop(L) > 1) {
3148 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3149 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003150 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003151 offset += output;
3152 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003153 lua_pushfstring(L, "offset out of range.");
3154 WILL_LJMP(lua_error(L));
3155 }
3156 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003157 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003158 if (lua_gettop(L) == 3) {
3159 len = MAY_LJMP(luaL_checkinteger(L, 3));
3160 if (!len)
3161 goto dup;
3162 if (len == -1)
3163 len = global.tune.bufsize;
3164 if (len < 0) {
3165 lua_pushfstring(L, "length out of range.");
3166 WILL_LJMP(lua_error(L));
3167 }
3168 }
3169
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003170 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003171 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3172 /* Yield waiting for more data, as requested */
3173 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3174 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003175 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003176 }
3177
3178 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003179 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003180 return 1;
3181}
3182
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003183/* Copies the first line (including the trailing LF) of input data in the
3184 * channel's buffer. It is possible to set a specific offset (0 by default) and
3185 * a length (all remaining input data starting for the offset by default). If
3186 * there is not enough input data and more data can be received, the function
3187 * yields. If a length is explicitly specified, no more data are
3188 * copied. Otherwise, if no LF is found and more data can be received, this
3189 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003190 *
3191 * From an action, All input data are considered. For a filter, the offset and
3192 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003193 */
3194__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003195{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003196 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003197 struct filter *filter;
3198 size_t l, input, output;
3199 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003200
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003201 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003202 output = co_data(chn);
3203 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003204
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003205 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3206 if (filter && !hlua_filter_from_payload(filter))
3207 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003208
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003209 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210 if (lua_gettop(L) > 1) {
3211 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3212 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003213 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003214 offset += output;
3215 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003216 lua_pushfstring(L, "offset out of range.");
3217 WILL_LJMP(lua_error(L));
3218 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003219 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003220
3221 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003222 if (lua_gettop(L) == 3) {
3223 len = MAY_LJMP(luaL_checkinteger(L, 3));
3224 if (!len)
3225 goto dup;
3226 if (len == -1)
3227 len = global.tune.bufsize;
3228 if (len < 0) {
3229 lua_pushfstring(L, "length out of range.");
3230 WILL_LJMP(lua_error(L));
3231 }
3232 }
3233
3234 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003235 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003236 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003237 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003238 len = l+1;
3239 goto dup;
3240 }
3241 }
3242
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003243 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003244 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3245 /* Yield waiting for more data */
3246 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3247 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003248 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003249 }
3250
3251 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003252 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003253 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003254}
3255
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003256/* [ DEPRECATED ]
3257 *
3258 * Duplicate all input data foud in the channel's buffer. The data are not
3259 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003260 *
3261 * From an action, All input data are considered. For a filter, the offset and
3262 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003263 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003264__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003265{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003266 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003267 struct filter *filter;
3268 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003269
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003270 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003271 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003272 if (IS_HTX_STRM(chn_strm(chn))) {
3273 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3274 WILL_LJMP(lua_error(L));
3275 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003276
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003277 offset = co_data(chn);
3278 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003279
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003280 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3281 if (filter && !hlua_filter_from_payload(filter))
3282 WILL_LJMP(lua_error(L));
3283
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003284 if (!ci_data(chn) && channel_input_closed(chn)) {
3285 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003286 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003287 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003288
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003289 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003290 return 1;
3291}
3292
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003293/* [ DEPRECATED ]
3294 *
3295 * Get all input data foud in the channel's buffer. The data are removed from
3296 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3297 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003298 *
3299 * From an action, All input data are considered. For a filter, the offset and
3300 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003301 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003302__LJMP static int hlua_channel_get(lua_State *L)
3303{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003304 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003305 struct filter *filter;
3306 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003307 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003308
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003309 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003310 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3311 if (IS_HTX_STRM(chn_strm(chn))) {
3312 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3313 WILL_LJMP(lua_error(L));
3314 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003315
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003316 offset = co_data(chn);
3317 len = ci_data(chn);
3318
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003319 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3320 if (filter && !hlua_filter_from_payload(filter))
3321 WILL_LJMP(lua_error(L));
3322
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003323 if (!ci_data(chn) && channel_input_closed(chn)) {
3324 lua_pushnil(L);
3325 return 1;
3326 }
3327
3328 ret = _hlua_channel_dup(chn, L, offset, len);
3329 _hlua_channel_delete(chn, offset, ret);
3330 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003331}
3332
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003333/* This functions consumes and returns one line. If the channel is closed,
3334 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003335 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003336 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003337 *
3338 * From an action, All input data are considered. For a filter, the offset and
3339 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003340 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003341__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003342{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003343 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003344 struct filter *filter;
3345 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003346 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003347
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003348 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003349
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003350 offset = co_data(chn);
3351 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003352
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003353 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3354 if (filter && !hlua_filter_from_payload(filter))
3355 WILL_LJMP(lua_error(L));
3356
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003357 if (!ci_data(chn) && channel_input_closed(chn)) {
3358 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003359 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003360 }
3361
3362 for (l = 0; l < len; l++) {
3363 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3364 len = l+1;
3365 goto dup;
3366 }
3367 }
3368
3369 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3370 /* Yield waiting for more data */
3371 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3372 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003373
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003374 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003375 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003376 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003377 return 1;
3378}
3379
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003380/* [ DEPRECATED ]
3381 *
3382 * Check arguments for the function "hlua_channel_getline_yield".
3383 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003384__LJMP static int hlua_channel_getline(lua_State *L)
3385{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003386 struct channel *chn;
3387
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003388 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003389 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3390 if (IS_HTX_STRM(chn_strm(chn))) {
3391 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3392 WILL_LJMP(lua_error(L));
3393 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003394 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3395}
3396
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003397/* Retrieves a given amount of input data at the given offset. By default all
3398 * available input data are returned. The offset may be negactive to start from
3399 * the end of input data. The length may be -1 to set it to the maximum buffer
3400 * size.
3401 */
3402__LJMP static int hlua_channel_get_data(lua_State *L)
3403{
3404 struct channel *chn;
3405
3406 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3407 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3408 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3409 if (IS_HTX_STRM(chn_strm(chn))) {
3410 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3411 WILL_LJMP(lua_error(L));
3412 }
3413 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3414}
3415
3416/* Retrieves a given amount of input data at the given offset. By default all
3417 * available input data are returned. The offset may be negactive to start from
3418 * the end of input data. The length may be -1 to set it to the maximum buffer
3419 * size.
3420 */
3421__LJMP static int hlua_channel_get_line(lua_State *L)
3422{
3423 struct channel *chn;
3424
3425 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3426 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3427 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3428 if (IS_HTX_STRM(chn_strm(chn))) {
3429 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3430 WILL_LJMP(lua_error(L));
3431 }
3432 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3433}
3434
3435/* Appends a string into the input side of channel. It returns the length of the
3436 * written string, or -1 if the channel is closed or if the buffer size is too
3437 * little for the data. 0 may be returned if nothing is copied. This function
3438 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003439 *
3440 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003441 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003442__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003443{
Christopher Faulet23976d92021-08-06 09:59:49 +02003444 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003445 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003446 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003447 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003448 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003449
3450 MAY_LJMP(check_args(L, 2, "append"));
3451 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003452 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003453 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003454 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003455 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003456 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003457
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003458 offset = co_data(chn);
3459 len = ci_data(chn);
3460
3461 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3462 if (filter && !hlua_filter_from_payload(filter))
3463 WILL_LJMP(lua_error(L));
3464
3465 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3466 if (ret > 0 && filter) {
3467 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3468
3469 flt_update_offsets(filter, chn, ret);
3470 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3471 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003472 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003473 return 1;
3474}
3475
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003476/* Prepends a string into the input side of channel. It returns the length of the
3477 * written string, or -1 if the channel is closed or if the buffer size is too
3478 * little for the data. 0 may be returned if nothing is copied. This function
3479 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003480 *
3481 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003482 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003483__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003484{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003485 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003486 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003487 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003488 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003489 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003490
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003491 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003492 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003493 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3494 if (IS_HTX_STRM(chn_strm(chn))) {
3495 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3496 WILL_LJMP(lua_error(L));
3497 }
3498
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003499 offset = co_data(chn);
3500 len = ci_data(chn);
3501
3502 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3503 if (filter && !hlua_filter_from_payload(filter))
3504 WILL_LJMP(lua_error(L));
3505
3506 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3507 if (ret > 0 && filter) {
3508 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3509
3510 flt_update_offsets(filter, chn, ret);
3511 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3512 }
3513
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003514 lua_pushinteger(L, ret);
3515 return 1;
3516}
3517
3518/* Inserts a given amount of input data at the given offset by a string
3519 * content. By default the string is appended at the end of input data. It
3520 * returns the length of the written string, or -1 if the channel is closed or
3521 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003522 *
3523 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003524 */
3525__LJMP static int hlua_channel_insert_data(lua_State *L)
3526{
3527 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003528 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003529 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003530 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003531 int ret, offset;
3532
3533 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3534 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3535 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3536 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003537
3538 output = co_data(chn);
3539 input = ci_data(chn);
3540
3541 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3542 if (filter && !hlua_filter_from_payload(filter))
3543 WILL_LJMP(lua_error(L));
3544
3545 offset = input + output;
3546 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003547 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003548 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003549 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003550 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003551 if (offset < output || offset > output + input) {
3552 lua_pushfstring(L, "offset out of range.");
3553 WILL_LJMP(lua_error(L));
3554 }
3555 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003556 if (IS_HTX_STRM(chn_strm(chn))) {
3557 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3558 WILL_LJMP(lua_error(L));
3559 }
3560
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003561 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3562 if (ret > 0 && filter) {
3563 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003564
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003565 flt_update_offsets(filter, chn, ret);
3566 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003567 }
3568
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003569 lua_pushinteger(L, ret);
3570 return 1;
3571}
3572/* Replaces a given amount of input data at the given offset by a string
3573 * content. By default all remaining data are removed (offset = 0 and len =
3574 * -1). It returns the length of the written string, or -1 if the channel is
3575 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003576 *
3577 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003578 */
3579__LJMP static int hlua_channel_set_data(lua_State *L)
3580{
3581 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003582 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003583 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003584 size_t sz, input, output;
3585 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003586
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003587 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3588 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3589 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3590 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003591
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003592 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003593 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003594 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003595 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003596
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003597 output = co_data(chn);
3598 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003600 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3601 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003602 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603
3604 offset = output;
3605 if (lua_gettop(L) > 2) {
3606 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3607 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003608 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003609 offset += output;
3610 if (offset < output || offset > input + output) {
3611 lua_pushfstring(L, "offset out of range.");
3612 WILL_LJMP(lua_error(L));
3613 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003614 }
3615
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003616 len = output + input - offset;
3617 if (lua_gettop(L) == 4) {
3618 len = MAY_LJMP(luaL_checkinteger(L, 4));
3619 if (!len)
3620 goto set;
3621 if (len == -1)
3622 len = output + input - offset;
3623 if (len < 0 || offset + len > output + input) {
3624 lua_pushfstring(L, "length out of range.");
3625 WILL_LJMP(lua_error(L));
3626 }
3627 }
3628
3629 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003630 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003631 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003632 lua_pushinteger(L, -1);
3633 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003634 _hlua_channel_delete(chn, offset, len);
3635 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3636 if (filter) {
3637 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3638
3639 len -= (ret > 0 ? ret : 0);
3640 flt_update_offsets(filter, chn, -len);
3641 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3642 }
3643
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003644 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003645 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003646 return 1;
3647}
3648
3649/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003650 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003651 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003652 *
3653 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003654 */
3655__LJMP static int hlua_channel_del_data(lua_State *L)
3656{
3657 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003658 struct filter *filter;
3659 size_t input, output;
3660 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003661
3662 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3663 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3664 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003665
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003666 if (IS_HTX_STRM(chn_strm(chn))) {
3667 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3668 WILL_LJMP(lua_error(L));
3669 }
3670
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003671 output = co_data(chn);
3672 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003673
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003674 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3675 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003676 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003677
3678 offset = output;
3679 if (lua_gettop(L) > 2) {
3680 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3681 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003682 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003683 offset += output;
3684 if (offset < output || offset > input + output) {
3685 lua_pushfstring(L, "offset out of range.");
3686 WILL_LJMP(lua_error(L));
3687 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003688 }
3689
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003690 len = output + input - offset;
3691 if (lua_gettop(L) == 4) {
3692 len = MAY_LJMP(luaL_checkinteger(L, 4));
3693 if (!len)
3694 goto end;
3695 if (len == -1)
3696 len = output + input - offset;
3697 if (len < 0 || offset + len > output + input) {
3698 lua_pushfstring(L, "length out of range.");
3699 WILL_LJMP(lua_error(L));
3700 }
3701 }
3702
3703 _hlua_channel_delete(chn, offset, len);
3704 if (filter) {
3705 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3706
3707 flt_update_offsets(filter, chn, -len);
3708 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3709 }
3710
3711 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003712 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003713 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003714}
3715
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003716/* Append data in the output side of the buffer. This data is immediately
3717 * sent. The function returns the amount of data written. If the buffer
3718 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003719 * if the channel is closed.
3720 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003721__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003722{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003723 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003724 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003725 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003726 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003727 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003728 struct hlua *hlua;
3729
3730 /* Get hlua struct, or NULL if we execute from main lua state */
3731 hlua = hlua_gethlua(L);
3732 if (!hlua) {
3733 lua_pushnil(L);
3734 return 1;
3735 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003736
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003737 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3738 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3739 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003740
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003741 offset = co_data(chn);
3742 len = ci_data(chn);
3743
3744 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3745 if (filter && !hlua_filter_from_payload(filter))
3746 WILL_LJMP(lua_error(L));
3747
3748
Willy Tarreau47860ed2015-03-10 14:07:50 +01003749 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003750 lua_pushinteger(L, -1);
3751 return 1;
3752 }
3753
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003754 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003755 if (len > sz -l) {
3756 if (filter) {
3757 lua_pushinteger(L, -1);
3758 return 1;
3759 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003760 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003761 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003762
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003763 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003764 if (ret == -1) {
3765 lua_pop(L, 1);
3766 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003767 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003768 }
3769 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003770 if (filter) {
3771 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3772
3773
3774 flt_update_offsets(filter, chn, ret);
3775 FLT_OFF(filter, chn) += ret;
3776 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3777 }
3778 else
3779 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003780
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003781 l += ret;
3782 lua_pop(L, 1);
3783 lua_pushinteger(L, l);
3784 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003785
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003786 if (l < sz) {
3787 /* Yield only if the channel's output is not empty.
3788 * Otherwise it means we cannot add more data. */
3789 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003790 return 1;
3791
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003792 /* If we are waiting for space in the response buffer, we
3793 * must set the flag WAKERESWR. This flag required the task
3794 * wake up if any activity is detected on the response buffer.
3795 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003796 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003797 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003798 else
3799 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003800 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003801 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003802
3803 return 1;
3804}
3805
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003806/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003807 * yield the LUA process, and resume it without checking the
3808 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003809 *
3810 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003811 */
3812__LJMP static int hlua_channel_send(lua_State *L)
3813{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003814 struct channel *chn;
3815
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003816 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003817 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3818 if (IS_HTX_STRM(chn_strm(chn))) {
3819 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3820 WILL_LJMP(lua_error(L));
3821 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003822 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003823 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003824}
3825
3826/* This function forward and amount of butes. The data pass from
3827 * the input side of the buffer to the output side, and can be
3828 * forwarded. This function never fails.
3829 *
3830 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003831 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003832 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003833__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003834{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003835 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003836 struct filter *filter;
3837 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003838 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003839 struct hlua *hlua;
3840
3841 /* Get hlua struct, or NULL if we execute from main lua state */
3842 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003843 if (!hlua) {
3844 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003845 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003846 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003847
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003848 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003849 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003850 l = MAY_LJMP(luaL_checkinteger(L, -1));
3851
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003852 offset = co_data(chn);
3853 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003854
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003855 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3856 if (filter && !hlua_filter_from_payload(filter))
3857 WILL_LJMP(lua_error(L));
3858
3859 max = fwd - l;
3860 if (max > len)
3861 max = len;
3862
3863 if (filter) {
3864 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3865
3866 FLT_OFF(filter, chn) += max;
3867 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3868 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3869 }
3870 else
3871 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003872
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003873 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003874 lua_pop(L, 1);
3875 lua_pushinteger(L, l);
3876
3877 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003878 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003879 /* The the input channel or the output channel are closed, we
3880 * must return the amount of data forwarded.
3881 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003882 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003883 return 1;
3884
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003885 /* If we are waiting for space data in the response buffer, we
3886 * must set the flag WAKERESWR. This flag required the task
3887 * wake up if any activity is detected on the response buffer.
3888 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003889 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003890 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003891 else
3892 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003893
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003894 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003895 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003896 }
3897
3898 return 1;
3899}
3900
3901/* Just check the input and prepare the stack for the previous
3902 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003903 *
3904 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003905 */
3906__LJMP static int hlua_channel_forward(lua_State *L)
3907{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003908 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003909
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003910 MAY_LJMP(check_args(L, 2, "forward"));
3911 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3912 if (IS_HTX_STRM(chn_strm(chn))) {
3913 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3914 WILL_LJMP(lua_error(L));
3915 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003916 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003917 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003918}
3919
3920/* Just returns the number of bytes available in the input
3921 * side of the buffer. This function never fails.
3922 */
3923__LJMP static int hlua_channel_get_in_len(lua_State *L)
3924{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003925 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003926 struct filter *filter;
3927 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003928
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003929 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003930 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003931
3932 output = co_data(chn);
3933 input = ci_data(chn);
3934 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3935 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3936 lua_pushinteger(L, input);
3937 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003938 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003939
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003940 lua_pushinteger(L, htx->data - co_data(chn));
3941 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003942 return 1;
3943}
3944
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003945/* Returns true if the channel is full. */
3946__LJMP static int hlua_channel_is_full(lua_State *L)
3947{
3948 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003949
3950 MAY_LJMP(check_args(L, 1, "is_full"));
3951 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003952 /* ignore the reserve, we are not on a producer side (ie in an
3953 * applet).
3954 */
3955 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003956 return 1;
3957}
3958
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003959/* Returns true if the channel may still receive data. */
3960__LJMP static int hlua_channel_may_recv(lua_State *L)
3961{
3962 struct channel *chn;
3963
3964 MAY_LJMP(check_args(L, 1, "may_recv"));
3965 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3966 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3967 return 1;
3968}
3969
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003970/* Returns true if the channel is the response channel. */
3971__LJMP static int hlua_channel_is_resp(lua_State *L)
3972{
3973 struct channel *chn;
3974
3975 MAY_LJMP(check_args(L, 1, "is_resp"));
3976 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3977
3978 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3979 return 1;
3980}
3981
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003982/* Just returns the number of bytes available in the output
3983 * side of the buffer. This function never fails.
3984 */
3985__LJMP static int hlua_channel_get_out_len(lua_State *L)
3986{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003987 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003988 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003989
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003990 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003991 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003992
3993 output = co_data(chn);
3994 input = ci_data(chn);
3995 hlua_channel_filter(L, 1, chn, &output, &input);
3996
3997 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003998 return 1;
3999}
4000
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004001/*
4002 *
4003 *
4004 * Class Fetches
4005 *
4006 *
4007 */
4008
4009/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004010 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004011 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004012__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004013{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004014 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004015}
4016
4017/* This function creates and push in the stack a fetch object according
4018 * with a current TXN.
4019 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004020static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004021{
Willy Tarreau7073c472015-04-06 11:15:40 +02004022 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004023
4024 /* Check stack size. */
4025 if (!lua_checkstack(L, 3))
4026 return 0;
4027
4028 /* Create the object: obj[0] = userdata.
4029 * Note that the base of the Fetches object is the
4030 * transaction object.
4031 */
4032 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004033 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004034 lua_rawseti(L, -2, 0);
4035
Willy Tarreau7073c472015-04-06 11:15:40 +02004036 hsmp->s = txn->s;
4037 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004038 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004039 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004040
4041 /* Pop a class sesison metatable and affect it to the userdata. */
4042 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4043 lua_setmetatable(L, -2);
4044
4045 return 1;
4046}
4047
4048/* This function is an LUA binding. It is called with each sample-fetch.
4049 * It uses closure argument to store the associated sample-fetch. It
4050 * returns only one argument or throws an error. An error is thrown
4051 * only if an error is encountered during the argument parsing. If
4052 * the "sample-fetch" function fails, nil is returned.
4053 */
4054__LJMP static int hlua_run_sample_fetch(lua_State *L)
4055{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004056 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004057 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004058 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004059 int i;
4060 struct sample smp;
4061
4062 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004063 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004064
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004065 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004066 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004067
Thierry FOURNIERca988662015-12-20 18:43:03 +01004068 /* Check execution authorization. */
4069 if (f->use & SMP_USE_HTTP_ANY &&
4070 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4071 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4072 "is not available in Lua services", f->kw);
4073 WILL_LJMP(lua_error(L));
4074 }
4075
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004076 /* Get extra arguments. */
4077 for (i = 0; i < lua_gettop(L) - 1; i++) {
4078 if (i >= ARGM_NBARGS)
4079 break;
4080 hlua_lua2arg(L, i + 2, &args[i]);
4081 }
4082 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004083 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004084
4085 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004086 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004087
4088 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004089 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004090 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004091 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004092 }
4093
4094 /* Initialise the sample. */
4095 memset(&smp, 0, sizeof(smp));
4096
4097 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004098 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004099 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004100 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004101 lua_pushstring(L, "");
4102 else
4103 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004104 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004105 }
4106
4107 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004108 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004109 hlua_smp2lua_str(L, &smp);
4110 else
4111 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004112
4113 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004114 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004115 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004116
4117 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004118 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004119 WILL_LJMP(lua_error(L));
4120 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004121}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004122
4123/*
4124 *
4125 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004126 * Class Converters
4127 *
4128 *
4129 */
4130
4131/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004132 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004133 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004134__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004135{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004136 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004137}
4138
4139/* This function creates and push in the stack a Converters object
4140 * according with a current TXN.
4141 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004142static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004143{
Willy Tarreau7073c472015-04-06 11:15:40 +02004144 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004145
4146 /* Check stack size. */
4147 if (!lua_checkstack(L, 3))
4148 return 0;
4149
4150 /* Create the object: obj[0] = userdata.
4151 * Note that the base of the Converters object is the
4152 * same than the TXN object.
4153 */
4154 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004155 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004156 lua_rawseti(L, -2, 0);
4157
Willy Tarreau7073c472015-04-06 11:15:40 +02004158 hsmp->s = txn->s;
4159 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004160 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004161 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004162
Willy Tarreau87b09662015-04-03 00:22:06 +02004163 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004164 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4165 lua_setmetatable(L, -2);
4166
4167 return 1;
4168}
4169
4170/* This function is an LUA binding. It is called with each converter.
4171 * It uses closure argument to store the associated converter. It
4172 * returns only one argument or throws an error. An error is thrown
4173 * only if an error is encountered during the argument parsing. If
4174 * the converter function function fails, nil is returned.
4175 */
4176__LJMP static int hlua_run_sample_conv(lua_State *L)
4177{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004178 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004179 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004180 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004181 int i;
4182 struct sample smp;
4183
4184 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004185 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004186
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004187 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004188 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004189
4190 /* Get extra arguments. */
4191 for (i = 0; i < lua_gettop(L) - 2; i++) {
4192 if (i >= ARGM_NBARGS)
4193 break;
4194 hlua_lua2arg(L, i + 3, &args[i]);
4195 }
4196 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004197 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004198
4199 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004200 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004201
4202 /* Run the special args checker. */
4203 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4204 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004205 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004206 }
4207
4208 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004209 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210 if (!hlua_lua2smp(L, 2, &smp)) {
4211 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004212 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004213 }
4214
Willy Tarreau1777ea62016-03-10 16:15:46 +01004215 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4216
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004217 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004218 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004219 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004220 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004221 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004222 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004223 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4224 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004225 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004226 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004227 }
4228
4229 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004230 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004231 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004232 lua_pushstring(L, "");
4233 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004234 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004235 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004236 }
4237
4238 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004239 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004240 hlua_smp2lua_str(L, &smp);
4241 else
4242 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004243 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004244 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004245 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004246
4247 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004248 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004249 WILL_LJMP(lua_error(L));
4250 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004251}
4252
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004253/*
4254 *
4255 *
4256 * Class AppletTCP
4257 *
4258 *
4259 */
4260
4261/* Returns a struct hlua_txn if the stack entry "ud" is
4262 * a class stream, otherwise it throws an error.
4263 */
4264__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4265{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004266 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004267}
4268
4269/* This function creates and push in the stack an Applet object
4270 * according with a current TXN.
4271 */
4272static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4273{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004274 struct hlua_appctx *luactx;
Christopher Faulet86e1c332021-12-20 17:09:39 +01004275 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004276 struct stream *s = si_strm(si);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004277 struct proxy *p;
4278
4279 ALREADY_CHECKED(s);
4280 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004281
4282 /* Check stack size. */
4283 if (!lua_checkstack(L, 3))
4284 return 0;
4285
4286 /* Create the object: obj[0] = userdata.
4287 * Note that the base of the Converters object is the
4288 * same than the TXN object.
4289 */
4290 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004291 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004292 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004293 luactx->appctx = ctx;
4294 luactx->htxn.s = s;
4295 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004296
4297 /* Create the "f" field that contains a list of fetches. */
4298 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004299 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004300 return 0;
4301 lua_settable(L, -3);
4302
4303 /* Create the "sf" field that contains a list of stringsafe fetches. */
4304 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004305 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004306 return 0;
4307 lua_settable(L, -3);
4308
4309 /* Create the "c" field that contains a list of converters. */
4310 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004311 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004312 return 0;
4313 lua_settable(L, -3);
4314
4315 /* Create the "sc" field that contains a list of stringsafe converters. */
4316 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004317 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004318 return 0;
4319 lua_settable(L, -3);
4320
4321 /* Pop a class stream metatable and affect it to the table. */
4322 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4323 lua_setmetatable(L, -2);
4324
4325 return 1;
4326}
4327
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004328__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4329{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004330 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004331 struct stream *s;
4332 const char *name;
4333 size_t len;
4334 struct sample smp;
4335
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004336 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4337 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004338
4339 /* It is useles to retrieve the stream, but this function
4340 * runs only in a stream context.
4341 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004342 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004343 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004344 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004345
4346 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004347 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004348 hlua_lua2smp(L, 3, &smp);
4349
4350 /* Store the sample in a variable. */
4351 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004352
4353 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4354 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4355 else
4356 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4357
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004358 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004359}
4360
4361__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4362{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004363 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004364 struct stream *s;
4365 const char *name;
4366 size_t len;
4367 struct sample smp;
4368
4369 MAY_LJMP(check_args(L, 2, "unset_var"));
4370
4371 /* It is useles to retrieve the stream, but this function
4372 * runs only in a stream context.
4373 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004374 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004375 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004376 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004377
4378 /* Unset the variable. */
4379 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004380 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4381 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004382}
4383
4384__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4385{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004386 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004387 struct stream *s;
4388 const char *name;
4389 size_t len;
4390 struct sample smp;
4391
4392 MAY_LJMP(check_args(L, 2, "get_var"));
4393
4394 /* It is useles to retrieve the stream, but this function
4395 * runs only in a stream context.
4396 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004397 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004398 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004399 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004400
4401 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004402 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004403 lua_pushnil(L);
4404 return 1;
4405 }
4406
4407 return hlua_smp2lua(L, &smp);
4408}
4409
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004410__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4411{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004412 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4413 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004414 struct hlua *hlua;
4415
4416 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004417 if (!s->hlua)
4418 return 0;
4419 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004420
4421 MAY_LJMP(check_args(L, 2, "set_priv"));
4422
4423 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004424 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004425
4426 /* Get and store new value. */
4427 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4428 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4429
4430 return 0;
4431}
4432
4433__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4434{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004435 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4436 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004437 struct hlua *hlua;
4438
4439 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004440 if (!s->hlua) {
4441 lua_pushnil(L);
4442 return 1;
4443 }
4444 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004445
4446 /* Push configuration index in the stack. */
4447 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4448
4449 return 1;
4450}
4451
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004452/* If expected data not yet available, it returns a yield. This function
4453 * consumes the data in the buffer. It returns a string containing the
4454 * data. This string can be empty.
4455 */
4456__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4457{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004458 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004459 struct stream_interface *si = cs_si(luactx->appctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004460 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004461 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004462 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004463 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004464 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004465
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004466 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004467 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004468
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004469 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004470 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004471 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004472 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004473 }
4474
4475 /* End of data: commit the total strings and return. */
4476 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004477 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004478 return 1;
4479 }
4480
4481 /* Ensure that the block 2 length is usable. */
4482 if (ret == 1)
4483 len2 = 0;
4484
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004485 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 luaL_addlstring(&luactx->b, blk1, len1);
4487 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004488
4489 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004490 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004491 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004492 return 1;
4493}
4494
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004495/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004496__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4497{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004498 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004499
4500 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004501 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004502
4503 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4504}
4505
4506/* If expected data not yet available, it returns a yield. This function
4507 * consumes the data in the buffer. It returns a string containing the
4508 * data. This string can be empty.
4509 */
4510__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4511{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004512 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004513 struct stream_interface *si = cs_si(luactx->appctx->owner);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004514 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004515 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004516 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004517 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004518 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004519 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004520
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004521 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004522 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004523
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004524 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004525 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004526 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004527 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004528 }
4529
4530 /* End of data: commit the total strings and return. */
4531 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004532 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004533 return 1;
4534 }
4535
4536 /* Ensure that the block 2 length is usable. */
4537 if (ret == 1)
4538 len2 = 0;
4539
4540 if (len == -1) {
4541
4542 /* If len == -1, catenate all the data avalaile and
4543 * yield because we want to get all the data until
4544 * the end of data stream.
4545 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004546 luaL_addlstring(&luactx->b, blk1, len1);
4547 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004548 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004549 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004550 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004551
4552 } else {
4553
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004554 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004555 if (len1 > len)
4556 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004557 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004558 len -= len1;
4559
4560 /* Copy the second block. */
4561 if (len2 > len)
4562 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004563 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004564 len -= len2;
4565
4566 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004567 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004568
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004569 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004570 if (len > 0) {
4571 lua_pushinteger(L, len);
4572 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004573 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004574 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004575 }
4576
4577 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004578 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004579 return 1;
4580 }
4581
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004582 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004583 hlua_pusherror(L, "Lua: internal error");
4584 WILL_LJMP(lua_error(L));
4585 return 0;
4586}
4587
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004588/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004589__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4590{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004591 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004592 int len = -1;
4593
4594 if (lua_gettop(L) > 2)
4595 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4596 if (lua_gettop(L) >= 2) {
4597 len = MAY_LJMP(luaL_checkinteger(L, 2));
4598 lua_pop(L, 1);
4599 }
4600
4601 /* Confirm or set the required length */
4602 lua_pushinteger(L, len);
4603
4604 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004605 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004606
4607 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4608}
4609
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004610/* Append data in the output side of the buffer. This data is immediately
4611 * sent. The function returns the amount of data written. If the buffer
4612 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004613 * if the channel is closed.
4614 */
4615__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4616{
4617 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004618 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004619 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4620 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004621 struct stream_interface *si = cs_si(luactx->appctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004622 struct channel *chn = si_ic(si);
4623 int max;
4624
4625 /* Get the max amount of data which can write as input in the channel. */
4626 max = channel_recv_max(chn);
4627 if (max > (len - l))
4628 max = len - l;
4629
4630 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004631 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004632
4633 /* update counters. */
4634 l += max;
4635 lua_pop(L, 1);
4636 lua_pushinteger(L, l);
4637
4638 /* If some data is not send, declares the situation to the
4639 * applet, and returns a yield.
4640 */
4641 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004642 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004643 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004644 }
4645
4646 return 1;
4647}
4648
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004649/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004650 * yield the LUA process, and resume it without checking the
4651 * input arguments.
4652 */
4653__LJMP static int hlua_applet_tcp_send(lua_State *L)
4654{
4655 MAY_LJMP(check_args(L, 2, "send"));
4656 lua_pushinteger(L, 0);
4657
4658 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4659}
4660
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004661/*
4662 *
4663 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004664 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004665 *
4666 *
4667 */
4668
4669/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004670 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004671 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004672__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004673{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004674 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004675}
4676
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004677/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004678 * according with a current TXN.
4679 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004680static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004681{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004682 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004683 struct hlua_txn htxn;
Christopher Faulet86e1c332021-12-20 17:09:39 +01004684 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004685 struct stream *s = si_strm(si);
4686 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004687 struct htx *htx;
4688 struct htx_blk *blk;
4689 struct htx_sl *sl;
4690 struct ist path;
4691 unsigned long long len = 0;
4692 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004693 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004694
4695 /* Check stack size. */
4696 if (!lua_checkstack(L, 3))
4697 return 0;
4698
4699 /* Create the object: obj[0] = userdata.
4700 * Note that the base of the Converters object is the
4701 * same than the TXN object.
4702 */
4703 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004704 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004705 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004706 luactx->appctx = ctx;
4707 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4708 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4709 luactx->htxn.s = s;
4710 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004711
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004712 /* Create the "f" field that contains a list of fetches. */
4713 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004714 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004715 return 0;
4716 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004717
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004718 /* Create the "sf" field that contains a list of stringsafe fetches. */
4719 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004720 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004721 return 0;
4722 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004723
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004724 /* Create the "c" field that contains a list of converters. */
4725 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004726 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004727 return 0;
4728 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004729
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004730 /* Create the "sc" field that contains a list of stringsafe converters. */
4731 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004732 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004733 return 0;
4734 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004735
Christopher Fauleta2097962019-07-15 16:25:33 +02004736 htx = htxbuf(&s->req.buf);
4737 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004738 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004739 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004740
Christopher Fauleta2097962019-07-15 16:25:33 +02004741 /* Stores the request method. */
4742 lua_pushstring(L, "method");
4743 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4744 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004745
Christopher Fauleta2097962019-07-15 16:25:33 +02004746 /* Stores the http version. */
4747 lua_pushstring(L, "version");
4748 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4749 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004750
Christopher Fauleta2097962019-07-15 16:25:33 +02004751 /* creates an array of headers. hlua_http_get_headers() crates and push
4752 * the array on the top of the stack.
4753 */
4754 lua_pushstring(L, "headers");
4755 htxn.s = s;
4756 htxn.p = px;
4757 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004758 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004759 return 0;
4760 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004761
Amaury Denoyellec453f952021-07-06 11:40:12 +02004762 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4763 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004764 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004765 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004766
Christopher Fauleta2097962019-07-15 16:25:33 +02004767 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004768 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004769 q = p;
4770 while (q < end && *q != '?')
4771 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004772
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004773 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004774 lua_pushstring(L, "path");
4775 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004776 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004777
Christopher Fauleta2097962019-07-15 16:25:33 +02004778 /* Stores the query string. */
4779 lua_pushstring(L, "qs");
4780 if (*q == '?')
4781 q++;
4782 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004783 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004784 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004785
Christopher Fauleta2097962019-07-15 16:25:33 +02004786 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4787 struct htx_blk *blk = htx_get_blk(htx, pos);
4788 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004789
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004790 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004791 break;
4792 if (type == HTX_BLK_DATA)
4793 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004794 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004795 if (htx->extra != ULLONG_MAX)
4796 len += htx->extra;
4797
4798 /* Stores the request path. */
4799 lua_pushstring(L, "length");
4800 lua_pushinteger(L, len);
4801 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004802
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004803 /* Create an empty array of HTTP request headers. */
4804 lua_pushstring(L, "response");
4805 lua_newtable(L);
4806 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004807
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004808 /* Pop a class stream metatable and affect it to the table. */
4809 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4810 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004811
4812 return 1;
4813}
4814
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004815__LJMP static int hlua_applet_http_set_var(lua_State *L)
4816{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004817 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004818 struct stream *s;
4819 const char *name;
4820 size_t len;
4821 struct sample smp;
4822
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004823 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4824 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004825
4826 /* It is useles to retrieve the stream, but this function
4827 * runs only in a stream context.
4828 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004829 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004830 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004831 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004832
4833 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004834 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004835 hlua_lua2smp(L, 3, &smp);
4836
4837 /* Store the sample in a variable. */
4838 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004839
4840 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4841 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4842 else
4843 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4844
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004845 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004846}
4847
4848__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4849{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004850 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004851 struct stream *s;
4852 const char *name;
4853 size_t len;
4854 struct sample smp;
4855
4856 MAY_LJMP(check_args(L, 2, "unset_var"));
4857
4858 /* It is useles to retrieve the stream, but this function
4859 * runs only in a stream context.
4860 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004861 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004862 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004863 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004864
4865 /* Unset the variable. */
4866 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004867 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4868 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004869}
4870
4871__LJMP static int hlua_applet_http_get_var(lua_State *L)
4872{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004873 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004874 struct stream *s;
4875 const char *name;
4876 size_t len;
4877 struct sample smp;
4878
4879 MAY_LJMP(check_args(L, 2, "get_var"));
4880
4881 /* It is useles to retrieve the stream, but this function
4882 * runs only in a stream context.
4883 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004884 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004885 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004886 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004887
4888 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004889 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004890 lua_pushnil(L);
4891 return 1;
4892 }
4893
4894 return hlua_smp2lua(L, &smp);
4895}
4896
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004897__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4898{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004899 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4900 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004901 struct hlua *hlua;
4902
4903 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004904 if (!s->hlua)
4905 return 0;
4906 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004907
4908 MAY_LJMP(check_args(L, 2, "set_priv"));
4909
4910 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004911 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004912
4913 /* Get and store new value. */
4914 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4915 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4916
4917 return 0;
4918}
4919
4920__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4921{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004922 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4923 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004924 struct hlua *hlua;
4925
4926 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004927 if (!s->hlua) {
4928 lua_pushnil(L);
4929 return 1;
4930 }
4931 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004932
4933 /* Push configuration index in the stack. */
4934 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4935
4936 return 1;
4937}
4938
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004939/* If expected data not yet available, it returns a yield. This function
4940 * consumes the data in the buffer. It returns a string containing the
4941 * data. This string can be empty.
4942 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004943__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004944{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004945 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004946 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004947 struct channel *req = si_oc(si);
4948 struct htx *htx;
4949 struct htx_blk *blk;
4950 size_t count;
4951 int stop = 0;
4952
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004953 htx = htx_from_buf(&req->buf);
4954 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004955 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004956
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004957 while (count && !stop && blk) {
4958 enum htx_blk_type type = htx_get_blk_type(blk);
4959 uint32_t sz = htx_get_blksz(blk);
4960 struct ist v;
4961 uint32_t vlen;
4962 char *nl;
4963
4964 vlen = sz;
4965 if (vlen > count) {
4966 if (type != HTX_BLK_DATA)
4967 break;
4968 vlen = count;
4969 }
4970
4971 switch (type) {
4972 case HTX_BLK_UNUSED:
4973 break;
4974
4975 case HTX_BLK_DATA:
4976 v = htx_get_blk_value(htx, blk);
4977 v.len = vlen;
4978 nl = istchr(v, '\n');
4979 if (nl != NULL) {
4980 stop = 1;
4981 vlen = nl - v.ptr + 1;
4982 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004983 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004984 break;
4985
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004986 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004987 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004988 stop = 1;
4989 break;
4990
4991 default:
4992 break;
4993 }
4994
Willy Tarreau84240042022-02-28 16:51:23 +01004995 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004996 count -= vlen;
4997 if (sz == vlen)
4998 blk = htx_remove_blk(htx, blk);
4999 else {
5000 htx_cut_data_blk(htx, blk, vlen);
5001 break;
5002 }
5003 }
5004
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005005 /* The message was fully consumed and no more data are expected
5006 * (EOM flag set).
5007 */
5008 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5009 stop = 1;
5010
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005011 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005012 if (!stop) {
5013 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005014 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005015 }
5016
5017 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005018 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005019 return 1;
5020}
5021
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005022
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005023/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005024__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005025{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005026 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005027
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005028 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005029 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005030
Christopher Fauleta2097962019-07-15 16:25:33 +02005031 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005032}
5033
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005034/* If expected data not yet available, it returns a yield. This function
5035 * consumes the data in the buffer. It returns a string containing the
5036 * data. This string can be empty.
5037 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005038__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005039{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005040 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005041 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005042 struct channel *req = si_oc(si);
5043 struct htx *htx;
5044 struct htx_blk *blk;
5045 size_t count;
5046 int len;
5047
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005048 htx = htx_from_buf(&req->buf);
5049 len = MAY_LJMP(luaL_checkinteger(L, 2));
5050 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005051 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005052 while (count && len && blk) {
5053 enum htx_blk_type type = htx_get_blk_type(blk);
5054 uint32_t sz = htx_get_blksz(blk);
5055 struct ist v;
5056 uint32_t vlen;
5057
5058 vlen = sz;
5059 if (len > 0 && vlen > len)
5060 vlen = len;
5061 if (vlen > count) {
5062 if (type != HTX_BLK_DATA)
5063 break;
5064 vlen = count;
5065 }
5066
5067 switch (type) {
5068 case HTX_BLK_UNUSED:
5069 break;
5070
5071 case HTX_BLK_DATA:
5072 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005073 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005074 break;
5075
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005076 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005077 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005078 len = 0;
5079 break;
5080
5081 default:
5082 break;
5083 }
5084
Willy Tarreau84240042022-02-28 16:51:23 +01005085 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005086 count -= vlen;
5087 if (len > 0)
5088 len -= vlen;
5089 if (sz == vlen)
5090 blk = htx_remove_blk(htx, blk);
5091 else {
5092 htx_cut_data_blk(htx, blk, vlen);
5093 break;
5094 }
5095 }
5096
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005097 /* The message was fully consumed and no more data are expected
5098 * (EOM flag set).
5099 */
5100 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5101 len = 0;
5102
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005103 htx_to_buf(htx, &req->buf);
5104
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005105 /* If we are no other data available, yield waiting for new data. */
5106 if (len) {
5107 if (len > 0) {
5108 lua_pushinteger(L, len);
5109 lua_replace(L, 2);
5110 }
5111 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005112 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005113 }
5114
5115 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005116 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005117 return 1;
5118}
5119
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005120/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005121__LJMP static int hlua_applet_http_recv(lua_State *L)
5122{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005123 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005124 int len = -1;
5125
5126 /* Check arguments. */
5127 if (lua_gettop(L) > 2)
5128 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5129 if (lua_gettop(L) >= 2) {
5130 len = MAY_LJMP(luaL_checkinteger(L, 2));
5131 lua_pop(L, 1);
5132 }
5133
Christopher Fauleta2097962019-07-15 16:25:33 +02005134 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005135
Christopher Fauleta2097962019-07-15 16:25:33 +02005136 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005137 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005138
Christopher Fauleta2097962019-07-15 16:25:33 +02005139 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005140}
5141
5142/* Append data in the output side of the buffer. This data is immediately
5143 * sent. The function returns the amount of data written. If the buffer
5144 * cannot contain the data, the function yields. The function returns -1
5145 * if the channel is closed.
5146 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005147__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005148{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005149 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005150 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005151 struct channel *res = si_ic(si);
5152 struct htx *htx = htx_from_buf(&res->buf);
5153 const char *data;
5154 size_t len;
5155 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5156 int max;
5157
Christopher Faulet9060fc02019-07-03 11:39:30 +02005158 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005159 if (!max)
5160 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005161
5162 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5163
5164 /* Get the max amount of data which can write as input in the channel. */
5165 if (max > (len - l))
5166 max = len - l;
5167
5168 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005169 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005170 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005171
5172 /* update counters. */
5173 l += max;
5174 lua_pop(L, 1);
5175 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005176
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005177 /* If some data is not send, declares the situation to the
5178 * applet, and returns a yield.
5179 */
5180 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005181 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005182 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005183 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005184 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005185 }
5186
Christopher Fauleta2097962019-07-15 16:25:33 +02005187 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005188 return 1;
5189}
5190
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005191/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005192 * yield the LUA process, and resume it without checking the
5193 * input arguments.
5194 */
5195__LJMP static int hlua_applet_http_send(lua_State *L)
5196{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005197 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005198
5199 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005200 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005201 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5202 WILL_LJMP(lua_error(L));
5203 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005204
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005205 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005206 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005207
Christopher Fauleta2097962019-07-15 16:25:33 +02005208 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005209}
5210
5211__LJMP static int hlua_applet_http_addheader(lua_State *L)
5212{
5213 const char *name;
5214 int ret;
5215
5216 MAY_LJMP(hlua_checkapplet_http(L, 1));
5217 name = MAY_LJMP(luaL_checkstring(L, 2));
5218 MAY_LJMP(luaL_checkstring(L, 3));
5219
5220 /* Push in the stack the "response" entry. */
5221 ret = lua_getfield(L, 1, "response");
5222 if (ret != LUA_TTABLE) {
5223 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5224 "is expected as an array. %s found", lua_typename(L, ret));
5225 WILL_LJMP(lua_error(L));
5226 }
5227
5228 /* check if the header is already registered if it is not
5229 * the case, register it.
5230 */
5231 ret = lua_getfield(L, -1, name);
5232 if (ret == LUA_TNIL) {
5233
5234 /* Entry not found. */
5235 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5236
5237 /* Insert the new header name in the array in the top of the stack.
5238 * It left the new array in the top of the stack.
5239 */
5240 lua_newtable(L);
5241 lua_pushvalue(L, 2);
5242 lua_pushvalue(L, -2);
5243 lua_settable(L, -4);
5244
5245 } else if (ret != LUA_TTABLE) {
5246
5247 /* corruption error. */
5248 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5249 "is expected as an array. %s found", name, lua_typename(L, ret));
5250 WILL_LJMP(lua_error(L));
5251 }
5252
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005253 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005254 * the header value as new entry.
5255 */
5256 lua_pushvalue(L, 3);
5257 ret = lua_rawlen(L, -2);
5258 lua_rawseti(L, -2, ret + 1);
5259 lua_pushboolean(L, 1);
5260 return 1;
5261}
5262
5263__LJMP static int hlua_applet_http_status(lua_State *L)
5264{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005265 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005266 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005267 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005268
5269 if (status < 100 || status > 599) {
5270 lua_pushboolean(L, 0);
5271 return 1;
5272 }
5273
Willy Tarreau7e702d12021-04-28 17:59:21 +02005274 luactx->appctx->ctx.hlua_apphttp.status = status;
5275 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005276 lua_pushboolean(L, 1);
5277 return 1;
5278}
5279
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005280
Christopher Fauleta2097962019-07-15 16:25:33 +02005281__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005282{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005283 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005284 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005285 struct channel *res = si_ic(si);
5286 struct htx *htx;
5287 struct htx_sl *sl;
5288 struct h1m h1m;
5289 const char *status, *reason;
5290 const char *name, *value;
5291 size_t nlen, vlen;
5292 unsigned int flags;
5293
5294 /* Send the message at once. */
5295 htx = htx_from_buf(&res->buf);
5296 h1m_init_res(&h1m);
5297
5298 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005299 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5300 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005301 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005302 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5303 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005304 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5305 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5306 }
5307 else {
5308 flags = HTX_SL_F_IS_RESP;
5309 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5310 }
5311 if (!sl) {
5312 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005313 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005314 WILL_LJMP(lua_error(L));
5315 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005316 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005317
5318 /* Get the array associated to the field "response" in the object AppletHTTP. */
5319 lua_pushvalue(L, 0);
5320 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5321 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005322 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005323 WILL_LJMP(lua_error(L));
5324 }
5325
5326 /* Browse the list of headers. */
5327 lua_pushnil(L);
5328 while(lua_next(L, -2) != 0) {
5329 /* We expect a string as -2. */
5330 if (lua_type(L, -2) != LUA_TSTRING) {
5331 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005332 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005333 lua_typename(L, lua_type(L, -2)));
5334 WILL_LJMP(lua_error(L));
5335 }
5336 name = lua_tolstring(L, -2, &nlen);
5337
5338 /* We expect an array as -1. */
5339 if (lua_type(L, -1) != LUA_TTABLE) {
5340 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 +02005341 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342 name,
5343 lua_typename(L, lua_type(L, -1)));
5344 WILL_LJMP(lua_error(L));
5345 }
5346
5347 /* Browse the table who is on the top of the stack. */
5348 lua_pushnil(L);
5349 while(lua_next(L, -2) != 0) {
5350 int id;
5351
5352 /* We expect a number as -2. */
5353 if (lua_type(L, -2) != LUA_TNUMBER) {
5354 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 +02005355 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005356 name,
5357 lua_typename(L, lua_type(L, -2)));
5358 WILL_LJMP(lua_error(L));
5359 }
5360 id = lua_tointeger(L, -2);
5361
5362 /* We expect a string as -2. */
5363 if (lua_type(L, -1) != LUA_TSTRING) {
5364 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 +02005365 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005366 name, id,
5367 lua_typename(L, lua_type(L, -1)));
5368 WILL_LJMP(lua_error(L));
5369 }
5370 value = lua_tolstring(L, -1, &vlen);
5371
5372 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005373 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5374 int ret;
5375
5376 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5377 if (ret < 0) {
5378 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5379 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5380 name);
5381 WILL_LJMP(lua_error(L));
5382 }
5383 else if (ret == 0)
5384 goto next; /* Skip it */
5385 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005386 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5387 struct ist v = ist2(value, vlen);
5388 int ret;
5389
5390 ret = h1_parse_cont_len_header(&h1m, &v);
5391 if (ret < 0) {
5392 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005393 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005394 name);
5395 WILL_LJMP(lua_error(L));
5396 }
5397 else if (ret == 0)
5398 goto next; /* Skip it */
5399 }
5400
5401 /* Add a new header */
5402 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5403 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005404 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005405 name);
5406 WILL_LJMP(lua_error(L));
5407 }
5408 next:
5409 /* Remove the array from the stack, and get next element with a remaining string. */
5410 lua_pop(L, 1);
5411 }
5412
5413 /* Remove the array from the stack, and get next element with a remaining string. */
5414 lua_pop(L, 1);
5415 }
5416
5417 if (h1m.flags & H1_MF_CHNK)
5418 h1m.flags &= ~H1_MF_CLEN;
5419 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5420 h1m.flags |= H1_MF_XFER_LEN;
5421
5422 /* Uset HTX start-line flags */
5423 if (h1m.flags & H1_MF_XFER_ENC)
5424 flags |= HTX_SL_F_XFER_ENC;
5425 if (h1m.flags & H1_MF_XFER_LEN) {
5426 flags |= HTX_SL_F_XFER_LEN;
5427 if (h1m.flags & H1_MF_CHNK)
5428 flags |= HTX_SL_F_CHNK;
5429 else if (h1m.flags & H1_MF_CLEN)
5430 flags |= HTX_SL_F_CLEN;
5431 if (h1m.body_len == 0)
5432 flags |= HTX_SL_F_BODYLESS;
5433 }
5434 sl->flags |= flags;
5435
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005436 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005437 * and the status code implies the presence of a message body, we must
5438 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005439 * for the keepalive compliance. If the applet announces a transfer-encoding
5440 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005441 */
5442 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005443 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5444 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5445 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005446 /* Add a new header */
5447 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5448 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5449 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005450 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005451 WILL_LJMP(lua_error(L));
5452 }
5453 }
5454
5455 /* Finalize headers. */
5456 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5457 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005458 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005459 WILL_LJMP(lua_error(L));
5460 }
5461
5462 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5463 b_reset(&res->buf);
5464 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5465 WILL_LJMP(lua_error(L));
5466 }
5467
5468 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005469 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005470
5471 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005472 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005473 return 0;
5474
5475}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005476/* We will build the status line and the headers of the HTTP response.
5477 * We will try send at once if its not possible, we give back the hand
5478 * waiting for more room.
5479 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005480__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005481{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005482 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005483 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005484 struct channel *res = si_ic(si);
5485
5486 if (co_data(res)) {
5487 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005488 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005489 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005490 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005491}
5492
5493
Christopher Fauleta2097962019-07-15 16:25:33 +02005494__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005495{
Christopher Fauleta2097962019-07-15 16:25:33 +02005496 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005497}
5498
Christopher Fauleta2097962019-07-15 16:25:33 +02005499/*
5500 *
5501 *
5502 * Class HTTP
5503 *
5504 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005505 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005506
5507/* Returns a struct hlua_txn if the stack entry "ud" is
5508 * a class stream, otherwise it throws an error.
5509 */
5510__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005511{
Christopher Fauleta2097962019-07-15 16:25:33 +02005512 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5513}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005514
Christopher Fauleta2097962019-07-15 16:25:33 +02005515/* This function creates and push in the stack a HTTP object
5516 * according with a current TXN.
5517 */
5518static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5519{
5520 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005521
Christopher Fauleta2097962019-07-15 16:25:33 +02005522 /* Check stack size. */
5523 if (!lua_checkstack(L, 3))
5524 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005525
Christopher Fauleta2097962019-07-15 16:25:33 +02005526 /* Create the object: obj[0] = userdata.
5527 * Note that the base of the Converters object is the
5528 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005529 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005530 lua_newtable(L);
5531 htxn = lua_newuserdata(L, sizeof(*htxn));
5532 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005533
5534 htxn->s = txn->s;
5535 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005536 htxn->dir = txn->dir;
5537 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005538
5539 /* Pop a class stream metatable and affect it to the table. */
5540 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5541 lua_setmetatable(L, -2);
5542
5543 return 1;
5544}
5545
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005546/* This function creates and returns an array containing the status-line
5547 * elements. This function does not fails.
5548 */
5549__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5550{
5551 /* Create the table. */
5552 lua_newtable(L);
5553
5554 if (sl->flags & HTX_SL_F_IS_RESP) {
5555 lua_pushstring(L, "version");
5556 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5557 lua_settable(L, -3);
5558 lua_pushstring(L, "code");
5559 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5560 lua_settable(L, -3);
5561 lua_pushstring(L, "reason");
5562 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5563 lua_settable(L, -3);
5564 }
5565 else {
5566 lua_pushstring(L, "method");
5567 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5568 lua_settable(L, -3);
5569 lua_pushstring(L, "uri");
5570 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5571 lua_settable(L, -3);
5572 lua_pushstring(L, "version");
5573 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5574 lua_settable(L, -3);
5575 }
5576 return 1;
5577}
5578
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005579/* This function creates ans returns an array of HTTP headers.
5580 * This function does not fails. It is used as wrapper with the
5581 * 2 following functions.
5582 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005583__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005584{
Christopher Fauleta2097962019-07-15 16:25:33 +02005585 struct htx *htx;
5586 int32_t pos;
5587
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005588 /* Create the table. */
5589 lua_newtable(L);
5590
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005591
Christopher Fauleta2097962019-07-15 16:25:33 +02005592 htx = htxbuf(&msg->chn->buf);
5593 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5594 struct htx_blk *blk = htx_get_blk(htx, pos);
5595 enum htx_blk_type type = htx_get_blk_type(blk);
5596 struct ist n, v;
5597 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005598
Christopher Fauleta2097962019-07-15 16:25:33 +02005599 if (type == HTX_BLK_HDR) {
5600 n = htx_get_blk_name(htx,blk);
5601 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005602 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005603 else if (type == HTX_BLK_EOH)
5604 break;
5605 else
5606 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005607
Christopher Fauleta2097962019-07-15 16:25:33 +02005608 /* Check for existing entry:
5609 * assume that the table is on the top of the stack, and
5610 * push the key in the stack, the function lua_gettable()
5611 * perform the lookup.
5612 */
5613 lua_pushlstring(L, n.ptr, n.len);
5614 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005615
Christopher Fauleta2097962019-07-15 16:25:33 +02005616 switch (lua_type(L, -1)) {
5617 case LUA_TNIL:
5618 /* Table not found, create it. */
5619 lua_pop(L, 1); /* remove the nil value. */
5620 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5621 lua_newtable(L); /* create and push empty table. */
5622 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5623 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5624 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005625 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005626
Christopher Fauleta2097962019-07-15 16:25:33 +02005627 case LUA_TTABLE:
5628 /* Entry found: push the value in the table. */
5629 len = lua_rawlen(L, -1);
5630 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5631 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5632 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5633 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005634
Christopher Fauleta2097962019-07-15 16:25:33 +02005635 default:
5636 /* Other cases are errors. */
5637 hlua_pusherror(L, "internal error during the parsing of headers.");
5638 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005639 }
5640 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005641 return 1;
5642}
5643
5644__LJMP static int hlua_http_req_get_headers(lua_State *L)
5645{
5646 struct hlua_txn *htxn;
5647
5648 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5649 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5650
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005651 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005652 WILL_LJMP(lua_error(L));
5653
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005654 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005655}
5656
5657__LJMP static int hlua_http_res_get_headers(lua_State *L)
5658{
5659 struct hlua_txn *htxn;
5660
5661 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5662 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5663
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005664 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005665 WILL_LJMP(lua_error(L));
5666
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005667 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005668}
5669
5670/* This function replace full header, or just a value in
5671 * the request or in the response. It is a wrapper fir the
5672 * 4 following functions.
5673 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005674__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005675{
5676 size_t name_len;
5677 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5678 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5679 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005680 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005681 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005682
Dragan Dosen26743032019-04-30 15:54:36 +02005683 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005684 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5685
Christopher Fauleta2097962019-07-15 16:25:33 +02005686 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005687 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005688 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005689 return 0;
5690}
5691
5692__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5693{
5694 struct hlua_txn *htxn;
5695
5696 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5697 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5698
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005699 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005700 WILL_LJMP(lua_error(L));
5701
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005702 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005703}
5704
5705__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5706{
5707 struct hlua_txn *htxn;
5708
5709 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5710 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5711
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005712 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005713 WILL_LJMP(lua_error(L));
5714
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005715 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005716}
5717
5718__LJMP static int hlua_http_req_rep_val(lua_State *L)
5719{
5720 struct hlua_txn *htxn;
5721
5722 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5723 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5724
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005725 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005726 WILL_LJMP(lua_error(L));
5727
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005728 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005729}
5730
5731__LJMP static int hlua_http_res_rep_val(lua_State *L)
5732{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005733 struct hlua_txn *htxn;
5734
5735 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5736 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5737
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005738 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005739 WILL_LJMP(lua_error(L));
5740
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005741 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005742}
5743
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005744/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005745 * It is a wrapper for the 2 following functions.
5746 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005747__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005748{
5749 size_t len;
5750 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005751 struct htx *htx = htxbuf(&msg->chn->buf);
5752 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005753
Christopher Fauleta2097962019-07-15 16:25:33 +02005754 ctx.blk = NULL;
5755 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5756 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005757 return 0;
5758}
5759
5760__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5761{
5762 struct hlua_txn *htxn;
5763
5764 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5765 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5766
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005767 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005768 WILL_LJMP(lua_error(L));
5769
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005770 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005771}
5772
5773__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5774{
5775 struct hlua_txn *htxn;
5776
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005777 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005778 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5779
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005780 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005781 WILL_LJMP(lua_error(L));
5782
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005783 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005784}
5785
5786/* This function adds an header. It is a wrapper used by
5787 * the 2 following functions.
5788 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005789__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005790{
5791 size_t name_len;
5792 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5793 size_t value_len;
5794 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005795 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005796
Christopher Fauleta2097962019-07-15 16:25:33 +02005797 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5798 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005799 return 0;
5800}
5801
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005802__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5803{
5804 struct hlua_txn *htxn;
5805
5806 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5807 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5808
5809 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5810 WILL_LJMP(lua_error(L));
5811
5812 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5813}
5814
5815__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5816{
5817 struct hlua_txn *htxn;
5818
5819 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5820 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5821
5822 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5823 WILL_LJMP(lua_error(L));
5824
5825 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5826}
5827
5828static int hlua_http_req_set_hdr(lua_State *L)
5829{
5830 struct hlua_txn *htxn;
5831
5832 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5833 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5834
5835 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5836 WILL_LJMP(lua_error(L));
5837
5838 hlua_http_del_hdr(L, &htxn->s->txn->req);
5839 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5840}
5841
5842static int hlua_http_res_set_hdr(lua_State *L)
5843{
5844 struct hlua_txn *htxn;
5845
5846 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5847 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5848
5849 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5850 WILL_LJMP(lua_error(L));
5851
5852 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5853 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5854}
5855
5856/* This function set the method. */
5857static int hlua_http_req_set_meth(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 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5867 return 1;
5868}
5869
5870/* This function set the method. */
5871static int hlua_http_req_set_path(lua_State *L)
5872{
5873 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5874 size_t name_len;
5875 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5876
5877 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5878 WILL_LJMP(lua_error(L));
5879
5880 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5881 return 1;
5882}
5883
5884/* This function set the query-string. */
5885static int hlua_http_req_set_query(lua_State *L)
5886{
5887 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5888 size_t name_len;
5889 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5890
5891 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5892 WILL_LJMP(lua_error(L));
5893
5894 /* Check length. */
5895 if (name_len > trash.size - 1) {
5896 lua_pushboolean(L, 0);
5897 return 1;
5898 }
5899
5900 /* Add the mark question as prefix. */
5901 chunk_reset(&trash);
5902 trash.area[trash.data++] = '?';
5903 memcpy(trash.area + trash.data, name, name_len);
5904 trash.data += name_len;
5905
5906 lua_pushboolean(L,
5907 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5908 return 1;
5909}
5910
5911/* This function set the uri. */
5912static int hlua_http_req_set_uri(lua_State *L)
5913{
5914 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5915 size_t name_len;
5916 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5917
5918 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5919 WILL_LJMP(lua_error(L));
5920
5921 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5922 return 1;
5923}
5924
5925/* This function set the response code & optionally reason. */
5926static int hlua_http_res_set_status(lua_State *L)
5927{
5928 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5929 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5930 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5931 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5932
5933 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5934 WILL_LJMP(lua_error(L));
5935
5936 http_res_set_status(code, reason, htxn->s);
5937 return 0;
5938}
5939
5940/*
5941 *
5942 *
5943 * Class HTTPMessage
5944 *
5945 *
5946 */
5947
5948/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5949 * otherwise it throws an error.
5950 */
5951__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5952{
5953 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5954}
5955
5956/* Creates and pushes on the stack a HTTP object according with a current TXN.
5957 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005958static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005959{
5960 /* Check stack size. */
5961 if (!lua_checkstack(L, 3))
5962 return 0;
5963
5964 lua_newtable(L);
5965 lua_pushlightuserdata(L, msg);
5966 lua_rawseti(L, -2, 0);
5967
5968 /* Create the "channel" field that contains the request channel object. */
5969 lua_pushstring(L, "channel");
5970 if (!hlua_channel_new(L, msg->chn))
5971 return 0;
5972 lua_rawset(L, -3);
5973
5974 /* Pop a class stream metatable and affect it to the table. */
5975 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5976 lua_setmetatable(L, -2);
5977
5978 return 1;
5979}
5980
5981/* Helper function returning a filter attached to the HTTP message at the
5982 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05005983 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005984 * filled with output and input length respectively.
5985 */
5986static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5987{
5988 struct channel *chn = msg->chn;
5989 struct htx *htx = htxbuf(&chn->buf);
5990 struct filter *filter = NULL;
5991
5992 *offset = co_data(msg->chn);
5993 *len = htx->data - co_data(msg->chn);
5994
5995 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5996 filter = lua_touserdata (L, -1);
5997 if (msg->msg_state >= HTTP_MSG_DATA) {
5998 struct hlua_flt_ctx *flt_ctx = filter->ctx;
5999
6000 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6001 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6002 }
6003 }
6004
6005 lua_pop(L, 1);
6006 return filter;
6007}
6008
6009/* Returns true if the channel attached to the HTTP message is the response
6010 * channel.
6011 */
6012__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6013{
6014 struct http_msg *msg;
6015
6016 MAY_LJMP(check_args(L, 1, "is_resp"));
6017 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6018
6019 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6020 return 1;
6021}
6022
6023/* Returns an array containing the elements status-line of the HTTP message. It relies
6024 * on hlua_http_get_stline().
6025 */
6026__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6027{
6028 struct http_msg *msg;
6029 struct htx *htx;
6030 struct htx_sl *sl;
6031
6032 MAY_LJMP(check_args(L, 1, "get_stline"));
6033 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6034
6035 if (msg->msg_state > HTTP_MSG_BODY)
6036 WILL_LJMP(lua_error(L));
6037
6038 htx = htxbuf(&msg->chn->buf);
6039 sl = http_get_stline(htx);
6040 if (!sl)
6041 return 0;
6042 return hlua_http_get_stline(L, sl);
6043}
6044
6045/* Returns an array containing all headers of the HTTP message. it relies on
6046 * hlua_http_get_headers().
6047 */
6048__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6049{
6050 struct http_msg *msg;
6051
6052 MAY_LJMP(check_args(L, 1, "get_headers"));
6053 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6054
6055 if (msg->msg_state > HTTP_MSG_BODY)
6056 WILL_LJMP(lua_error(L));
6057
6058 return hlua_http_get_headers(L, msg);
6059}
6060
6061/* Deletes all occurrences of an header in the HTTP message matching on its
6062 * name. It relies on hlua_http_del_hdr().
6063 */
6064__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6065{
6066 struct http_msg *msg;
6067
6068 MAY_LJMP(check_args(L, 2, "del_header"));
6069 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6070
6071 if (msg->msg_state > HTTP_MSG_BODY)
6072 WILL_LJMP(lua_error(L));
6073
6074 return hlua_http_del_hdr(L, msg);
6075}
6076
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006077/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006078 * message given its name against a regex and replaces it if it matches. It
6079 * relies on hlua_http_rep_hdr().
6080 */
6081__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6082{
6083 struct http_msg *msg;
6084
6085 MAY_LJMP(check_args(L, 4, "rep_header"));
6086 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6087
6088 if (msg->msg_state > HTTP_MSG_BODY)
6089 WILL_LJMP(lua_error(L));
6090
6091 return hlua_http_rep_hdr(L, msg, 1);
6092}
6093
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006094/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006095 * message given its name against a regex and replaces it if it matches. It
6096 * relies on hlua_http_rep_hdr().
6097 */
6098__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6099{
6100 struct http_msg *msg;
6101
6102 MAY_LJMP(check_args(L, 4, "rep_value"));
6103 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6104
6105 if (msg->msg_state > HTTP_MSG_BODY)
6106 WILL_LJMP(lua_error(L));
6107
6108 return hlua_http_rep_hdr(L, msg, 0);
6109}
6110
6111/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6112__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6113{
6114 struct http_msg *msg;
6115
6116 MAY_LJMP(check_args(L, 3, "add_header"));
6117 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6118
6119 if (msg->msg_state > HTTP_MSG_BODY)
6120 WILL_LJMP(lua_error(L));
6121
6122 return hlua_http_add_hdr(L, msg);
6123}
6124
6125/* Add an header in the HTTP message removing existing headers with the same
6126 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6127 */
6128__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6129{
6130 struct http_msg *msg;
6131
6132 MAY_LJMP(check_args(L, 3, "set_header"));
6133 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6134
6135 if (msg->msg_state > HTTP_MSG_BODY)
6136 WILL_LJMP(lua_error(L));
6137
6138 hlua_http_del_hdr(L, msg);
6139 return hlua_http_add_hdr(L, msg);
6140}
6141
6142/* Rewrites the request method. It relies on http_req_replace_stline(). */
6143__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6144{
6145 struct stream *s;
6146 struct http_msg *msg;
6147 const char *name;
6148 size_t name_len;
6149
6150 MAY_LJMP(check_args(L, 2, "set_method"));
6151 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6152 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6153
6154 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6155 WILL_LJMP(lua_error(L));
6156
6157 s = chn_strm(msg->chn);
6158 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6159 return 1;
6160}
6161
6162/* Rewrites the request path. It relies on http_req_replace_stline(). */
6163__LJMP static int hlua_http_msg_set_path(lua_State *L)
6164{
6165 struct stream *s;
6166 struct http_msg *msg;
6167 const char *name;
6168 size_t name_len;
6169
6170 MAY_LJMP(check_args(L, 2, "set_path"));
6171 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6172 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6173
6174 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6175 WILL_LJMP(lua_error(L));
6176
6177 s = chn_strm(msg->chn);
6178 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6179 return 1;
6180}
6181
6182/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6183__LJMP static int hlua_http_msg_set_query(lua_State *L)
6184{
6185 struct stream *s;
6186 struct http_msg *msg;
6187 const char *name;
6188 size_t name_len;
6189
6190 MAY_LJMP(check_args(L, 2, "set_query"));
6191 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6192 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6193
6194 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6195 WILL_LJMP(lua_error(L));
6196
6197 /* Check length. */
6198 if (name_len > trash.size - 1) {
6199 lua_pushboolean(L, 0);
6200 return 1;
6201 }
6202
6203 /* Add the mark question as prefix. */
6204 chunk_reset(&trash);
6205 trash.area[trash.data++] = '?';
6206 memcpy(trash.area + trash.data, name, name_len);
6207 trash.data += name_len;
6208
6209 s = chn_strm(msg->chn);
6210 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6211 return 1;
6212}
6213
6214/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6215__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6216{
6217 struct stream *s;
6218 struct http_msg *msg;
6219 const char *name;
6220 size_t name_len;
6221
6222 MAY_LJMP(check_args(L, 2, "set_uri"));
6223 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6224 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6225
6226 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6227 WILL_LJMP(lua_error(L));
6228
6229 s = chn_strm(msg->chn);
6230 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6231 return 1;
6232}
6233
6234/* Rewrites the response status code. It relies on http_res_set_status(). */
6235__LJMP static int hlua_http_msg_set_status(lua_State *L)
6236{
6237 struct http_msg *msg;
6238 unsigned int code;
6239 const char *reason;
6240 size_t reason_len;
6241
6242 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6243 code = MAY_LJMP(luaL_checkinteger(L, 2));
6244 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6245
6246 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6247 WILL_LJMP(lua_error(L));
6248
6249 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6250 return 1;
6251}
6252
6253/* Returns true if the HTTP message is full. */
6254__LJMP static int hlua_http_msg_is_full(lua_State *L)
6255{
6256 struct http_msg *msg;
6257
6258 MAY_LJMP(check_args(L, 1, "is_full"));
6259 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6260 lua_pushboolean(L, channel_full(msg->chn, 0));
6261 return 1;
6262}
6263
6264/* Returns true if the HTTP message may still receive data. */
6265__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6266{
6267 struct http_msg *msg;
6268 struct htx *htx;
6269
6270 MAY_LJMP(check_args(L, 1, "may_recv"));
6271 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6272 htx = htxbuf(&msg->chn->buf);
6273 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6274 return 1;
6275}
6276
6277/* Returns true if the HTTP message EOM was received */
6278__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6279{
6280 struct http_msg *msg;
6281 struct htx *htx;
6282
6283 MAY_LJMP(check_args(L, 1, "may_recv"));
6284 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6285 htx = htxbuf(&msg->chn->buf);
6286 lua_pushboolean(L, !htx_expect_more(htx));
6287 return 1;
6288}
6289
6290/* Returns the number of bytes available in the input side of the HTTP
6291 * message. This function never fails.
6292 */
6293__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6294{
6295 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006296 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006297
6298 MAY_LJMP(check_args(L, 1, "input"));
6299 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006300 hlua_http_msg_filter(L, 1, msg, &output, &input);
6301 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006302 return 1;
6303}
6304
6305/* Returns the number of bytes available in the output side of the HTTP
6306 * message. This function never fails.
6307 */
6308__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6309{
6310 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006311 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006312
6313 MAY_LJMP(check_args(L, 1, "output"));
6314 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006315 hlua_http_msg_filter(L, 1, msg, &output, &input);
6316 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006317 return 1;
6318}
6319
6320/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6321 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006322 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006323 * block. This function is called during the payload filtering, so the headers
6324 * are already scheduled for output (from the filter point of view).
6325 */
6326static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6327{
6328 struct htx *htx = htxbuf(&msg->chn->buf);
6329 struct htx_blk *blk;
6330 struct htx_ret htxret;
6331 luaL_Buffer b;
6332 int ret = 0;
6333
6334 luaL_buffinit(L, &b);
6335 htxret = htx_find_offset(htx, offset);
6336 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6337 enum htx_blk_type type = htx_get_blk_type(blk);
6338 struct ist v;
6339
6340 switch (type) {
6341 case HTX_BLK_UNUSED:
6342 break;
6343
6344 case HTX_BLK_DATA:
6345 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006346 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006347 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006348
6349 luaL_addlstring(&b, v.ptr, v.len);
6350 ret += v.len;
6351 break;
6352
6353 default:
vishnu0af4bd72021-10-24 06:46:24 +05306354 if (!ret)
6355 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006356 goto end;
6357 }
6358 offset = 0;
6359 }
6360
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006361end:
vishnu0af4bd72021-10-24 06:46:24 +05306362 if (!ret && (htx->flags & HTX_FL_EOM))
6363 goto no_data;
6364 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006365 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306366
6367 no_data:
6368 /* Remove the empty string and push nil on the stack */
6369 lua_pop(L, 1);
6370 lua_pushnil(L);
6371 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006372}
6373
6374/* Copies the string <str> to the HTTP message <msg> at the offset
6375 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006376 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006377 * the filter context.
6378 */
6379static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6380{
6381 struct htx *htx = htx_from_buf(&msg->chn->buf);
6382 struct htx_ret htxret;
6383 int /*max, */ret = 0;
6384
6385 /* Nothing to do, just return */
6386 if (unlikely(istlen(str) == 0))
6387 goto end;
6388
6389 if (istlen(str) > htx_free_data_space(htx)) {
6390 ret = -1;
6391 goto end;
6392 }
6393
6394 htxret = htx_find_offset(htx, offset);
6395 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6396 if (!htx_add_last_data(htx, str))
6397 goto end;
6398 }
6399 else {
6400 struct ist v = htx_get_blk_value(htx, htxret.blk);
6401 v.ptr += htxret.ret;
6402 v.len = 0;
6403 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6404 goto end;
6405 }
6406 ret = str.len;
6407 if (ret) {
6408 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6409 flt_update_offsets(filter, msg->chn, ret);
6410 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6411 }
6412
6413 end:
6414 htx_to_buf(htx, &msg->chn->buf);
6415 return ret;
6416}
6417
6418/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6419 * position <offset>. It stops on the first non-DATA HTX block. This function is
6420 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006421 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006422 * update the filter context.
6423 */
6424static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6425{
6426 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6427 struct htx *htx = htx_from_buf(&msg->chn->buf);
6428 struct htx_blk *blk;
6429 struct htx_ret htxret;
6430 size_t ret = 0;
6431
6432 /* Be sure <len> is always the amount of DATA to remove */
6433 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6434 htx_truncate(htx, offset);
6435 ret = len;
6436 goto end;
6437 }
6438
6439 htxret = htx_find_offset(htx, offset);
6440 blk = htxret.blk;
6441 if (htxret.ret) {
6442 struct ist v;
6443
6444 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6445 goto end;
6446 v = htx_get_blk_value(htx, blk);
6447 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006448 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006449 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006450 len -= v.len;
6451 ret += v.len;
6452 }
6453
6454
6455 while (blk && len) {
6456 enum htx_blk_type type = htx_get_blk_type(blk);
6457 uint32_t sz = htx_get_blksz(blk);
6458
6459 switch (type) {
6460 case HTX_BLK_UNUSED:
6461 break;
6462
6463 case HTX_BLK_DATA:
6464 if (len < sz) {
6465 htx_cut_data_blk(htx, blk, len);
6466 ret += len;
6467 goto end;
6468 }
6469 break;
6470
6471 default:
6472 goto end;
6473 }
6474
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006475 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006476 len -= sz;
6477 ret += sz;
6478 blk = htx_remove_blk(htx, blk);
6479 }
6480
6481end:
6482 flt_update_offsets(filter, msg->chn, -ret);
6483 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6484 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6485 * to loose the EOM flag if the message is empty.
6486 */
6487}
6488
6489/* Copies input data found in an HTTP message. Unlike the channel function used
6490 * to duplicate raw data, this one can only be called inside a filter, from
6491 * http_payload callback. So it cannot yield. An exception is returned if it is
6492 * called from another callback. If nothing was copied, a nil value is pushed on
6493 * the stack.
6494 */
6495__LJMP static int hlua_http_msg_get_body(lua_State *L)
6496{
6497 struct http_msg *msg;
6498 struct filter *filter;
6499 size_t output, input;
6500 int offset, len;
6501
6502 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6503 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6504 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6505
6506 if (msg->msg_state < HTTP_MSG_DATA)
6507 WILL_LJMP(lua_error(L));
6508
6509 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6510 if (!filter || !hlua_filter_from_payload(filter))
6511 WILL_LJMP(lua_error(L));
6512
6513 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6514 lua_pushnil(L);
6515 return 1;
6516 }
6517
6518 offset = output;
6519 if (lua_gettop(L) > 1) {
6520 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6521 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006522 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006523 offset += output;
6524 if (offset < output || offset > input + output) {
6525 lua_pushfstring(L, "offset out of range.");
6526 WILL_LJMP(lua_error(L));
6527 }
6528 }
6529 len = output + input - offset;
6530 if (lua_gettop(L) == 3) {
6531 len = MAY_LJMP(luaL_checkinteger(L, 3));
6532 if (!len)
6533 goto dup;
6534 if (len == -1)
6535 len = global.tune.bufsize;
6536 if (len < 0) {
6537 lua_pushfstring(L, "length out of range.");
6538 WILL_LJMP(lua_error(L));
6539 }
6540 }
6541
6542 dup:
6543 _hlua_http_msg_dup(msg, L, offset, len);
6544 return 1;
6545}
6546
6547/* Appends a string to the HTTP message, after all existing DATA blocks but
6548 * before the trailers, if any. It returns the amount of data written or -1 if
6549 * nothing was copied. Unlike the channel function used to append data, this one
6550 * can only be called inside a filter, from http_payload callback. So it cannot
6551 * yield. An exception is returned if it is called from another callback.
6552 */
6553__LJMP static int hlua_http_msg_append(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, "append"));
6562 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6563
6564 if (msg->msg_state < HTTP_MSG_DATA)
6565 WILL_LJMP(lua_error(L));
6566
6567 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))
6570 WILL_LJMP(lua_error(L));
6571
6572 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6573 lua_pushinteger(L, ret);
6574 return 1;
6575}
6576
6577/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6578 * returns the amount of data written or -1 if nothing was copied. Unlike the
6579 * channel function used to prepend data, this one can only be called inside a
6580 * filter, from http_payload callback. So it cannot yield. An exception is
6581 * returned if it is called from another callback.
6582 */
6583__LJMP static int hlua_http_msg_prepend(lua_State *L)
6584{
6585 struct http_msg *msg;
6586 struct filter *filter;
6587 const char *str;
6588 size_t offset, len, sz;
6589 int ret;
6590
6591 MAY_LJMP(check_args(L, 2, "prepend"));
6592 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006593
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006594 if (msg->msg_state < HTTP_MSG_DATA)
6595 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006596
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006597 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6598 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6599 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006600 WILL_LJMP(lua_error(L));
6601
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006602 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6603 lua_pushinteger(L, ret);
6604 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006605}
6606
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006607/* Inserts a string to the HTTP message at a given offset. By default the string
6608 * is appended at the end of DATA blocks. It returns the amount of data written
6609 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6610 * this one can only be called inside a filter, from http_payload callback. So
6611 * it cannot yield. An exception is returned if it is called from another
6612 * callback.
6613 */
6614__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006615{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006616 struct http_msg *msg;
6617 struct filter *filter;
6618 const char *str;
6619 size_t input, output, sz;
6620 int offset;
6621 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006622
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006623 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6624 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6625 MAY_LJMP(check_args(L, 2, "insert"));
6626 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006627
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006628 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006629 WILL_LJMP(lua_error(L));
6630
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006631 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6632 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6633 if (!filter || !hlua_filter_from_payload(filter))
6634 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006635
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006636 offset = input + output;
6637 if (lua_gettop(L) > 2) {
6638 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6639 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006640 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006641 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006642 if (offset < output || offset > output + input) {
6643 lua_pushfstring(L, "offset out of range.");
6644 WILL_LJMP(lua_error(L));
6645 }
6646 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006647
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006648 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6649 lua_pushinteger(L, ret);
6650 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006651}
6652
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006653/* Removes a given amount of data from the HTTP message at a given offset. By
6654 * default all DATA blocks are removed. It returns the amount of data
6655 * removed. Unlike the channel function used to remove data, this one can only
6656 * be called inside a filter, from http_payload callback. So it cannot yield. An
6657 * exception is returned if it is called from another callback.
6658 */
6659__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006660{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006661 struct http_msg *msg;
6662 struct filter *filter;
6663 size_t input, output;
6664 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006665
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006666 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6667 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6668 MAY_LJMP(check_args(L, 2, "insert"));
6669 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006670
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006671 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006672 WILL_LJMP(lua_error(L));
6673
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006674 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6675 if (!filter || !hlua_filter_from_payload(filter))
6676 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006677
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006678 offset = input + output;
6679 if (lua_gettop(L) > 2) {
6680 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6681 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006682 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006683 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006684 if (offset < output || offset > output + input) {
6685 lua_pushfstring(L, "offset out of range.");
6686 WILL_LJMP(lua_error(L));
6687 }
6688 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006689
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006690 len = output + input - offset;
6691 if (lua_gettop(L) == 4) {
6692 len = MAY_LJMP(luaL_checkinteger(L, 4));
6693 if (!len)
6694 goto end;
6695 if (len == -1)
6696 len = output + input - offset;
6697 if (len < 0 || offset + len > output + input) {
6698 lua_pushfstring(L, "length out of range.");
6699 WILL_LJMP(lua_error(L));
6700 }
6701 }
6702
6703 _hlua_http_msg_delete(msg, filter, offset, len);
6704
6705 end:
6706 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006707 return 1;
6708}
6709
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006710/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006711 * all remaining data are removed, accordingly to the filter context. It returns
6712 * the amount of data written or -1 if nothing was copied. Unlike the channel
6713 * function used to replace data, this one can only be called inside a filter,
6714 * from http_payload callback. So it cannot yield. An exception is returned if
6715 * it is called from another callback.
6716 */
6717__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006718{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006719 struct http_msg *msg;
6720 struct filter *filter;
6721 struct htx *htx;
6722 const char *str;
6723 size_t input, output, sz;
6724 int offset, len;
6725 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006726
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006727 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6728 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6729 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6730
6731 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006732 WILL_LJMP(lua_error(L));
6733
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006734 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6735 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6736 if (!filter || !hlua_filter_from_payload(filter))
6737 WILL_LJMP(lua_error(L));
6738
6739 offset = output;
6740 if (lua_gettop(L) > 2) {
6741 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6742 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006743 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006744 offset += output;
6745 if (offset < output || offset > input + output) {
6746 lua_pushfstring(L, "offset out of range.");
6747 WILL_LJMP(lua_error(L));
6748 }
6749 }
6750
6751 len = output + input - offset;
6752 if (lua_gettop(L) == 4) {
6753 len = MAY_LJMP(luaL_checkinteger(L, 4));
6754 if (!len)
6755 goto set;
6756 if (len == -1)
6757 len = output + input - offset;
6758 if (len < 0 || offset + len > output + input) {
6759 lua_pushfstring(L, "length out of range.");
6760 WILL_LJMP(lua_error(L));
6761 }
6762 }
6763
6764 set:
6765 /* Be sure we can copied the string once input data will be removed. */
6766 htx = htx_from_buf(&msg->chn->buf);
6767 if (sz > htx_free_data_space(htx) + len)
6768 lua_pushinteger(L, -1);
6769 else {
6770 _hlua_http_msg_delete(msg, filter, offset, len);
6771 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6772 lua_pushinteger(L, ret);
6773 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006774 return 1;
6775}
6776
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006777/* Prepends data into an HTTP message and forward it, from the filter point of
6778 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6779 * the channel function used to send data, this one can only be called inside a
6780 * filter, from http_payload callback. So it cannot yield. An exception is
6781 * returned if it is called from another callback.
6782 */
6783__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006784{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006785 struct http_msg *msg;
6786 struct filter *filter;
6787 struct htx *htx;
6788 const char *str;
6789 size_t offset, len, sz;
6790 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006791
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006792 MAY_LJMP(check_args(L, 2, "send"));
6793 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6794
6795 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006796 WILL_LJMP(lua_error(L));
6797
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006798 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6799 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6800 if (!filter || !hlua_filter_from_payload(filter))
6801 WILL_LJMP(lua_error(L));
6802
6803 /* Return an error if the channel's output is closed */
6804 if (unlikely(channel_output_closed(msg->chn))) {
6805 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006806 return 1;
6807 }
6808
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 htx = htx_from_buf(&msg->chn->buf);
6810 if (sz > htx_free_data_space(htx)) {
6811 lua_pushinteger(L, -1);
6812 return 1;
6813 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006814
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006815 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6816 if (ret > 0) {
6817 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6818
6819 FLT_OFF(filter, msg->chn) += ret;
6820 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6821 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6822 }
6823
6824 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006825 return 1;
6826}
6827
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006828/* Forwards a given amount of bytes. It return -1 if the channel's output is
6829 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6830 * channel function used to forward data, this one can only be called inside a
6831 * filter, from http_payload callback. So it cannot yield. An exception is
6832 * returned if it is called from another callback. All other functions deal with
6833 * DATA block, this one not.
6834*/
6835__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006836{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006837 struct http_msg *msg;
6838 struct filter *filter;
6839 size_t offset, len;
6840 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006841
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006842 MAY_LJMP(check_args(L, 2, "forward"));
6843 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6844
6845 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006846 WILL_LJMP(lua_error(L));
6847
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006848 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6849 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6850 if (!filter || !hlua_filter_from_payload(filter))
6851 WILL_LJMP(lua_error(L));
6852
6853 /* Nothing to do, just return */
6854 if (!fwd)
6855 goto end;
6856
6857 /* Return an error if the channel's output is closed */
6858 if (unlikely(channel_output_closed(msg->chn))) {
6859 ret = -1;
6860 goto end;
6861 }
6862
6863 ret = fwd;
6864 if (ret > len)
6865 ret = len;
6866
6867 if (ret) {
6868 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6869
6870 FLT_OFF(filter, msg->chn) += ret;
6871 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6872 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6873 }
6874
6875 end:
6876 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006877 return 1;
6878}
6879
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006880/* Set EOM flag on the HTX message.
6881 *
6882 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6883 * really know how to do without this feature.
6884 */
6885__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006886{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006887 struct http_msg *msg;
6888 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006889
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006890 MAY_LJMP(check_args(L, 1, "set_eom"));
6891 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6892 htx = htxbuf(&msg->chn->buf);
6893 htx->flags |= HTX_FL_EOM;
6894 return 0;
6895}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006896
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006897/* Unset EOM flag on the HTX message.
6898 *
6899 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6900 * really know how to do without this feature.
6901 */
6902__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6903{
6904 struct http_msg *msg;
6905 struct htx *htx;
6906
6907 MAY_LJMP(check_args(L, 1, "set_eom"));
6908 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6909 htx = htxbuf(&msg->chn->buf);
6910 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006911 return 0;
6912}
6913
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006914/*
6915 *
6916 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006917 * Class HTTPClient
6918 *
6919 *
6920 */
6921__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6922{
6923 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6924}
6925
William Lallemandf77f1de2021-09-28 19:10:38 +02006926
6927/* stops the httpclient and ask it to kill itself */
6928__LJMP static int hlua_httpclient_gc(lua_State *L)
6929{
6930 struct hlua_httpclient *hlua_hc;
6931
6932 MAY_LJMP(check_args(L, 1, "__gc"));
6933
6934 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6935
6936 httpclient_stop_and_destroy(hlua_hc->hc);
6937
6938 hlua_hc->hc = NULL;
6939
6940
6941 return 0;
6942}
6943
6944
William Lallemand3956c4e2021-09-21 16:25:15 +02006945__LJMP static int hlua_httpclient_new(lua_State *L)
6946{
6947 struct hlua_httpclient *hlua_hc;
6948 struct hlua *hlua;
6949
6950 /* Get hlua struct, or NULL if we execute from main lua state */
6951 hlua = hlua_gethlua(L);
6952 if (!hlua)
6953 return 0;
6954
6955 /* Check stack size. */
6956 if (!lua_checkstack(L, 3)) {
6957 hlua_pusherror(L, "httpclient: full stack");
6958 goto err;
6959 }
6960 /* Create the object: obj[0] = userdata. */
6961 lua_newtable(L);
6962 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6963 lua_rawseti(L, -2, 0);
6964 memset(hlua_hc, 0, sizeof(*hlua_hc));
6965
6966 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6967 if (!hlua_hc->hc)
6968 goto err;
6969
6970 /* Pop a class stream metatable and affect it to the userdata. */
6971 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6972 lua_setmetatable(L, -2);
6973
6974 return 1;
6975
6976 err:
6977 WILL_LJMP(lua_error(L));
6978 return 0;
6979}
6980
6981
6982/*
6983 * Callback of the httpclient, this callback wakes the lua task up, once the
6984 * httpclient receives some data
6985 *
6986 */
6987
William Lallemandbd5739e2021-10-28 15:41:38 +02006988static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02006989{
6990 struct hlua *hlua = hc->caller;
6991
6992 if (!hlua || !hlua->task)
6993 return;
6994
6995 task_wakeup(hlua->task, TASK_WOKEN_MSG);
6996}
6997
6998/*
William Lallemandd7df73a2021-09-23 17:54:00 +02006999 * Fill the lua stack with headers from the httpclient response
7000 * This works the same way as the hlua_http_get_headers() function
7001 */
7002__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7003{
7004 struct http_hdr *hdr;
7005
7006 lua_newtable(L);
7007
William Lallemandef574b22021-10-05 16:19:31 +02007008 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007009 struct ist n, v;
7010 int len;
7011
7012 n = hdr->n;
7013 v = hdr->v;
7014
7015 /* Check for existing entry:
7016 * assume that the table is on the top of the stack, and
7017 * push the key in the stack, the function lua_gettable()
7018 * perform the lookup.
7019 */
7020
7021 lua_pushlstring(L, n.ptr, n.len);
7022 lua_gettable(L, -2);
7023
7024 switch (lua_type(L, -1)) {
7025 case LUA_TNIL:
7026 /* Table not found, create it. */
7027 lua_pop(L, 1); /* remove the nil value. */
7028 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7029 lua_newtable(L); /* create and push empty table. */
7030 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7031 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7032 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7033 break;
7034
7035 case LUA_TTABLE:
7036 /* Entry found: push the value in the table. */
7037 len = lua_rawlen(L, -1);
7038 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7039 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7040 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7041 break;
7042
7043 default:
7044 /* Other cases are errors. */
7045 hlua_pusherror(L, "internal error during the parsing of headers.");
7046 WILL_LJMP(lua_error(L));
7047 }
7048 }
7049 return 1;
7050}
7051
7052/*
William Lallemand746e6f32021-10-06 10:57:44 +02007053 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7054 *
7055 * Caller must free the result
7056 */
7057struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7058{
7059 struct http_hdr hdrs[global.tune.max_http_hdr];
7060 struct http_hdr *result = NULL;
7061 uint32_t hdr_num = 0;
7062
7063 lua_pushnil(L);
7064 while (lua_next(L, -2) != 0) {
7065 struct ist name, value;
7066 const char *n, *v;
7067 size_t nlen, vlen;
7068
7069 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7070 /* Skip element if the key is not a string or if the value is not a table */
7071 goto next_hdr;
7072 }
7073
7074 n = lua_tolstring(L, -2, &nlen);
7075 name = ist2(n, nlen);
7076
7077 /* Loop on header's values */
7078 lua_pushnil(L);
7079 while (lua_next(L, -2)) {
7080 if (!lua_isstring(L, -1)) {
7081 /* Skip the value if it is not a string */
7082 goto next_value;
7083 }
7084
7085 v = lua_tolstring(L, -1, &vlen);
7086 value = ist2(v, vlen);
7087 name = ist2(n, nlen);
7088
7089 hdrs[hdr_num].n = istdup(name);
7090 hdrs[hdr_num].v = istdup(value);
7091
7092 hdr_num++;
7093
7094 next_value:
7095 lua_pop(L, 1);
7096 }
7097
7098 next_hdr:
7099 lua_pop(L, 1);
7100
7101 }
7102
7103 if (hdr_num) {
7104 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007105 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007106 if (!result)
7107 goto skip_headers;
7108 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7109
7110 result[hdr_num].n = IST_NULL;
7111 result[hdr_num].v = IST_NULL;
7112 }
7113
7114skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007115
7116 return result;
7117}
7118
7119
William Lallemandbd5739e2021-10-28 15:41:38 +02007120/*
7121 * For each yield, checks if there is some data in the httpclient and push them
7122 * in the lua buffer, once the httpclient finished its job, push the result on
7123 * the stack
7124 */
7125__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7126{
7127 struct buffer *tr;
7128 int res;
7129 struct hlua *hlua = hlua_gethlua(L);
7130 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7131
7132
7133 tr = get_trash_chunk();
7134
7135 res = httpclient_res_xfer(hlua_hc->hc, tr);
7136 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7137
7138 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7139
7140 luaL_pushresult(&hlua_hc->b);
7141 lua_settable(L, -3);
7142
7143 lua_pushstring(L, "status");
7144 lua_pushinteger(L, hlua_hc->hc->res.status);
7145 lua_settable(L, -3);
7146
7147
7148 lua_pushstring(L, "reason");
7149 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7150 lua_settable(L, -3);
7151
7152 lua_pushstring(L, "headers");
7153 hlua_httpclient_get_headers(L, hlua_hc);
7154 lua_settable(L, -3);
7155
7156 return 1;
7157 }
7158
7159 if (httpclient_data(hlua_hc->hc))
7160 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7161
7162 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7163
7164 return 0;
7165}
7166
7167/*
7168 * Call this when trying to stream a body during a request
7169 */
7170__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7171{
7172 struct hlua *hlua;
7173 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7174 const char *body_str = NULL;
7175 int ret;
7176 int end = 0;
7177 size_t buf_len;
7178 size_t to_send = 0;
7179
7180 hlua = hlua_gethlua(L);
7181
7182 if (!hlua || !hlua->task)
7183 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7184 "'frontend', 'backend' or 'task'"));
7185
7186 ret = lua_getfield(L, -1, "body");
7187 if (ret != LUA_TSTRING)
7188 goto rcv;
7189
7190 body_str = lua_tolstring(L, -1, &buf_len);
7191 lua_pop(L, 1);
7192
Christopher Fauletfc591292022-01-12 14:46:03 +01007193 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007194
7195 if ((hlua_hc->sent + to_send) >= buf_len)
7196 end = 1;
7197
7198 /* the end flag is always set since we are using the whole remaining size */
7199 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7200
7201 if (buf_len > hlua_hc->sent) {
7202 /* still need to process the buffer */
7203 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7204 } else {
7205 goto rcv;
7206 /* we sent the whole request buffer we can recv */
7207 }
7208 return 0;
7209
7210rcv:
7211
7212 /* we return a "res" object */
7213 lua_newtable(L);
7214
William Lallemandbd5739e2021-10-28 15:41:38 +02007215 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007216 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007217
William Lallemand933fe392021-11-04 09:45:58 +01007218 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007219 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7220
7221 return 1;
7222}
William Lallemand746e6f32021-10-06 10:57:44 +02007223
William Lallemand3956c4e2021-09-21 16:25:15 +02007224/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007225 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007226 */
7227
William Lallemanddc2cc902021-10-26 11:43:26 +02007228__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007229{
7230 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007231 struct http_hdr *hdrs = NULL;
7232 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007233 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007234 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007235 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007236 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007237 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007238
7239 hlua = hlua_gethlua(L);
7240
7241 if (!hlua || !hlua->task)
7242 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7243 "'frontend', 'backend' or 'task'"));
7244
William Lallemand746e6f32021-10-06 10:57:44 +02007245 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7246 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7247
William Lallemand4f4f2b72022-02-17 20:00:23 +01007248 hlua_hc = hlua_checkhttpclient(L, 1);
7249
William Lallemand7177a952022-03-03 15:33:12 +01007250 lua_pushnil(L); /* first key */
7251 while (lua_next(L, 2)) {
7252 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7253 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7254 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007255
William Lallemand7177a952022-03-03 15:33:12 +01007256 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7257 if (lua_type(L, -1) != LUA_TSTRING)
7258 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7259 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007260
William Lallemand7177a952022-03-03 15:33:12 +01007261 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7262 if (lua_type(L, -1) != LUA_TNUMBER)
7263 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7264 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007265
William Lallemand7177a952022-03-03 15:33:12 +01007266 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7267 if (lua_type(L, -1) != LUA_TTABLE)
7268 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7269 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007270
William Lallemand7177a952022-03-03 15:33:12 +01007271 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7272 if (lua_type(L, -1) != LUA_TSTRING)
7273 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7274 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007275
William Lallemand7177a952022-03-03 15:33:12 +01007276 } else {
7277 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7278 }
7279 /* removes 'value'; keeps 'key' for next iteration */
7280 lua_pop(L, 1);
7281 }
William Lallemanddec25c32021-10-25 19:48:37 +02007282
William Lallemand746e6f32021-10-06 10:57:44 +02007283 if (!url_str) {
7284 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7285 return 0;
7286 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007287
William Lallemand10a37362022-03-02 16:18:26 +01007288 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007289
7290 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007291 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007292
7293 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007294 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7295 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7296 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007297 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007298
William Lallemandbd5739e2021-10-28 15:41:38 +02007299 /* a body is available, it will use the request callback */
7300 if (body_str) {
7301 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7302 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007303
William Lallemandbd5739e2021-10-28 15:41:38 +02007304 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007305
William Lallemand746e6f32021-10-06 10:57:44 +02007306 /* free the temporary headers array */
7307 hdrs_i = hdrs;
7308 while (hdrs_i && isttest(hdrs_i->n)) {
7309 istfree(&hdrs_i->n);
7310 istfree(&hdrs_i->v);
7311 hdrs_i++;
7312 }
7313 ha_free(&hdrs);
7314
7315
William Lallemand6137a9e2021-10-26 15:01:53 +02007316 if (ret != ERR_NONE) {
7317 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7318 return 0;
7319 }
7320
William Lallemand6137a9e2021-10-26 15:01:53 +02007321 httpclient_start(hlua_hc->hc);
7322
William Lallemandbd5739e2021-10-28 15:41:38 +02007323 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007324
William Lallemand3956c4e2021-09-21 16:25:15 +02007325 return 0;
7326}
7327
7328/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007329 * Sends an HTTP HEAD request and wait for a response
7330 *
7331 * httpclient:head(url, headers, payload)
7332 */
7333__LJMP static int hlua_httpclient_head(lua_State *L)
7334{
7335 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7336}
7337
7338/*
7339 * Send an HTTP GET request and wait for a response
7340 *
7341 * httpclient:get(url, headers, payload)
7342 */
7343__LJMP static int hlua_httpclient_get(lua_State *L)
7344{
7345 return hlua_httpclient_send(L, HTTP_METH_GET);
7346
7347}
7348
7349/*
7350 * Sends an HTTP PUT request and wait for a response
7351 *
7352 * httpclient:put(url, headers, payload)
7353 */
7354__LJMP static int hlua_httpclient_put(lua_State *L)
7355{
7356 return hlua_httpclient_send(L, HTTP_METH_PUT);
7357}
7358
7359/*
7360 * Send an HTTP POST request and wait for a response
7361 *
7362 * httpclient:post(url, headers, payload)
7363 */
7364__LJMP static int hlua_httpclient_post(lua_State *L)
7365{
7366 return hlua_httpclient_send(L, HTTP_METH_POST);
7367}
7368
7369
7370/*
7371 * Sends an HTTP DELETE request and wait for a response
7372 *
7373 * httpclient:delete(url, headers, payload)
7374 */
7375__LJMP static int hlua_httpclient_delete(lua_State *L)
7376{
7377 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7378}
7379
7380/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007381 *
7382 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007383 * Class TXN
7384 *
7385 *
7386 */
7387
7388/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007389 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007390 */
7391__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7392{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007393 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007394}
7395
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007396__LJMP static int hlua_set_var(lua_State *L)
7397{
7398 struct hlua_txn *htxn;
7399 const char *name;
7400 size_t len;
7401 struct sample smp;
7402
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007403 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7404 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007405
7406 /* It is useles to retrieve the stream, but this function
7407 * runs only in a stream context.
7408 */
7409 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7410 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7411
7412 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007413 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007414 hlua_lua2smp(L, 3, &smp);
7415
7416 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007417 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007418
7419 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7420 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7421 else
7422 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7423
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007424 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007425}
7426
Christopher Faulet85d79c92016-11-09 16:54:56 +01007427__LJMP static int hlua_unset_var(lua_State *L)
7428{
7429 struct hlua_txn *htxn;
7430 const char *name;
7431 size_t len;
7432 struct sample smp;
7433
7434 MAY_LJMP(check_args(L, 2, "unset_var"));
7435
7436 /* It is useles to retrieve the stream, but this function
7437 * runs only in a stream context.
7438 */
7439 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7440 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7441
7442 /* Unset the variable. */
7443 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007444 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7445 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007446}
7447
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007448__LJMP static int hlua_get_var(lua_State *L)
7449{
7450 struct hlua_txn *htxn;
7451 const char *name;
7452 size_t len;
7453 struct sample smp;
7454
7455 MAY_LJMP(check_args(L, 2, "get_var"));
7456
7457 /* It is useles to retrieve the stream, but this function
7458 * runs only in a stream context.
7459 */
7460 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7461 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7462
Willy Tarreau7560dd42016-03-10 16:28:58 +01007463 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007464 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007465 lua_pushnil(L);
7466 return 1;
7467 }
7468
7469 return hlua_smp2lua(L, &smp);
7470}
7471
Willy Tarreau59551662015-03-10 14:23:13 +01007472__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007473{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007474 struct hlua *hlua;
7475
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007476 MAY_LJMP(check_args(L, 2, "set_priv"));
7477
Willy Tarreau87b09662015-04-03 00:22:06 +02007478 /* It is useles to retrieve the stream, but this function
7479 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007480 */
7481 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007482
7483 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007484 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007485 if (!hlua)
7486 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007487
7488 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007489 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007490
7491 /* Get and store new value. */
7492 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7493 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7494
7495 return 0;
7496}
7497
Willy Tarreau59551662015-03-10 14:23:13 +01007498__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007499{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007500 struct hlua *hlua;
7501
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007502 MAY_LJMP(check_args(L, 1, "get_priv"));
7503
Willy Tarreau87b09662015-04-03 00:22:06 +02007504 /* It is useles to retrieve the stream, but this function
7505 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007506 */
7507 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007508
7509 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007510 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007511 if (!hlua) {
7512 lua_pushnil(L);
7513 return 1;
7514 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007515
7516 /* Push configuration index in the stack. */
7517 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7518
7519 return 1;
7520}
7521
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007522/* Create stack entry containing a class TXN. This function
7523 * return 0 if the stack does not contains free slots,
7524 * otherwise it returns 1.
7525 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007526static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007527{
Willy Tarreaude491382015-04-06 11:04:28 +02007528 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007529
7530 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007531 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007532 return 0;
7533
7534 /* NOTE: The allocation never fails. The failure
7535 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007536 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007537 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007538 /* Create the object: obj[0] = userdata. */
7539 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007540 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007541 lua_rawseti(L, -2, 0);
7542
Willy Tarreaude491382015-04-06 11:04:28 +02007543 htxn->s = s;
7544 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007545 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007546 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007547
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007548 /* Create the "f" field that contains a list of fetches. */
7549 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007550 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007551 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007552 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007553
7554 /* Create the "sf" field that contains a list of stringsafe fetches. */
7555 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007556 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007557 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007558 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007559
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007560 /* Create the "c" field that contains a list of converters. */
7561 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007562 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007563 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007564 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007565
7566 /* Create the "sc" field that contains a list of stringsafe converters. */
7567 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007568 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007569 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007570 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007571
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007572 /* Create the "req" field that contains the request channel object. */
7573 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007574 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007575 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007576 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007577
7578 /* Create the "res" field that contains the response channel object. */
7579 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007580 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007581 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007582 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007583
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007584 /* Creates the HTTP object is the current proxy allows http. */
7585 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007586 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007587 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007588 return 0;
7589 }
7590 else
7591 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007592 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007593
Christopher Faulet78c35472020-02-26 17:14:08 +01007594 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7595 /* HTTPMessage object are created when a lua TXN is created from
7596 * a filter context only
7597 */
7598
7599 /* Creates the HTTP-Request object is the current proxy allows http. */
7600 lua_pushstring(L, "http_req");
7601 if (p->mode == PR_MODE_HTTP) {
7602 if (!hlua_http_msg_new(L, &s->txn->req))
7603 return 0;
7604 }
7605 else
7606 lua_pushnil(L);
7607 lua_rawset(L, -3);
7608
7609 /* Creates the HTTP-Response object is the current proxy allows http. */
7610 lua_pushstring(L, "http_res");
7611 if (p->mode == PR_MODE_HTTP) {
7612 if (!hlua_http_msg_new(L, &s->txn->rsp))
7613 return 0;
7614 }
7615 else
7616 lua_pushnil(L);
7617 lua_rawset(L, -3);
7618 }
7619
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007620 /* Pop a class sesison metatable and affect it to the userdata. */
7621 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7622 lua_setmetatable(L, -2);
7623
7624 return 1;
7625}
7626
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007627__LJMP static int hlua_txn_deflog(lua_State *L)
7628{
7629 const char *msg;
7630 struct hlua_txn *htxn;
7631
7632 MAY_LJMP(check_args(L, 2, "deflog"));
7633 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7634 msg = MAY_LJMP(luaL_checkstring(L, 2));
7635
7636 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7637 return 0;
7638}
7639
7640__LJMP static int hlua_txn_log(lua_State *L)
7641{
7642 int level;
7643 const char *msg;
7644 struct hlua_txn *htxn;
7645
7646 MAY_LJMP(check_args(L, 3, "log"));
7647 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7648 level = MAY_LJMP(luaL_checkinteger(L, 2));
7649 msg = MAY_LJMP(luaL_checkstring(L, 3));
7650
7651 if (level < 0 || level >= NB_LOG_LEVELS)
7652 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7653
7654 hlua_sendlog(htxn->s->be, level, msg);
7655 return 0;
7656}
7657
7658__LJMP static int hlua_txn_log_debug(lua_State *L)
7659{
7660 const char *msg;
7661 struct hlua_txn *htxn;
7662
7663 MAY_LJMP(check_args(L, 2, "Debug"));
7664 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7665 msg = MAY_LJMP(luaL_checkstring(L, 2));
7666 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7667 return 0;
7668}
7669
7670__LJMP static int hlua_txn_log_info(lua_State *L)
7671{
7672 const char *msg;
7673 struct hlua_txn *htxn;
7674
7675 MAY_LJMP(check_args(L, 2, "Info"));
7676 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7677 msg = MAY_LJMP(luaL_checkstring(L, 2));
7678 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7679 return 0;
7680}
7681
7682__LJMP static int hlua_txn_log_warning(lua_State *L)
7683{
7684 const char *msg;
7685 struct hlua_txn *htxn;
7686
7687 MAY_LJMP(check_args(L, 2, "Warning"));
7688 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7689 msg = MAY_LJMP(luaL_checkstring(L, 2));
7690 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7691 return 0;
7692}
7693
7694__LJMP static int hlua_txn_log_alert(lua_State *L)
7695{
7696 const char *msg;
7697 struct hlua_txn *htxn;
7698
7699 MAY_LJMP(check_args(L, 2, "Alert"));
7700 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7701 msg = MAY_LJMP(luaL_checkstring(L, 2));
7702 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7703 return 0;
7704}
7705
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007706__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7707{
7708 struct hlua_txn *htxn;
7709 int ll;
7710
7711 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7712 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7713 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7714
7715 if (ll < 0 || ll > 7)
7716 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7717
7718 htxn->s->logs.level = ll;
7719 return 0;
7720}
7721
7722__LJMP static int hlua_txn_set_tos(lua_State *L)
7723{
7724 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007725 int tos;
7726
7727 MAY_LJMP(check_args(L, 2, "set_tos"));
7728 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7729 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7730
Willy Tarreau1a18b542018-12-11 16:37:42 +01007731 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007732 return 0;
7733}
7734
7735__LJMP static int hlua_txn_set_mark(lua_State *L)
7736{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007737 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007738 int mark;
7739
7740 MAY_LJMP(check_args(L, 2, "set_mark"));
7741 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7742 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7743
Lukas Tribus579e3e32019-08-11 18:03:45 +02007744 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007745 return 0;
7746}
7747
Patrick Hemmer268a7072018-05-11 12:52:31 -04007748__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7749{
7750 struct hlua_txn *htxn;
7751
7752 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7753 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7754 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7755 return 0;
7756}
7757
7758__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7759{
7760 struct hlua_txn *htxn;
7761
7762 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7763 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7764 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7765 return 0;
7766}
7767
Christopher Faulet700d9e82020-01-31 12:21:52 +01007768/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007769 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007770 * message and terminate the transaction. It returns 1 on success and 0 on
7771 * error. The Reply must be on top of the stack.
7772 */
7773__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7774{
7775 struct htx *htx;
7776 struct htx_sl *sl;
7777 struct h1m h1m;
7778 const char *status, *reason, *body;
7779 size_t status_len, reason_len, body_len;
7780 int ret, code, flags;
7781
7782 code = 200;
7783 status = "200";
7784 status_len = 3;
7785 ret = lua_getfield(L, -1, "status");
7786 if (ret == LUA_TNUMBER) {
7787 code = lua_tointeger(L, -1);
7788 status = lua_tolstring(L, -1, &status_len);
7789 }
7790 lua_pop(L, 1);
7791
7792 reason = http_get_reason(code);
7793 reason_len = strlen(reason);
7794 ret = lua_getfield(L, -1, "reason");
7795 if (ret == LUA_TSTRING)
7796 reason = lua_tolstring(L, -1, &reason_len);
7797 lua_pop(L, 1);
7798
7799 body = NULL;
7800 body_len = 0;
7801 ret = lua_getfield(L, -1, "body");
7802 if (ret == LUA_TSTRING)
7803 body = lua_tolstring(L, -1, &body_len);
7804 lua_pop(L, 1);
7805
7806 /* Prepare the response before inserting the headers */
7807 h1m_init_res(&h1m);
7808 htx = htx_from_buf(&s->res.buf);
7809 channel_htx_truncate(&s->res, htx);
7810 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7811 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7812 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7813 ist2(status, status_len), ist2(reason, reason_len));
7814 }
7815 else {
7816 flags = HTX_SL_F_IS_RESP;
7817 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7818 ist2(status, status_len), ist2(reason, reason_len));
7819 }
7820 if (!sl)
7821 goto fail;
7822 sl->info.res.status = code;
7823
7824 /* Push in the stack the "headers" entry. */
7825 ret = lua_getfield(L, -1, "headers");
7826 if (ret != LUA_TTABLE)
7827 goto skip_headers;
7828
7829 lua_pushnil(L);
7830 while (lua_next(L, -2) != 0) {
7831 struct ist name, value;
7832 const char *n, *v;
7833 size_t nlen, vlen;
7834
7835 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7836 /* Skip element if the key is not a string or if the value is not a table */
7837 goto next_hdr;
7838 }
7839
7840 n = lua_tolstring(L, -2, &nlen);
7841 name = ist2(n, nlen);
7842 if (isteqi(name, ist("content-length"))) {
7843 /* Always skip content-length header. It will be added
7844 * later with the correct len
7845 */
7846 goto next_hdr;
7847 }
7848
7849 /* Loop on header's values */
7850 lua_pushnil(L);
7851 while (lua_next(L, -2)) {
7852 if (!lua_isstring(L, -1)) {
7853 /* Skip the value if it is not a string */
7854 goto next_value;
7855 }
7856
7857 v = lua_tolstring(L, -1, &vlen);
7858 value = ist2(v, vlen);
7859
7860 if (isteqi(name, ist("transfer-encoding")))
7861 h1_parse_xfer_enc_header(&h1m, value);
7862 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7863 goto fail;
7864
7865 next_value:
7866 lua_pop(L, 1);
7867 }
7868
7869 next_hdr:
7870 lua_pop(L, 1);
7871 }
7872 skip_headers:
7873 lua_pop(L, 1);
7874
7875 /* Update h1m flags: CLEN is set if CHNK is not present */
7876 if (!(h1m.flags & H1_MF_CHNK)) {
7877 const char *clen = ultoa(body_len);
7878
7879 h1m.flags |= H1_MF_CLEN;
7880 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7881 goto fail;
7882 }
7883 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7884 h1m.flags |= H1_MF_XFER_LEN;
7885
7886 /* Update HTX start-line flags */
7887 if (h1m.flags & H1_MF_XFER_ENC)
7888 flags |= HTX_SL_F_XFER_ENC;
7889 if (h1m.flags & H1_MF_XFER_LEN) {
7890 flags |= HTX_SL_F_XFER_LEN;
7891 if (h1m.flags & H1_MF_CHNK)
7892 flags |= HTX_SL_F_CHNK;
7893 else if (h1m.flags & H1_MF_CLEN)
7894 flags |= HTX_SL_F_CLEN;
7895 if (h1m.body_len == 0)
7896 flags |= HTX_SL_F_BODYLESS;
7897 }
7898 sl->flags |= flags;
7899
7900
7901 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007902 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007903 goto fail;
7904
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007905 htx->flags |= HTX_FL_EOM;
7906
Christopher Faulet700d9e82020-01-31 12:21:52 +01007907 /* Now, forward the response and terminate the transaction */
7908 s->txn->status = code;
7909 htx_to_buf(htx, &s->res.buf);
7910 if (!http_forward_proxy_resp(s, 1))
7911 goto fail;
7912
7913 return 1;
7914
7915 fail:
7916 channel_htx_truncate(&s->res, htx);
7917 return 0;
7918}
7919
7920/* Terminate a transaction if called from a lua action. For TCP streams,
7921 * processing is just aborted. Nothing is returned to the client and all
7922 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7923 * is forwarded to the client before terminating the transaction. On success,
7924 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7925 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7926 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007927 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007928__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007929{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007930 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007931 struct stream *s;
7932 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007933
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007934 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007935
Christopher Faulet700d9e82020-01-31 12:21:52 +01007936 /* If the flags NOTERM is set, we cannot terminate the session, so we
7937 * just end the execution of the current lua code. */
7938 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007939 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007940
Christopher Faulet700d9e82020-01-31 12:21:52 +01007941 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007942 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007943 struct channel *req = &s->req;
7944 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007945
Christopher Faulet700d9e82020-01-31 12:21:52 +01007946 channel_auto_read(req);
7947 channel_abort(req);
7948 channel_auto_close(req);
7949 channel_erase(req);
7950
7951 res->wex = tick_add_ifset(now_ms, res->wto);
7952 channel_auto_read(res);
7953 channel_auto_close(res);
7954 channel_shutr_now(res);
7955
7956 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7957 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007958 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007959
Christopher Faulet700d9e82020-01-31 12:21:52 +01007960 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7961 /* No reply or invalid reply */
7962 s->txn->status = 0;
7963 http_reply_and_close(s, 0, NULL);
7964 }
7965 else {
7966 /* Remove extra args to have the reply on top of the stack */
7967 if (lua_gettop(L) > 2)
7968 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007969
Christopher Faulet700d9e82020-01-31 12:21:52 +01007970 if (!hlua_txn_forward_reply(L, s)) {
7971 if (!(s->flags & SF_ERR_MASK))
7972 s->flags |= SF_ERR_PRXCOND;
7973 lua_pushinteger(L, ACT_RET_ERR);
7974 WILL_LJMP(hlua_done(L));
7975 return 0; /* Never reached */
7976 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007977 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007978
Christopher Faulet700d9e82020-01-31 12:21:52 +01007979 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7980 if (htxn->dir == SMP_OPT_DIR_REQ) {
7981 /* let's log the request time */
7982 s->logs.tv_request = now;
7983 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007984 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007985 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007986
Christopher Faulet700d9e82020-01-31 12:21:52 +01007987 done:
7988 if (!(s->flags & SF_ERR_MASK))
7989 s->flags |= SF_ERR_LOCAL;
7990 if (!(s->flags & SF_FINST_MASK))
7991 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007992
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007993 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7994 lua_pushinteger(L, -1);
7995 else
7996 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007997 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007998 return 0;
7999}
8000
Christopher Faulet700d9e82020-01-31 12:21:52 +01008001/*
8002 *
8003 *
8004 * Class REPLY
8005 *
8006 *
8007 */
8008
8009/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8010 * free slots, the function fails and returns 0;
8011 */
8012static int hlua_txn_reply_new(lua_State *L)
8013{
8014 struct hlua_txn *htxn;
8015 const char *reason, *body = NULL;
8016 int ret, status;
8017
8018 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008019 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008020 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8021 WILL_LJMP(lua_error(L));
8022 }
8023
8024 /* Default value */
8025 status = 200;
8026 reason = http_get_reason(status);
8027
8028 if (lua_istable(L, 2)) {
8029 /* load status and reason from the table argument at index 2 */
8030 ret = lua_getfield(L, 2, "status");
8031 if (ret == LUA_TNIL)
8032 goto reason;
8033 else if (ret != LUA_TNUMBER) {
8034 /* invalid status: ignore the reason */
8035 goto body;
8036 }
8037 status = lua_tointeger(L, -1);
8038
8039 reason:
8040 lua_pop(L, 1); /* restore the stack: remove status */
8041 ret = lua_getfield(L, 2, "reason");
8042 if (ret == LUA_TSTRING)
8043 reason = lua_tostring(L, -1);
8044
8045 body:
8046 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8047 ret = lua_getfield(L, 2, "body");
8048 if (ret == LUA_TSTRING)
8049 body = lua_tostring(L, -1);
8050 lua_pop(L, 1); /* restore the stack: remove body */
8051 }
8052
8053 /* Create the Reply table */
8054 lua_newtable(L);
8055
8056 /* Add status element */
8057 lua_pushstring(L, "status");
8058 lua_pushinteger(L, status);
8059 lua_settable(L, -3);
8060
8061 /* Add reason element */
8062 reason = http_get_reason(status);
8063 lua_pushstring(L, "reason");
8064 lua_pushstring(L, reason);
8065 lua_settable(L, -3);
8066
8067 /* Add body element, nil if undefined */
8068 lua_pushstring(L, "body");
8069 if (body)
8070 lua_pushstring(L, body);
8071 else
8072 lua_pushnil(L);
8073 lua_settable(L, -3);
8074
8075 /* Add headers element */
8076 lua_pushstring(L, "headers");
8077 lua_newtable(L);
8078
8079 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8080 if (lua_istable(L, 2)) {
8081 /* load headers from the table argument at index 2. If it is a table, copy it. */
8082 ret = lua_getfield(L, 2, "headers");
8083 if (ret == LUA_TTABLE) {
8084 /* stack: [ ... <headers:table>, <table> ] */
8085 lua_pushnil(L);
8086 while (lua_next(L, -2) != 0) {
8087 /* stack: [ ... <headers:table>, <table>, k, v] */
8088 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8089 /* invalid value type, skip it */
8090 lua_pop(L, 1);
8091 continue;
8092 }
8093
8094
8095 /* Duplicate the key and swap it with the value. */
8096 lua_pushvalue(L, -2);
8097 lua_insert(L, -2);
8098 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8099
8100 lua_newtable(L);
8101 lua_insert(L, -2);
8102 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8103
8104 if (lua_isstring(L, -1)) {
8105 /* push the value in the inner table */
8106 lua_rawseti(L, -2, 1);
8107 }
8108 else { /* table */
8109 lua_pushnil(L);
8110 while (lua_next(L, -2) != 0) {
8111 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8112 if (!lua_isstring(L, -1)) {
8113 /* invalid value type, skip it*/
8114 lua_pop(L, 1);
8115 continue;
8116 }
8117 /* push the value in the inner table */
8118 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8119 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8120 }
8121 lua_pop(L, 1);
8122 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8123 }
8124
8125 /* push (k,v) on the stack in the headers table:
8126 * stack: [ ... <headers:table>, <table>, k, k, v ]
8127 */
8128 lua_settable(L, -5);
8129 /* stack: [ ... <headers:table>, <table>, k ] */
8130 }
8131 }
8132 lua_pop(L, 1);
8133 }
8134 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8135 lua_settable(L, -3);
8136 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8137
8138 /* Pop a class sesison metatable and affect it to the userdata. */
8139 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8140 lua_setmetatable(L, -2);
8141 return 1;
8142}
8143
8144/* Set the reply status code, and optionally the reason. If no reason is
8145 * provided, the default one corresponding to the status code is used.
8146 */
8147__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8148{
8149 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8150 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8151
8152 /* First argument (self) must be a table */
8153 luaL_checktype(L, 1, LUA_TTABLE);
8154
8155 if (status < 100 || status > 599) {
8156 lua_pushboolean(L, 0);
8157 return 1;
8158 }
8159 if (!reason)
8160 reason = http_get_reason(status);
8161
8162 lua_pushinteger(L, status);
8163 lua_setfield(L, 1, "status");
8164
8165 lua_pushstring(L, reason);
8166 lua_setfield(L, 1, "reason");
8167
8168 lua_pushboolean(L, 1);
8169 return 1;
8170}
8171
8172/* Add a header into the reply object. Each header name is associated to an
8173 * array of values in the "headers" table. If the header name is not found, a
8174 * new entry is created.
8175 */
8176__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8177{
8178 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8179 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8180 int ret;
8181
8182 /* First argument (self) must be a table */
8183 luaL_checktype(L, 1, LUA_TTABLE);
8184
8185 /* Push in the stack the "headers" entry. */
8186 ret = lua_getfield(L, 1, "headers");
8187 if (ret != LUA_TTABLE) {
8188 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8189 WILL_LJMP(lua_error(L));
8190 }
8191
8192 /* check if the header is already registered. If not, register it. */
8193 ret = lua_getfield(L, -1, name);
8194 if (ret == LUA_TNIL) {
8195 /* Entry not found. */
8196 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8197
8198 /* Insert the new header name in the array in the top of the stack.
8199 * It left the new array in the top of the stack.
8200 */
8201 lua_newtable(L);
8202 lua_pushstring(L, name);
8203 lua_pushvalue(L, -2);
8204 lua_settable(L, -4);
8205 }
8206 else if (ret != LUA_TTABLE) {
8207 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8208 WILL_LJMP(lua_error(L));
8209 }
8210
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008211 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008212 * the header value as new entry.
8213 */
8214 lua_pushstring(L, value);
8215 ret = lua_rawlen(L, -2);
8216 lua_rawseti(L, -2, ret + 1);
8217
8218 lua_pushboolean(L, 1);
8219 return 1;
8220}
8221
8222/* Remove all occurrences of a given header name. */
8223__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8224{
8225 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8226 int ret;
8227
8228 /* First argument (self) must be a table */
8229 luaL_checktype(L, 1, LUA_TTABLE);
8230
8231 /* Push in the stack the "headers" entry. */
8232 ret = lua_getfield(L, 1, "headers");
8233 if (ret != LUA_TTABLE) {
8234 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8235 WILL_LJMP(lua_error(L));
8236 }
8237
8238 lua_pushstring(L, name);
8239 lua_pushnil(L);
8240 lua_settable(L, -3);
8241
8242 lua_pushboolean(L, 1);
8243 return 1;
8244}
8245
8246/* Set the reply's body. Overwrite any existing entry. */
8247__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8248{
8249 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8250
8251 /* First argument (self) must be a table */
8252 luaL_checktype(L, 1, LUA_TTABLE);
8253
8254 lua_pushstring(L, payload);
8255 lua_setfield(L, 1, "body");
8256
8257 lua_pushboolean(L, 1);
8258 return 1;
8259}
8260
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008261__LJMP static int hlua_log(lua_State *L)
8262{
8263 int level;
8264 const char *msg;
8265
8266 MAY_LJMP(check_args(L, 2, "log"));
8267 level = MAY_LJMP(luaL_checkinteger(L, 1));
8268 msg = MAY_LJMP(luaL_checkstring(L, 2));
8269
8270 if (level < 0 || level >= NB_LOG_LEVELS)
8271 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8272
8273 hlua_sendlog(NULL, level, msg);
8274 return 0;
8275}
8276
8277__LJMP static int hlua_log_debug(lua_State *L)
8278{
8279 const char *msg;
8280
8281 MAY_LJMP(check_args(L, 1, "debug"));
8282 msg = MAY_LJMP(luaL_checkstring(L, 1));
8283 hlua_sendlog(NULL, LOG_DEBUG, msg);
8284 return 0;
8285}
8286
8287__LJMP static int hlua_log_info(lua_State *L)
8288{
8289 const char *msg;
8290
8291 MAY_LJMP(check_args(L, 1, "info"));
8292 msg = MAY_LJMP(luaL_checkstring(L, 1));
8293 hlua_sendlog(NULL, LOG_INFO, msg);
8294 return 0;
8295}
8296
8297__LJMP static int hlua_log_warning(lua_State *L)
8298{
8299 const char *msg;
8300
8301 MAY_LJMP(check_args(L, 1, "warning"));
8302 msg = MAY_LJMP(luaL_checkstring(L, 1));
8303 hlua_sendlog(NULL, LOG_WARNING, msg);
8304 return 0;
8305}
8306
8307__LJMP static int hlua_log_alert(lua_State *L)
8308{
8309 const char *msg;
8310
8311 MAY_LJMP(check_args(L, 1, "alert"));
8312 msg = MAY_LJMP(luaL_checkstring(L, 1));
8313 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008314 return 0;
8315}
8316
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008317__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008318{
8319 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008320 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008321 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008322 return 0;
8323}
8324
8325__LJMP static int hlua_sleep(lua_State *L)
8326{
8327 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008328 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008329
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008330 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008331
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008332 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008333 wakeup_ms = tick_add(now_ms, delay);
8334 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008335
Willy Tarreau9635e032018-10-16 17:52:55 +02008336 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008337 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008338}
8339
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008340__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008341{
8342 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008343 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008344
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008345 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008346
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008347 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008348 wakeup_ms = tick_add(now_ms, delay);
8349 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008350
Willy Tarreau9635e032018-10-16 17:52:55 +02008351 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008352 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008353}
8354
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008355/* This functionis an LUA binding. it permits to give back
8356 * the hand at the HAProxy scheduler. It is used when the
8357 * LUA processing consumes a lot of time.
8358 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008359__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008360{
8361 return 0;
8362}
8363
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008364__LJMP static int hlua_yield(lua_State *L)
8365{
Willy Tarreau9635e032018-10-16 17:52:55 +02008366 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008367 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008368}
8369
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008370/* This function change the nice of the currently executed
8371 * task. It is used set low or high priority at the current
8372 * task.
8373 */
Willy Tarreau59551662015-03-10 14:23:13 +01008374__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008375{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008376 struct hlua *hlua;
8377 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008378
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008379 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008380 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008381
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008382 /* Get hlua struct, or NULL if we execute from main lua state */
8383 hlua = hlua_gethlua(L);
8384
8385 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008386 if (!hlua || !hlua->task)
8387 return 0;
8388
8389 if (nice < -1024)
8390 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008391 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008392 nice = 1024;
8393
8394 hlua->task->nice = nice;
8395 return 0;
8396}
8397
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008398/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008399 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8400 * return an E_AGAIN signal, the emmiter of this signal must set a
8401 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008402 *
8403 * Task wrapper are longjmp safe because the only one Lua code
8404 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008405 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008406struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008407{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008408 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008409 enum hlua_exec status;
8410
Christopher Faulet5bc99722018-04-25 10:34:45 +02008411 if (task->thread_mask == MAX_THREADS_MASK)
8412 task_set_affinity(task, tid_bit);
8413
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008414 /* If it is the first call to the task, we must initialize the
8415 * execution timeouts.
8416 */
8417 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008418 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008419
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008420 /* Execute the Lua code. */
8421 status = hlua_ctx_resume(hlua, 1);
8422
8423 switch (status) {
8424 /* finished or yield */
8425 case HLUA_E_OK:
8426 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008427 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008428 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008429 break;
8430
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008431 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008432 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008433 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008434 break;
8435
8436 /* finished with error. */
8437 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008438 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008439 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008440 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008441 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008442 break;
8443
8444 case HLUA_E_ERR:
8445 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008446 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008447 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008448 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008449 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008450 break;
8451 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008452 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008453}
8454
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008455/* This function is an LUA binding that register LUA function to be
8456 * executed after the HAProxy configuration parsing and before the
8457 * HAProxy scheduler starts. This function expect only one LUA
8458 * argument that is a function. This function returns nothing, but
8459 * throws if an error is encountered.
8460 */
8461__LJMP static int hlua_register_init(lua_State *L)
8462{
8463 struct hlua_init_function *init;
8464 int ref;
8465
8466 MAY_LJMP(check_args(L, 1, "register_init"));
8467
8468 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8469
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008470 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008471 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008472 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008473
8474 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008475 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008476 return 0;
8477}
8478
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008479/* This functio is an LUA binding. It permits to register a task
8480 * executed in parallel of the main HAroxy activity. The task is
8481 * created and it is set in the HAProxy scheduler. It can be called
8482 * from the "init" section, "post init" or during the runtime.
8483 *
8484 * Lua prototype:
8485 *
8486 * <none> core.register_task(<function>)
8487 */
8488static int hlua_register_task(lua_State *L)
8489{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008490 struct hlua *hlua = NULL;
8491 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008492 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008493 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008494
8495 MAY_LJMP(check_args(L, 1, "register_task"));
8496
8497 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8498
Thierry Fournier75fc0292020-11-28 13:18:56 +01008499 /* Get the reference state. If the reference is NULL, L is the master
8500 * state, otherwise hlua->T is.
8501 */
8502 hlua = hlua_gethlua(L);
8503 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008504 /* we are in runtime processing */
8505 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008506 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008507 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008508 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008509
Willy Tarreaubafbe012017-11-24 17:34:44 +01008510 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008511 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008512 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008513 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008514
Thierry Fournier59f11be2020-11-29 00:37:41 +01008515 /* We are in the common lua state, execute the task anywhere,
8516 * otherwise, inherit the current thread identifier
8517 */
8518 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008519 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008520 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008521 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008522 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008523 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008524
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008525 task->context = hlua;
8526 task->process = hlua_process_task;
8527
Thierry Fournier021d9862020-11-28 23:42:03 +01008528 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008529 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008530
8531 /* Restore the function in the stack. */
8532 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8533 hlua->nargs = 0;
8534
8535 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008536 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008537
8538 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008539
8540 alloc_error:
8541 task_destroy(task);
8542 hlua_ctx_destroy(hlua);
8543 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8544 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008545}
8546
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008547/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8548 * doesn't allow "yield" functions because the HAProxy engine cannot
8549 * resume converters.
8550 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008551static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008552{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008553 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008554 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008555 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008556
Willy Tarreaube508f12016-03-10 11:47:01 +01008557 if (!stream)
8558 return 0;
8559
Willy Tarreau87b09662015-04-03 00:22:06 +02008560 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008561 * Lua context can be not initialized. This behavior
8562 * permits to save performances because a systematic
8563 * Lua initialization cause 5% performances loss.
8564 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008565 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008566 struct hlua *hlua;
8567
8568 hlua = pool_alloc(pool_head_hlua);
8569 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008570 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8571 return 0;
8572 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008573 HLUA_INIT(hlua);
8574 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008575 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008576 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8577 return 0;
8578 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008579 }
8580
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008581 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008582 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008583
8584 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008585 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008586 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8587 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008588 else
8589 error = "critical error";
8590 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008591 return 0;
8592 }
8593
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008594 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008595 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008596 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008597 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008598 return 0;
8599 }
8600
8601 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008602 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008603
8604 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008605 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008606 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008607 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008608 return 0;
8609 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008610 hlua_smp2lua(stream->hlua->T, smp);
8611 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008612
8613 /* push keywords in the stack. */
8614 if (arg_p) {
8615 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008616 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008617 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008618 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008619 return 0;
8620 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008621 hlua_arg2lua(stream->hlua->T, arg_p);
8622 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008623 }
8624 }
8625
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008626 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008627 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008628
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008629 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008630 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008631 }
8632
8633 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008634 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008635 /* finished. */
8636 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008637 /* If the stack is empty, the function fails. */
8638 if (lua_gettop(stream->hlua->T) <= 0)
8639 return 0;
8640
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008641 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008642 hlua_lua2smp(stream->hlua->T, -1, smp);
8643 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008644 return 1;
8645
8646 /* yield. */
8647 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008648 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008649 return 0;
8650
8651 /* finished with error. */
8652 case HLUA_E_ERRMSG:
8653 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008654 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008655 fcn->name, lua_tostring(stream->hlua->T, -1));
8656 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008657 return 0;
8658
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008659 case HLUA_E_ETMOUT:
8660 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8661 return 0;
8662
8663 case HLUA_E_NOMEM:
8664 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8665 return 0;
8666
8667 case HLUA_E_YIELD:
8668 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8669 return 0;
8670
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008671 case HLUA_E_ERR:
8672 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008673 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008674 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008675
8676 default:
8677 return 0;
8678 }
8679}
8680
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008681/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8682 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008683 * resume sample-fetches. This function will be called by the sample
8684 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008685 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008686static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8687 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008688{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008689 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008690 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008691 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008692 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008693
Willy Tarreaube508f12016-03-10 11:47:01 +01008694 if (!stream)
8695 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008696
Willy Tarreau87b09662015-04-03 00:22:06 +02008697 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008698 * Lua context can be not initialized. This behavior
8699 * permits to save performances because a systematic
8700 * Lua initialization cause 5% performances loss.
8701 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008702 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008703 struct hlua *hlua;
8704
8705 hlua = pool_alloc(pool_head_hlua);
8706 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008707 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8708 return 0;
8709 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008710 hlua->T = NULL;
8711 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008712 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008713 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8714 return 0;
8715 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008716 }
8717
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008718 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008719 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008720
8721 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008722 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008723 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8724 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008725 else
8726 error = "critical error";
8727 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008728 return 0;
8729 }
8730
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008731 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008732 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008733 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008734 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008735 return 0;
8736 }
8737
8738 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008739 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008740
8741 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008742 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008743 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008744 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008745 return 0;
8746 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008747 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008748
8749 /* push keywords in the stack. */
8750 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8751 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008752 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008753 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008754 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008755 return 0;
8756 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008757 hlua_arg2lua(stream->hlua->T, arg_p);
8758 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008759 }
8760
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008761 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008762 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008763
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008764 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008765 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008766 }
8767
8768 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008769 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008770 /* finished. */
8771 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008772 /* If the stack is empty, the function fails. */
8773 if (lua_gettop(stream->hlua->T) <= 0)
8774 return 0;
8775
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008776 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008777 hlua_lua2smp(stream->hlua->T, -1, smp);
8778 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008779
8780 /* Set the end of execution flag. */
8781 smp->flags &= ~SMP_F_MAY_CHANGE;
8782 return 1;
8783
8784 /* yield. */
8785 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008786 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008787 return 0;
8788
8789 /* finished with error. */
8790 case HLUA_E_ERRMSG:
8791 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008792 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008793 fcn->name, lua_tostring(stream->hlua->T, -1));
8794 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008795 return 0;
8796
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008797 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008798 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8799 return 0;
8800
8801 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008802 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8803 return 0;
8804
8805 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008806 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8807 return 0;
8808
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008809 case HLUA_E_ERR:
8810 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008811 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008812 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008813
8814 default:
8815 return 0;
8816 }
8817}
8818
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008819/* This function is an LUA binding used for registering
8820 * "sample-conv" functions. It expects a converter name used
8821 * in the haproxy configuration file, and an LUA function.
8822 */
8823__LJMP static int hlua_register_converters(lua_State *L)
8824{
8825 struct sample_conv_kw_list *sck;
8826 const char *name;
8827 int ref;
8828 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008829 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008830 struct sample_conv *sc;
8831 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008832
8833 MAY_LJMP(check_args(L, 2, "register_converters"));
8834
8835 /* First argument : converter name. */
8836 name = MAY_LJMP(luaL_checkstring(L, 1));
8837
8838 /* Second argument : lua function. */
8839 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8840
Thierry Fournierf67442e2020-11-28 20:41:07 +01008841 /* Check if the converter is already registered */
8842 trash = get_trash_chunk();
8843 chunk_printf(trash, "lua.%s", name);
8844 sc = find_sample_conv(trash->area, trash->data);
8845 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008846 fcn = sc->private;
8847 if (fcn->function_ref[hlua_state_id] != -1) {
8848 ha_warning("Trying to register converter 'lua.%s' more than once. "
8849 "This will become a hard error in version 2.5.\n", name);
8850 }
8851 fcn->function_ref[hlua_state_id] = ref;
8852 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008853 }
8854
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008855 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008856 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008857 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008858 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008859 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008860 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008861 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008862
8863 /* Fill fcn. */
8864 fcn->name = strdup(name);
8865 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008866 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008867 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008868
8869 /* List head */
8870 sck->list.n = sck->list.p = NULL;
8871
8872 /* converter keyword. */
8873 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008874 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008875 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008876 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008877
8878 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8879 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008880 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 +01008881 sck->kw[0].val_args = NULL;
8882 sck->kw[0].in_type = SMP_T_STR;
8883 sck->kw[0].out_type = SMP_T_STR;
8884 sck->kw[0].private = fcn;
8885
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008886 /* Register this new converter */
8887 sample_register_convs(sck);
8888
8889 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008890
8891 alloc_error:
8892 release_hlua_function(fcn);
8893 ha_free(&sck);
8894 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8895 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008896}
8897
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008898/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008899 * "sample-fetch" functions. It expects a converter name used
8900 * in the haproxy configuration file, and an LUA function.
8901 */
8902__LJMP static int hlua_register_fetches(lua_State *L)
8903{
8904 const char *name;
8905 int ref;
8906 int len;
8907 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008908 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008909 struct sample_fetch *sf;
8910 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008911
8912 MAY_LJMP(check_args(L, 2, "register_fetches"));
8913
8914 /* First argument : sample-fetch name. */
8915 name = MAY_LJMP(luaL_checkstring(L, 1));
8916
8917 /* Second argument : lua function. */
8918 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8919
Thierry Fournierf67442e2020-11-28 20:41:07 +01008920 /* Check if the sample-fetch is already registered */
8921 trash = get_trash_chunk();
8922 chunk_printf(trash, "lua.%s", name);
8923 sf = find_sample_fetch(trash->area, trash->data);
8924 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008925 fcn = sf->private;
8926 if (fcn->function_ref[hlua_state_id] != -1) {
8927 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8928 "This will become a hard error in version 2.5.\n", name);
8929 }
8930 fcn->function_ref[hlua_state_id] = ref;
8931 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008932 }
8933
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008934 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008935 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008936 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008937 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008938 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008939 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008940 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008941
8942 /* Fill fcn. */
8943 fcn->name = strdup(name);
8944 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008945 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008946 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008947
8948 /* List head */
8949 sfk->list.n = sfk->list.p = NULL;
8950
8951 /* sample-fetch keyword. */
8952 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008953 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008954 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008955 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008956
8957 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8958 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008959 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 +01008960 sfk->kw[0].val_args = NULL;
8961 sfk->kw[0].out_type = SMP_T_STR;
8962 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8963 sfk->kw[0].val = 0;
8964 sfk->kw[0].private = fcn;
8965
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008966 /* Register this new fetch. */
8967 sample_register_fetches(sfk);
8968
8969 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008970
8971 alloc_error:
8972 release_hlua_function(fcn);
8973 ha_free(&sfk);
8974 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8975 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008976}
8977
Christopher Faulet501465d2020-02-26 14:54:16 +01008978/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008979 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008980__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008981{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008982 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008983 unsigned int delay;
8984 unsigned int wakeup_ms;
8985
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008986 /* Get hlua struct, or NULL if we execute from main lua state */
8987 hlua = hlua_gethlua(L);
8988 if (!hlua) {
8989 return 0;
8990 }
8991
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008992 MAY_LJMP(check_args(L, 1, "wake_time"));
8993
8994 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8995 wakeup_ms = tick_add(now_ms, delay);
8996 hlua->wake_time = wakeup_ms;
8997 return 0;
8998}
8999
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009000/* This function is a wrapper to execute each LUA function declared as an action
9001 * wrapper during the initialisation period. This function may return any
9002 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9003 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9004 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009005 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009006static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009007 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009008{
9009 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009010 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009011 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009012 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009013
9014 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009015 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9016 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9017 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9018 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009019 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009020 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009021 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009022 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009023
Willy Tarreau87b09662015-04-03 00:22:06 +02009024 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009025 * Lua context can be not initialized. This behavior
9026 * permits to save performances because a systematic
9027 * Lua initialization cause 5% performances loss.
9028 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009029 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009030 struct hlua *hlua;
9031
9032 hlua = pool_alloc(pool_head_hlua);
9033 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009034 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009035 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009036 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009037 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009038 HLUA_INIT(hlua);
9039 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009040 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 +01009041 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009042 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009043 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009044 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009045 }
9046
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009047 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009048 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009049
9050 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009051 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009052 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9053 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009054 else
9055 error = "critical error";
9056 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009057 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009058 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009059 }
9060
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009061 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009062 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009063 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009064 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009065 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009066 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009067 }
9068
9069 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009070 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 +01009071
Willy Tarreau87b09662015-04-03 00:22:06 +02009072 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009073 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009074 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009075 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009076 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009077 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009078 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009079 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009080
9081 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009082 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009083 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009084 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009085 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009086 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009087 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009088 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009089 lua_pushstring(s->hlua->T, *arg);
9090 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009091 }
9092
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009093 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009094 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009095
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009096 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009097 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009098 }
9099
9100 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009101 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009102 /* finished. */
9103 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009104 /* Catch the return value */
9105 if (lua_gettop(s->hlua->T) > 0)
9106 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009107
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009108 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009109 if (act_ret == ACT_RET_YIELD) {
9110 if (flags & ACT_OPT_FINAL)
9111 goto err_yield;
9112
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009113 if (dir == SMP_OPT_DIR_REQ)
9114 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9115 s->hlua->wake_time);
9116 else
9117 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9118 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009119 }
9120 goto end;
9121
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009122 /* yield. */
9123 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009124 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009125 if (dir == SMP_OPT_DIR_REQ)
9126 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9127 s->hlua->wake_time);
9128 else
9129 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9130 s->hlua->wake_time);
9131
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009132 /* Some actions can be wake up when a "write" event
9133 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009134 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009135 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009136 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009137 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009138 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009139 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009140 act_ret = ACT_RET_YIELD;
9141 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009142
9143 /* finished with error. */
9144 case HLUA_E_ERRMSG:
9145 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009146 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009147 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009148 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009149 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009150
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009151 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009152 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009153 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009154
9155 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009156 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009157 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009158
9159 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009160 err_yield:
9161 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009162 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009163 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009164 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009165
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009166 case HLUA_E_ERR:
9167 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009168 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009169 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009170
9171 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009172 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009173 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009174
9175 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009176 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009177 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009178 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009179}
9180
Willy Tarreau144f84a2021-03-02 16:09:26 +01009181struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009182{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009183 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009184
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009185 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009186 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009187 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009188}
9189
9190static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
9191{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009192 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009193 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009194 struct task *task;
9195 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009196 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009197
Willy Tarreaubafbe012017-11-24 17:34:44 +01009198 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009199 if (!hlua) {
9200 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009201 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009202 return 0;
9203 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009204 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009205 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009206 ctx->ctx.hlua_apptcp.flags = 0;
9207
9208 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009209 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009210 if (!task) {
9211 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009212 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009213 return 0;
9214 }
9215 task->nice = 0;
9216 task->context = ctx;
9217 task->process = hlua_applet_wakeup;
9218 ctx->ctx.hlua_apptcp.task = task;
9219
9220 /* In the execution wrappers linked with a stream, the
9221 * Lua context can be not initialized. This behavior
9222 * permits to save performances because a systematic
9223 * Lua initialization cause 5% performances loss.
9224 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009225 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 +02009226 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009227 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009228 return 0;
9229 }
9230
9231 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009232 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009233
9234 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009235 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009236 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9237 error = lua_tostring(hlua->T, -1);
9238 else
9239 error = "critical error";
9240 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009241 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009242 return 0;
9243 }
9244
9245 /* Check stack available size. */
9246 if (!lua_checkstack(hlua->T, 1)) {
9247 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009248 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009249 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009250 return 0;
9251 }
9252
9253 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009254 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009255
9256 /* Create and and push object stream in the stack. */
9257 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
9258 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009259 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009260 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009261 return 0;
9262 }
9263 hlua->nargs = 1;
9264
9265 /* push keywords in the stack. */
9266 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9267 if (!lua_checkstack(hlua->T, 1)) {
9268 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009269 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009270 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009271 return 0;
9272 }
9273 lua_pushstring(hlua->T, *arg);
9274 hlua->nargs++;
9275 }
9276
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009277 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009278
9279 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009280 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01009281 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009282
9283 return 1;
9284}
9285
Willy Tarreau60409db2019-08-21 14:14:50 +02009286void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009287{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009288 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009289 struct stream *strm = si_strm(si);
9290 struct channel *res = si_ic(si);
9291 struct act_rule *rule = ctx->rule;
9292 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009293 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009294
9295 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02009296 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
9297 /* eat the whole request */
9298 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009299 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009300 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009301
9302 /* If the stream is disconnect or closed, ldo nothing. */
9303 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9304 return;
9305
9306 /* Execute the function. */
9307 switch (hlua_ctx_resume(hlua, 1)) {
9308 /* finished. */
9309 case HLUA_E_OK:
9310 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9311
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009312 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02009313 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009314 res->flags |= CF_READ_NULL;
9315 si_shutr(si);
9316 return;
9317
9318 /* yield. */
9319 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009320 if (hlua->wake_time != TICK_ETERNITY)
9321 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009322 return;
9323
9324 /* finished with error. */
9325 case HLUA_E_ERRMSG:
9326 /* Display log. */
9327 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009328 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009329 lua_pop(hlua->T, 1);
9330 goto error;
9331
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009332 case HLUA_E_ETMOUT:
9333 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009334 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009335 goto error;
9336
9337 case HLUA_E_NOMEM:
9338 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009339 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009340 goto error;
9341
9342 case HLUA_E_YIELD: /* unexpected */
9343 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009344 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009345 goto error;
9346
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009347 case HLUA_E_ERR:
9348 /* Display log. */
9349 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009350 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009351 goto error;
9352
9353 default:
9354 goto error;
9355 }
9356
9357error:
9358
9359 /* For all other cases, just close the stream. */
9360 si_shutw(si);
9361 si_shutr(si);
9362 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9363}
9364
9365static void hlua_applet_tcp_release(struct appctx *ctx)
9366{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009367 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009368 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009369 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009370 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009371}
9372
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009373/* The function returns 1 if the initialisation is complete, 0 if
9374 * an errors occurs and -1 if more data are required for initializing
9375 * the applet.
9376 */
9377static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
9378{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009379 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009380 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009381 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009382 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009383 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009384 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009385
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009386 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009387 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009388 if (!hlua) {
9389 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009390 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009391 return 0;
9392 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009393 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009394 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009395 ctx->ctx.hlua_apphttp.left_bytes = -1;
9396 ctx->ctx.hlua_apphttp.flags = 0;
9397
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009398 if (txn->req.flags & HTTP_MSGF_VER_11)
9399 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
9400
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009401 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009402 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009403 if (!task) {
9404 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009405 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009406 return 0;
9407 }
9408 task->nice = 0;
9409 task->context = ctx;
9410 task->process = hlua_applet_wakeup;
9411 ctx->ctx.hlua_apphttp.task = task;
9412
9413 /* In the execution wrappers linked with a stream, the
9414 * Lua context can be not initialized. This behavior
9415 * permits to save performances because a systematic
9416 * Lua initialization cause 5% performances loss.
9417 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009418 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 +02009419 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009420 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009421 return 0;
9422 }
9423
9424 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009425 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009426
9427 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009428 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009429 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9430 error = lua_tostring(hlua->T, -1);
9431 else
9432 error = "critical error";
9433 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009434 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009435 return 0;
9436 }
9437
9438 /* Check stack available size. */
9439 if (!lua_checkstack(hlua->T, 1)) {
9440 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009441 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009442 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009443 return 0;
9444 }
9445
9446 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009447 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009448
9449 /* Create and and push object stream in the stack. */
9450 if (!hlua_applet_http_new(hlua->T, ctx)) {
9451 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009452 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009453 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009454 return 0;
9455 }
9456 hlua->nargs = 1;
9457
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009458 /* push keywords in the stack. */
9459 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9460 if (!lua_checkstack(hlua->T, 1)) {
9461 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009462 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009463 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009464 return 0;
9465 }
9466 lua_pushstring(hlua->T, *arg);
9467 hlua->nargs++;
9468 }
9469
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009470 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009471
9472 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009473 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009474
9475 return 1;
9476}
9477
Willy Tarreau60409db2019-08-21 14:14:50 +02009478void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009479{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009480 struct stream_interface *si = cs_si(ctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009481 struct stream *strm = si_strm(si);
9482 struct channel *req = si_oc(si);
9483 struct channel *res = si_ic(si);
9484 struct act_rule *rule = ctx->rule;
9485 struct proxy *px = strm->be;
9486 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
9487 struct htx *req_htx, *res_htx;
9488
9489 res_htx = htx_from_buf(&res->buf);
9490
9491 /* If the stream is disconnect or closed, ldo nothing. */
9492 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9493 goto out;
9494
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009495 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009496 if (!b_size(&res->buf)) {
9497 si_rx_room_blk(si);
9498 goto out;
9499 }
9500 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009501 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009502 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9503
9504 /* Set the currently running flag. */
9505 if (!HLUA_IS_RUNNING(hlua) &&
9506 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009507 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009508 si_cant_get(si);
9509 goto out;
9510 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009511 }
9512
9513 /* Executes The applet if it is not done. */
9514 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9515
9516 /* Execute the function. */
9517 switch (hlua_ctx_resume(hlua, 1)) {
9518 /* finished. */
9519 case HLUA_E_OK:
9520 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9521 break;
9522
9523 /* yield. */
9524 case HLUA_E_AGAIN:
9525 if (hlua->wake_time != TICK_ETERNITY)
9526 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009527 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009528
9529 /* finished with error. */
9530 case HLUA_E_ERRMSG:
9531 /* Display log. */
9532 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009533 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009534 lua_pop(hlua->T, 1);
9535 goto error;
9536
9537 case HLUA_E_ETMOUT:
9538 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009539 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009540 goto error;
9541
9542 case HLUA_E_NOMEM:
9543 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009544 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009545 goto error;
9546
9547 case HLUA_E_YIELD: /* unexpected */
9548 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009549 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009550 goto error;
9551
9552 case HLUA_E_ERR:
9553 /* Display log. */
9554 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009555 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009556 goto error;
9557
9558 default:
9559 goto error;
9560 }
9561 }
9562
9563 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009564 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9565 goto done;
9566
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009567 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9568 goto error;
9569
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009570 /* no more data are expected. If the response buffer is empty
9571 * for a chunked message, be sure to add something (EOT block in
9572 * this case) to have something to send. It is important to be
9573 * sure the EOM flags will be handled by the endpoint.
9574 */
9575 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9576 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
9577 si_rx_room_blk(si);
9578 goto out;
9579 }
9580 channel_add_input(res, 1);
9581 }
9582
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009583 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009584 si->cs->flags |= CS_FL_EOI;
9585 res->flags |= CF_EOI;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009586 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9587 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009588 }
9589
9590 done:
9591 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009592 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009593 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009594 si_shutr(si);
9595 }
9596
9597 /* eat the whole request */
9598 if (co_data(req)) {
9599 req_htx = htx_from_buf(&req->buf);
9600 co_htx_skip(req, req_htx, co_data(req));
9601 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009602 }
9603 }
9604
9605 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009606 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009607 return;
9608
9609 error:
9610
9611 /* If we are in HTTP mode, and we are not send any
9612 * data, return a 500 server error in best effort:
9613 * if there is no room available in the buffer,
9614 * just close the connection.
9615 */
9616 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009617 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009618
9619 channel_erase(res);
9620 res->buf.data = b_data(err);
9621 memcpy(res->buf.area, b_head(err), b_data(err));
9622 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009623 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009624 }
9625 if (!(strm->flags & SF_ERR_MASK))
9626 strm->flags |= SF_ERR_RESOURCE;
9627 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9628 goto done;
9629}
9630
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009631static void hlua_applet_http_release(struct appctx *ctx)
9632{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009633 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009634 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009635 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009636 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009637}
9638
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009639/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009640 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009641 *
9642 * This function can fail with an abort() due to an Lua critical error.
9643 * We are in the configuration parsing process of HAProxy, this abort() is
9644 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009645 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009646static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9647 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009648{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009649 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009650 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009651
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009652 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009653 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009654 if (!rule->arg.hlua_rule) {
9655 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009656 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009657 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009658
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009659 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009660 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9661 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009662 if (!rule->arg.hlua_rule->args) {
9663 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009664 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009665 }
9666
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009667 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009668 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009669
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009670 /* Expect some arguments */
9671 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009672 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009673 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009674 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009675 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009676 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009677 if (!rule->arg.hlua_rule->args[i]) {
9678 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009679 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009680 }
9681 (*cur_arg)++;
9682 }
9683 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009684
Thierry FOURNIER42148732015-09-02 17:17:33 +02009685 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009686 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009687 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009688
9689 error:
9690 if (rule->arg.hlua_rule) {
9691 if (rule->arg.hlua_rule->args) {
9692 for (i = 0; i < fcn->nargs; i++)
9693 ha_free(&rule->arg.hlua_rule->args[i]);
9694 ha_free(&rule->arg.hlua_rule->args);
9695 }
9696 ha_free(&rule->arg.hlua_rule);
9697 }
9698 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009699}
9700
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009701static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9702 struct act_rule *rule, char **err)
9703{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009704 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009705
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009706 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009707 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009708 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009709 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009710 * the call of this analyzer.
9711 */
9712 if (rule->from != ACT_F_HTTP_REQ) {
9713 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9714 return ACT_RET_PRS_ERR;
9715 }
9716
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009717 /* Memory for the rule. */
9718 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9719 if (!rule->arg.hlua_rule) {
9720 memprintf(err, "out of memory error");
9721 return ACT_RET_PRS_ERR;
9722 }
9723
9724 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009725 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009726
9727 /* TODO: later accept arguments. */
9728 rule->arg.hlua_rule->args = NULL;
9729
9730 /* Add applet pointer in the rule. */
9731 rule->applet.obj_type = OBJ_TYPE_APPLET;
9732 rule->applet.name = fcn->name;
9733 rule->applet.init = hlua_applet_http_init;
9734 rule->applet.fct = hlua_applet_http_fct;
9735 rule->applet.release = hlua_applet_http_release;
9736 rule->applet.timeout = hlua_timeout_applet;
9737
9738 return ACT_RET_PRS_OK;
9739}
9740
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009741/* This function is an LUA binding used for registering
9742 * "sample-conv" functions. It expects a converter name used
9743 * in the haproxy configuration file, and an LUA function.
9744 */
9745__LJMP static int hlua_register_action(lua_State *L)
9746{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009747 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009748 const char *name;
9749 int ref;
9750 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009751 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009752 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009753 struct buffer *trash;
9754 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009755
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009756 /* Initialise the number of expected arguments at 0. */
9757 nargs = 0;
9758
9759 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9760 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009761
9762 /* First argument : converter name. */
9763 name = MAY_LJMP(luaL_checkstring(L, 1));
9764
9765 /* Second argument : environment. */
9766 if (lua_type(L, 2) != LUA_TTABLE)
9767 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9768
9769 /* Third argument : lua function. */
9770 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9771
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009772 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009773 if (lua_gettop(L) >= 4)
9774 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9775
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009776 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009777 lua_pushnil(L);
9778 while (lua_next(L, 2) != 0) {
9779 if (lua_type(L, -1) != LUA_TSTRING)
9780 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9781
Thierry Fournierf67442e2020-11-28 20:41:07 +01009782 /* Check if action exists */
9783 trash = get_trash_chunk();
9784 chunk_printf(trash, "lua.%s", name);
9785 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9786 akw = tcp_req_cont_action(trash->area);
9787 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9788 akw = tcp_res_cont_action(trash->area);
9789 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9790 akw = action_http_req_custom(trash->area);
9791 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9792 akw = action_http_res_custom(trash->area);
9793 } else {
9794 akw = NULL;
9795 }
9796 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009797 fcn = akw->private;
9798 if (fcn->function_ref[hlua_state_id] != -1) {
9799 ha_warning("Trying to register action 'lua.%s' more than once. "
9800 "This will become a hard error in version 2.5.\n", name);
9801 }
9802 fcn->function_ref[hlua_state_id] = ref;
9803
9804 /* pop the environment string. */
9805 lua_pop(L, 1);
9806 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009807 }
9808
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009809 /* Check required environment. Only accepted "http" or "tcp". */
9810 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009811 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009812 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009813 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009814 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009815 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009816 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009817
9818 /* Fill fcn. */
9819 fcn->name = strdup(name);
9820 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009821 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009822 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009823
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009824 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009825 fcn->nargs = nargs;
9826
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009827 /* List head */
9828 akl->list.n = akl->list.p = NULL;
9829
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009830 /* action keyword. */
9831 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009832 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009833 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009834 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009835
9836 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9837
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009838 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009839 akl->kw[0].private = fcn;
9840 akl->kw[0].parse = action_register_lua;
9841
9842 /* select the action registering point. */
9843 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9844 tcp_req_cont_keywords_register(akl);
9845 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9846 tcp_res_cont_keywords_register(akl);
9847 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9848 http_req_keywords_register(akl);
9849 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9850 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009851 else {
9852 release_hlua_function(fcn);
9853 if (akl)
9854 ha_free((char **)&(akl->kw[0].kw));
9855 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009856 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009857 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9858 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009859 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009860
9861 /* pop the environment string. */
9862 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009863
9864 /* reset for next loop */
9865 akl = NULL;
9866 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009867 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009868 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009869
9870 alloc_error:
9871 release_hlua_function(fcn);
9872 ha_free(&akl);
9873 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9874 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009875}
9876
9877static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9878 struct act_rule *rule, char **err)
9879{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009880 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009881
Christopher Faulet280f85b2019-07-15 15:02:04 +02009882 if (px->mode == PR_MODE_HTTP) {
9883 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009884 return ACT_RET_PRS_ERR;
9885 }
9886
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009887 /* Memory for the rule. */
9888 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9889 if (!rule->arg.hlua_rule) {
9890 memprintf(err, "out of memory error");
9891 return ACT_RET_PRS_ERR;
9892 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009893
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009894 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009895 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009896
9897 /* TODO: later accept arguments. */
9898 rule->arg.hlua_rule->args = NULL;
9899
9900 /* Add applet pointer in the rule. */
9901 rule->applet.obj_type = OBJ_TYPE_APPLET;
9902 rule->applet.name = fcn->name;
9903 rule->applet.init = hlua_applet_tcp_init;
9904 rule->applet.fct = hlua_applet_tcp_fct;
9905 rule->applet.release = hlua_applet_tcp_release;
9906 rule->applet.timeout = hlua_timeout_applet;
9907
9908 return 0;
9909}
9910
9911/* This function is an LUA binding used for registering
9912 * "sample-conv" functions. It expects a converter name used
9913 * in the haproxy configuration file, and an LUA function.
9914 */
9915__LJMP static int hlua_register_service(lua_State *L)
9916{
9917 struct action_kw_list *akl;
9918 const char *name;
9919 const char *env;
9920 int ref;
9921 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009922 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009923 struct buffer *trash;
9924 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009925
9926 MAY_LJMP(check_args(L, 3, "register_service"));
9927
9928 /* First argument : converter name. */
9929 name = MAY_LJMP(luaL_checkstring(L, 1));
9930
9931 /* Second argument : environment. */
9932 env = MAY_LJMP(luaL_checkstring(L, 2));
9933
9934 /* Third argument : lua function. */
9935 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9936
Thierry Fournierf67442e2020-11-28 20:41:07 +01009937 /* Check for service already registered */
9938 trash = get_trash_chunk();
9939 chunk_printf(trash, "lua.%s", name);
9940 akw = service_find(trash->area);
9941 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009942 fcn = akw->private;
9943 if (fcn->function_ref[hlua_state_id] != -1) {
9944 ha_warning("Trying to register service 'lua.%s' more than once. "
9945 "This will become a hard error in version 2.5.\n", name);
9946 }
9947 fcn->function_ref[hlua_state_id] = ref;
9948 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009949 }
9950
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009951 /* Allocate and fill the sample fetch keyword struct. */
9952 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9953 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009954 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009955 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009956 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009957 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009958
9959 /* Fill fcn. */
9960 len = strlen("<lua.>") + strlen(name) + 1;
9961 fcn->name = calloc(1, len);
9962 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009963 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009964 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009965 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009966
9967 /* List head */
9968 akl->list.n = akl->list.p = NULL;
9969
9970 /* converter keyword. */
9971 len = strlen("lua.") + strlen(name) + 1;
9972 akl->kw[0].kw = calloc(1, len);
9973 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009974 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009975
9976 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9977
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009978 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009979 if (strcmp(env, "tcp") == 0)
9980 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009981 else if (strcmp(env, "http") == 0)
9982 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009983 else {
9984 release_hlua_function(fcn);
9985 if (akl)
9986 ha_free((char **)&(akl->kw[0].kw));
9987 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009988 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009989 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009990 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009991
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009992 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009993 akl->kw[0].private = fcn;
9994
9995 /* End of array. */
9996 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9997
9998 /* Register this new converter */
9999 service_keywords_register(akl);
10000
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010001 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010002
10003 alloc_error:
10004 release_hlua_function(fcn);
10005 ha_free(&akl);
10006 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10007 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010008}
10009
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010010/* This function initialises Lua cli handler. It copies the
10011 * arguments in the Lua stack and create channel IO objects.
10012 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010013static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010014{
10015 struct hlua *hlua;
10016 struct hlua_function *fcn;
10017 int i;
10018 const char *error;
10019
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010020 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010021 appctx->ctx.hlua_cli.fcn = private;
10022
Willy Tarreaubafbe012017-11-24 17:34:44 +010010023 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010024 if (!hlua) {
10025 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010026 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010027 }
10028 HLUA_INIT(hlua);
10029 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010030
10031 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010032 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010033 * applet_http. It is absolutely compatible.
10034 */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010035 appctx->ctx.hlua_cli.task = task_new_here();
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010036 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010037 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010038 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010039 }
10040 appctx->ctx.hlua_cli.task->nice = 0;
10041 appctx->ctx.hlua_cli.task->context = appctx;
10042 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
10043
10044 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +010010045 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 +010010046 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010047 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010048 }
10049
10050 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010051 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010052 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10053 error = lua_tostring(hlua->T, -1);
10054 else
10055 error = "critical error";
10056 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10057 goto error;
10058 }
10059
10060 /* Check stack available size. */
10061 if (!lua_checkstack(hlua->T, 2)) {
10062 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10063 goto error;
10064 }
10065
10066 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010067 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010068
10069 /* Once the arguments parsed, the CLI is like an AppletTCP,
10070 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010071 */
10072 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10073 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10074 goto error;
10075 }
10076 hlua->nargs = 1;
10077
10078 /* push keywords in the stack. */
10079 for (i = 0; *args[i]; i++) {
10080 /* Check stack available size. */
10081 if (!lua_checkstack(hlua->T, 1)) {
10082 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10083 goto error;
10084 }
10085 lua_pushstring(hlua->T, args[i]);
10086 hlua->nargs++;
10087 }
10088
10089 /* We must initialize the execution timeouts. */
10090 hlua->max_time = hlua_timeout_session;
10091
10092 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010093 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010094
10095 /* It's ok */
10096 return 0;
10097
10098 /* It's not ok. */
10099error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010100 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010101 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010102 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010103 return 1;
10104}
10105
10106static int hlua_cli_io_handler_fct(struct appctx *appctx)
10107{
10108 struct hlua *hlua;
10109 struct stream_interface *si;
10110 struct hlua_function *fcn;
10111
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010112 hlua = appctx->ctx.hlua_cli.hlua;
Christopher Faulet86e1c332021-12-20 17:09:39 +010010113 si = cs_si(appctx->owner);
Willy Tarreau8ae4f752016-12-14 15:41:45 +010010114 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010115
10116 /* If the stream is disconnect or closed, ldo nothing. */
10117 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
10118 return 1;
10119
10120 /* Execute the function. */
10121 switch (hlua_ctx_resume(hlua, 1)) {
10122
10123 /* finished. */
10124 case HLUA_E_OK:
10125 return 1;
10126
10127 /* yield. */
10128 case HLUA_E_AGAIN:
10129 /* We want write. */
10130 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +010010131 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010132 /* Set the timeout. */
10133 if (hlua->wake_time != TICK_ETERNITY)
10134 task_schedule(hlua->task, hlua->wake_time);
10135 return 0;
10136
10137 /* finished with error. */
10138 case HLUA_E_ERRMSG:
10139 /* Display log. */
10140 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10141 fcn->name, lua_tostring(hlua->T, -1));
10142 lua_pop(hlua->T, 1);
10143 return 1;
10144
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010145 case HLUA_E_ETMOUT:
10146 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10147 fcn->name);
10148 return 1;
10149
10150 case HLUA_E_NOMEM:
10151 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10152 fcn->name);
10153 return 1;
10154
10155 case HLUA_E_YIELD: /* unexpected */
10156 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10157 fcn->name);
10158 return 1;
10159
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010160 case HLUA_E_ERR:
10161 /* Display log. */
10162 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10163 fcn->name);
10164 return 1;
10165
10166 default:
10167 return 1;
10168 }
10169
10170 return 1;
10171}
10172
10173static void hlua_cli_io_release_fct(struct appctx *appctx)
10174{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010175 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010176 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010177}
10178
10179/* This function is an LUA binding used for registering
10180 * new keywords in the cli. It expects a list of keywords
10181 * which are the "path". It is limited to 5 keywords. A
10182 * description of the command, a function to be executed
10183 * for the parsing and a function for io handlers.
10184 */
10185__LJMP static int hlua_register_cli(lua_State *L)
10186{
10187 struct cli_kw_list *cli_kws;
10188 const char *message;
10189 int ref_io;
10190 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010191 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010192 int index;
10193 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010194 struct buffer *trash;
10195 const char *kw[5];
10196 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010197 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010198
10199 MAY_LJMP(check_args(L, 3, "register_cli"));
10200
10201 /* First argument : an array of maximum 5 keywords. */
10202 if (!lua_istable(L, 1))
10203 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10204
10205 /* Second argument : string with contextual message. */
10206 message = MAY_LJMP(luaL_checkstring(L, 2));
10207
10208 /* Third and fourth argument : lua function. */
10209 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10210
Thierry Fournierf67442e2020-11-28 20:41:07 +010010211 /* Check for CLI service already registered */
10212 trash = get_trash_chunk();
10213 index = 0;
10214 lua_pushnil(L);
10215 memset(kw, 0, sizeof(kw));
10216 while (lua_next(L, 1) != 0) {
10217 if (index >= CLI_PREFIX_KW_NB)
10218 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10219 if (lua_type(L, -1) != LUA_TSTRING)
10220 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10221 kw[index] = lua_tostring(L, -1);
10222 if (index == 0)
10223 chunk_printf(trash, "%s", kw[index]);
10224 else
10225 chunk_appendf(trash, " %s", kw[index]);
10226 index++;
10227 lua_pop(L, 1);
10228 }
10229 cli_kw = cli_find_kw_exact((char **)kw);
10230 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010231 fcn = cli_kw->private;
10232 if (fcn->function_ref[hlua_state_id] != -1) {
10233 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10234 "This will become a hard error in version 2.5.\n", trash->area);
10235 }
10236 fcn->function_ref[hlua_state_id] = ref_io;
10237 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010238 }
10239
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010240 /* Allocate and fill the sample fetch keyword struct. */
10241 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010242 if (!cli_kws) {
10243 errmsg = "Lua out of memory error.";
10244 goto error;
10245 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010246 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010247 if (!fcn) {
10248 errmsg = "Lua out of memory error.";
10249 goto error;
10250 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010251
10252 /* Fill path. */
10253 index = 0;
10254 lua_pushnil(L);
10255 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010256 if (index >= 5) {
10257 errmsg = "1st argument must be a table with a maximum of 5 entries";
10258 goto error;
10259 }
10260 if (lua_type(L, -1) != LUA_TSTRING) {
10261 errmsg = "1st argument must be a table filled with strings";
10262 goto error;
10263 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010264 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010265 if (!cli_kws->kw[0].str_kw[index]) {
10266 errmsg = "Lua out of memory error.";
10267 goto error;
10268 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010269 index++;
10270 lua_pop(L, 1);
10271 }
10272
10273 /* Copy help message. */
10274 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010275 if (!cli_kws->kw[0].usage) {
10276 errmsg = "Lua out of memory error.";
10277 goto error;
10278 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010279
10280 /* Fill fcn io handler. */
10281 len = strlen("<lua.cli>") + 1;
10282 for (i = 0; i < index; i++)
10283 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10284 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010285 if (!fcn->name) {
10286 errmsg = "Lua out of memory error.";
10287 goto error;
10288 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010289 strncat((char *)fcn->name, "<lua.cli", len);
10290 for (i = 0; i < index; i++) {
10291 strncat((char *)fcn->name, ".", len);
10292 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10293 }
10294 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010295 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010296
10297 /* Fill last entries. */
10298 cli_kws->kw[0].private = fcn;
10299 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10300 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10301 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10302
10303 /* Register this new converter */
10304 cli_register_kw(cli_kws);
10305
10306 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010307
10308 error:
10309 release_hlua_function(fcn);
10310 if (cli_kws) {
10311 for (i = 0; i < index; i++)
10312 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10313 ha_free((char **)&(cli_kws->kw[0].usage));
10314 }
10315 ha_free(&cli_kws);
10316 WILL_LJMP(luaL_error(L, errmsg));
10317 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010318}
10319
Christopher Faulet69c581a2021-05-31 08:54:04 +020010320static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10321{
10322 struct hlua_flt_config *conf = fconf->conf;
10323 lua_State *L;
10324 int error, pos, state_id, flt_ref;
10325
10326 state_id = reg_flt_to_stack_id(conf->reg);
10327 L = hlua_states[state_id];
10328 pos = lua_gettop(L);
10329
10330 /* The filter parsing function */
10331 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10332
10333 /* Push the filter class on the stack and resolve all callbacks */
10334 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10335
10336 /* Duplicate the filter class so each filter will have its own copy */
10337 lua_newtable(L);
10338 lua_pushnil(L);
10339
10340 while (lua_next(L, pos+2)) {
10341 lua_pushvalue(L, -2);
10342 lua_insert(L, -2);
10343 lua_settable(L, -4);
10344 }
10345 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10346
10347 /* Remove the original lua filter class from the stack */
10348 lua_pop(L, 1);
10349
10350 /* Push the copy on the stack */
10351 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10352
10353 /* extra args are pushed in a table */
10354 lua_newtable(L);
10355 for (pos = 0; conf->args[pos]; pos++) {
10356 /* Check stack available size. */
10357 if (!lua_checkstack(L, 1)) {
10358 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10359 goto error;
10360 }
10361 lua_pushstring(L, conf->args[pos]);
10362 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10363 }
10364
10365 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10366 switch (error) {
10367 case LUA_OK:
10368 /* replace the filter ref */
10369 conf->ref[state_id] = flt_ref;
10370 break;
10371 case LUA_ERRRUN:
10372 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10373 goto error;
10374 case LUA_ERRMEM:
10375 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10376 goto error;
10377 case LUA_ERRERR:
10378 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10379 goto error;
10380#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10381 case LUA_ERRGCMM:
10382 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10383 goto error;
10384#endif
10385 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010386 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010387 goto error;
10388 }
10389
10390 lua_settop(L, 0);
10391 return 0;
10392
10393 error:
10394 lua_settop(L, 0);
10395 return -1;
10396}
10397
10398static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10399{
10400 struct hlua_flt_config *conf = fconf->conf;
10401 lua_State *L;
10402 int state_id;
10403
10404 if (!conf)
10405 return;
10406
10407 state_id = reg_flt_to_stack_id(conf->reg);
10408 L = hlua_states[state_id];
10409 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10410}
10411
10412static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10413{
10414 struct hlua_flt_config *conf = fconf->conf;
10415 int state_id = reg_flt_to_stack_id(conf->reg);
10416
10417 /* Rely on per-thread init for global scripts */
10418 if (!state_id)
10419 return hlua_filter_init_per_thread(px, fconf);
10420 return 0;
10421}
10422
10423static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10424{
10425
10426 if (fconf->conf) {
10427 struct hlua_flt_config *conf = fconf->conf;
10428 int state_id = reg_flt_to_stack_id(conf->reg);
10429 int pos;
10430
10431 /* Rely on per-thread deinit for global scripts */
10432 if (!state_id)
10433 hlua_filter_deinit_per_thread(px, fconf);
10434
10435 for (pos = 0; conf->args[pos]; pos++)
10436 free(conf->args[pos]);
10437 free(conf->args);
10438 }
10439 ha_free(&fconf->conf);
10440 ha_free((char **)&fconf->id);
10441 ha_free(&fconf->ops);
10442}
10443
10444static int hlua_filter_new(struct stream *s, struct filter *filter)
10445{
10446 struct hlua_flt_config *conf = FLT_CONF(filter);
10447 struct hlua_flt_ctx *flt_ctx = NULL;
10448 int ret = 1;
10449
10450 /* In the execution wrappers linked with a stream, the
10451 * Lua context can be not initialized. This behavior
10452 * permits to save performances because a systematic
10453 * Lua initialization cause 5% performances loss.
10454 */
10455 if (!s->hlua) {
10456 struct hlua *hlua;
10457
10458 hlua = pool_alloc(pool_head_hlua);
10459 if (!hlua) {
10460 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10461 conf->reg->name);
10462 ret = 0;
10463 goto end;
10464 }
10465 HLUA_INIT(hlua);
10466 s->hlua = hlua;
10467 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10468 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10469 conf->reg->name);
10470 ret = 0;
10471 goto end;
10472 }
10473 }
10474
10475 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10476 if (!flt_ctx) {
10477 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10478 conf->reg->name);
10479 ret = 0;
10480 goto end;
10481 }
10482 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10483 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10484 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10485 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10486 conf->reg->name);
10487 ret = 0;
10488 goto end;
10489 }
10490 HLUA_INIT(flt_ctx->hlua[0]);
10491 HLUA_INIT(flt_ctx->hlua[1]);
10492 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10493 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10494 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10495 conf->reg->name);
10496 ret = 0;
10497 goto end;
10498 }
10499
10500 if (!HLUA_IS_RUNNING(s->hlua)) {
10501 /* The following Lua calls can fail. */
10502 if (!SET_SAFE_LJMP(s->hlua)) {
10503 const char *error;
10504
10505 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10506 error = lua_tostring(s->hlua->T, -1);
10507 else
10508 error = "critical error";
10509 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10510 ret = 0;
10511 goto end;
10512 }
10513
10514 /* Check stack size. */
10515 if (!lua_checkstack(s->hlua->T, 1)) {
10516 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010517 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010518 ret = 0;
10519 goto end;
10520 }
10521
10522 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10523 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10524 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10525 conf->reg->name);
10526 RESET_SAFE_LJMP(s->hlua);
10527 ret = 0;
10528 goto end;
10529 }
10530 lua_insert(s->hlua->T, -2);
10531
10532 /* Push the copy on the stack */
10533 s->hlua->nargs = 1;
10534
10535 /* We must initialize the execution timeouts. */
10536 s->hlua->max_time = hlua_timeout_session;
10537
10538 /* At this point the execution is safe. */
10539 RESET_SAFE_LJMP(s->hlua);
10540 }
10541
10542 switch (hlua_ctx_resume(s->hlua, 0)) {
10543 case HLUA_E_OK:
10544 /* Nothing returned or not a table, ignore the filter for current stream */
10545 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10546 ret = 0;
10547 goto end;
10548 }
10549
10550 /* Attached the filter pointer to the ctx */
10551 lua_pushstring(s->hlua->T, "__filter");
10552 lua_pushlightuserdata(s->hlua->T, filter);
10553 lua_settable(s->hlua->T, -3);
10554
10555 /* Save a ref on the filter ctx */
10556 lua_pushvalue(s->hlua->T, 1);
10557 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10558 filter->ctx = flt_ctx;
10559 break;
10560 case HLUA_E_ERRMSG:
10561 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10562 ret = -1;
10563 goto end;
10564 case HLUA_E_ETMOUT:
10565 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10566 ret = 0;
10567 goto end;
10568 case HLUA_E_NOMEM:
10569 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10570 ret = 0;
10571 goto end;
10572 case HLUA_E_AGAIN:
10573 case HLUA_E_YIELD:
10574 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10575 " are not allowed from 'new' function.\n", conf->reg->name);
10576 ret = 0;
10577 goto end;
10578 case HLUA_E_ERR:
10579 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10580 ret = 0;
10581 goto end;
10582 default:
10583 ret = 0;
10584 goto end;
10585 }
10586
10587 end:
10588 if (s->hlua)
10589 lua_settop(s->hlua->T, 0);
10590 if (ret <= 0) {
10591 if (flt_ctx) {
10592 hlua_ctx_destroy(flt_ctx->hlua[0]);
10593 hlua_ctx_destroy(flt_ctx->hlua[1]);
10594 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10595 }
10596 }
10597 return ret;
10598}
10599
10600static void hlua_filter_delete(struct stream *s, struct filter *filter)
10601{
10602 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10603
10604 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10605 hlua_ctx_destroy(flt_ctx->hlua[0]);
10606 hlua_ctx_destroy(flt_ctx->hlua[1]);
10607 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10608 filter->ctx = NULL;
10609}
10610
Christopher Faulet9f55a502020-02-25 15:21:02 +010010611static int hlua_filter_from_payload(struct filter *filter)
10612{
10613 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10614
10615 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10616}
10617
Christopher Fauletc404f112020-02-26 15:03:09 +010010618static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10619 int dir, unsigned int flags)
10620{
10621 struct hlua *flt_hlua;
10622 struct hlua_flt_config *conf = FLT_CONF(filter);
10623 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10624 unsigned int hflags = HLUA_TXN_FLT_CTX;
10625 int ret = 1;
10626
10627 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10628 if (!flt_hlua)
10629 goto end;
10630
10631 if (!HLUA_IS_RUNNING(flt_hlua)) {
10632 int extra_idx = lua_gettop(flt_hlua->T);
10633
10634 /* The following Lua calls can fail. */
10635 if (!SET_SAFE_LJMP(flt_hlua)) {
10636 const char *error;
10637
10638 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10639 error = lua_tostring(flt_hlua->T, -1);
10640 else
10641 error = "critical error";
10642 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10643 goto end;
10644 }
10645
10646 /* Check stack size. */
10647 if (!lua_checkstack(flt_hlua->T, 3)) {
10648 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10649 RESET_SAFE_LJMP(flt_hlua);
10650 goto end;
10651 }
10652
10653 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10654 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10655 RESET_SAFE_LJMP(flt_hlua);
10656 goto end;
10657 }
10658 lua_insert(flt_hlua->T, -2);
10659
10660 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10661 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10662 RESET_SAFE_LJMP(flt_hlua);
10663 goto end;
10664 }
10665 flt_hlua->nargs = 2;
10666
10667 if (flags & HLUA_FLT_CB_ARG_CHN) {
10668 if (dir == SMP_OPT_DIR_REQ)
10669 lua_getfield(flt_hlua->T, -1, "req");
10670 else
10671 lua_getfield(flt_hlua->T, -1, "res");
10672 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10673 lua_pushstring(flt_hlua->T, "__filter");
10674 lua_pushlightuserdata(flt_hlua->T, filter);
10675 lua_settable(flt_hlua->T, -3);
10676 }
10677 flt_hlua->nargs++;
10678 }
10679 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010680 if (dir == SMP_OPT_DIR_REQ)
10681 lua_getfield(flt_hlua->T, -1, "http_req");
10682 else
10683 lua_getfield(flt_hlua->T, -1, "http_res");
10684 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10685 lua_pushstring(flt_hlua->T, "__filter");
10686 lua_pushlightuserdata(flt_hlua->T, filter);
10687 lua_settable(flt_hlua->T, -3);
10688 }
10689 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010690 }
10691
10692 /* Check stack size. */
10693 if (!lua_checkstack(flt_hlua->T, 1)) {
10694 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10695 RESET_SAFE_LJMP(flt_hlua);
10696 goto end;
10697 }
10698
10699 while (extra_idx--) {
10700 lua_pushvalue(flt_hlua->T, 1);
10701 lua_remove(flt_hlua->T, 1);
10702 flt_hlua->nargs++;
10703 }
10704
10705 /* We must initialize the execution timeouts. */
10706 flt_hlua->max_time = hlua_timeout_session;
10707
10708 /* At this point the execution is safe. */
10709 RESET_SAFE_LJMP(flt_hlua);
10710 }
10711
10712 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10713 case HLUA_E_OK:
10714 /* Catch the return value if it required */
10715 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10716 ret = lua_tointeger(flt_hlua->T, -1);
10717 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10718 }
10719
10720 /* Set timeout in the required channel. */
10721 if (flt_hlua->wake_time != TICK_ETERNITY) {
10722 if (dir == SMP_OPT_DIR_REQ)
10723 s->req.analyse_exp = flt_hlua->wake_time;
10724 else
10725 s->res.analyse_exp = flt_hlua->wake_time;
10726 }
10727 break;
10728 case HLUA_E_AGAIN:
10729 /* Set timeout in the required channel. */
10730 if (flt_hlua->wake_time != TICK_ETERNITY) {
10731 if (dir == SMP_OPT_DIR_REQ)
10732 s->req.analyse_exp = flt_hlua->wake_time;
10733 else
10734 s->res.analyse_exp = flt_hlua->wake_time;
10735 }
10736 /* Some actions can be wake up when a "write" event
10737 * is detected on a response channel. This is useful
10738 * only for actions targeted on the requests.
10739 */
10740 if (HLUA_IS_WAKERESWR(flt_hlua))
10741 s->res.flags |= CF_WAKE_WRITE;
10742 if (HLUA_IS_WAKEREQWR(flt_hlua))
10743 s->req.flags |= CF_WAKE_WRITE;
10744 ret = 0;
10745 goto end;
10746 case HLUA_E_ERRMSG:
10747 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10748 ret = -1;
10749 goto end;
10750 case HLUA_E_ETMOUT:
10751 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10752 goto end;
10753 case HLUA_E_NOMEM:
10754 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10755 goto end;
10756 case HLUA_E_YIELD:
10757 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10758 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10759 goto end;
10760 case HLUA_E_ERR:
10761 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10762 goto end;
10763 default:
10764 goto end;
10765 }
10766
10767
10768 end:
10769 return ret;
10770}
10771
10772static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10773{
10774 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10775
10776 flt_ctx->flags = 0;
10777 return hlua_filter_callback(s, filter, "start_analyze",
10778 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10779 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10780}
10781
10782static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10783{
10784 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10785
10786 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10787 return hlua_filter_callback(s, filter, "end_analyze",
10788 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10789 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10790}
10791
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010792static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10793{
10794 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10795
10796 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10797 return hlua_filter_callback(s, filter, "http_headers",
10798 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10799 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10800}
10801
10802static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10803 unsigned int offset, unsigned int len)
10804{
10805 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10806 struct hlua *flt_hlua;
10807 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10808 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10809 int ret;
10810
10811 flt_hlua = flt_ctx->hlua[idx];
10812 flt_ctx->cur_off[idx] = offset;
10813 flt_ctx->cur_len[idx] = len;
10814 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10815 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10816 if (ret != -1) {
10817 ret = flt_ctx->cur_len[idx];
10818 if (lua_gettop(flt_hlua->T) > 0) {
10819 ret = lua_tointeger(flt_hlua->T, -1);
10820 if (ret > flt_ctx->cur_len[idx])
10821 ret = flt_ctx->cur_len[idx];
10822 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10823 }
10824 }
10825 return ret;
10826}
10827
10828static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10829{
10830 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10831
10832 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10833 return hlua_filter_callback(s, filter, "http_end",
10834 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10835 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10836}
10837
Christopher Fauletc404f112020-02-26 15:03:09 +010010838static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10839 unsigned int offset, unsigned int len)
10840{
10841 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10842 struct hlua *flt_hlua;
10843 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10844 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10845 int ret;
10846
10847 flt_hlua = flt_ctx->hlua[idx];
10848 flt_ctx->cur_off[idx] = offset;
10849 flt_ctx->cur_len[idx] = len;
10850 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10851 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10852 if (ret != -1) {
10853 ret = flt_ctx->cur_len[idx];
10854 if (lua_gettop(flt_hlua->T) > 0) {
10855 ret = lua_tointeger(flt_hlua->T, -1);
10856 if (ret > flt_ctx->cur_len[idx])
10857 ret = flt_ctx->cur_len[idx];
10858 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10859 }
10860 }
10861 return ret;
10862}
10863
Christopher Faulet69c581a2021-05-31 08:54:04 +020010864static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10865 struct flt_conf *fconf, char **err, void *private)
10866{
10867 struct hlua_reg_filter *reg_flt = private;
10868 lua_State *L;
10869 struct hlua_flt_config *conf = NULL;
10870 const char *flt_id = NULL;
10871 int state_id, pos, flt_flags = 0;
10872 struct flt_ops *hlua_flt_ops = NULL;
10873
10874 state_id = reg_flt_to_stack_id(reg_flt);
10875 L = hlua_states[state_id];
10876
10877 /* Initialize the filter ops with default callbacks */
10878 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010879 if (!hlua_flt_ops)
10880 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010881 hlua_flt_ops->init = hlua_filter_init;
10882 hlua_flt_ops->deinit = hlua_filter_deinit;
10883 if (state_id) {
10884 /* Set per-thread callback if script is loaded per-thread */
10885 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10886 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10887 }
10888 hlua_flt_ops->attach = hlua_filter_new;
10889 hlua_flt_ops->detach = hlua_filter_delete;
10890
10891 /* Push the filter class on the stack and resolve all callbacks */
10892 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10893
Christopher Fauletc404f112020-02-26 15:03:09 +010010894 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10895 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10896 lua_pop(L, 1);
10897 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10898 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10899 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010900 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10901 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10902 lua_pop(L, 1);
10903 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10904 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10905 lua_pop(L, 1);
10906 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10907 hlua_flt_ops->http_end = hlua_filter_http_end;
10908 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010909 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10910 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10911 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010912
10913 /* Get id and flags of the filter class */
10914 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10915 flt_id = lua_tostring(L, -1);
10916 lua_pop(L, 1);
10917 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10918 flt_flags = lua_tointeger(L, -1);
10919 lua_pop(L, 1);
10920
10921 /* Create the filter config */
10922 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010923 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010924 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010925 conf->reg = reg_flt;
10926
10927 /* duplicate args */
10928 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10929 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010930 if (!conf->args)
10931 goto error;
10932 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010933 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010934 if (!conf->args[pos])
10935 goto error;
10936 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010937 conf->args[pos] = NULL;
10938 *cur_arg += pos + 1;
10939
Christopher Fauletc86bb872021-08-13 08:33:57 +020010940 if (flt_id) {
10941 fconf->id = strdup(flt_id);
10942 if (!fconf->id)
10943 goto error;
10944 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010945 fconf->flags = flt_flags;
10946 fconf->conf = conf;
10947 fconf->ops = hlua_flt_ops;
10948
10949 lua_settop(L, 0);
10950 return 0;
10951
10952 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010953 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010954 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010955 if (conf && conf->args) {
10956 for (pos = 0; conf->args[pos]; pos++)
10957 free(conf->args[pos]);
10958 free(conf->args);
10959 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010960 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010961 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010962 lua_settop(L, 0);
10963 return -1;
10964}
10965
Christopher Fauletc404f112020-02-26 15:03:09 +010010966__LJMP static int hlua_register_data_filter(lua_State *L)
10967{
10968 struct filter *filter;
10969 struct channel *chn;
10970
10971 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10972 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10973 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10974
10975 lua_getfield(L, 1, "__filter");
10976 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10977 filter = lua_touserdata (L, -1);
10978 lua_pop(L, 1);
10979
10980 register_data_filter(chn_strm(chn), chn, filter);
10981 return 1;
10982}
10983
10984__LJMP static int hlua_unregister_data_filter(lua_State *L)
10985{
10986 struct filter *filter;
10987 struct channel *chn;
10988
10989 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10990 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10991 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10992
10993 lua_getfield(L, 1, "__filter");
10994 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10995 filter = lua_touserdata (L, -1);
10996 lua_pop(L, 1);
10997
10998 unregister_data_filter(chn_strm(chn), chn, filter);
10999 return 1;
11000}
11001
Christopher Faulet69c581a2021-05-31 08:54:04 +020011002/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011003 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011004 * parse configuration arguments.
11005 */
11006__LJMP static int hlua_register_filter(lua_State *L)
11007{
11008 struct buffer *trash;
11009 struct flt_kw_list *fkl;
11010 struct flt_kw *fkw;
11011 const char *name;
11012 struct hlua_reg_filter *reg_flt= NULL;
11013 int flt_ref, fun_ref;
11014 int len;
11015
11016 MAY_LJMP(check_args(L, 3, "register_filter"));
11017
11018 /* First argument : filter name. */
11019 name = MAY_LJMP(luaL_checkstring(L, 1));
11020
11021 /* Second argument : The filter class */
11022 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11023
11024 /* Third argument : lua function. */
11025 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11026
11027 trash = get_trash_chunk();
11028 chunk_printf(trash, "lua.%s", name);
11029 fkw = flt_find_kw(trash->area);
11030 if (fkw != NULL) {
11031 reg_flt = fkw->private;
11032 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11033 ha_warning("Trying to register filter 'lua.%s' more than once. "
11034 "This will become a hard error in version 2.5.\n", name);
11035 }
11036 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11037 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11038 return 0;
11039 }
11040
11041 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11042 if (!fkl)
11043 goto alloc_error;
11044 fkl->scope = "HLUA";
11045
11046 reg_flt = new_hlua_reg_filter(name);
11047 if (!reg_flt)
11048 goto alloc_error;
11049
11050 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11051 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11052
11053 /* The filter keyword */
11054 len = strlen("lua.") + strlen(name) + 1;
11055 fkl->kw[0].kw = calloc(1, len);
11056 if (!fkl->kw[0].kw)
11057 goto alloc_error;
11058
11059 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11060
11061 fkl->kw[0].parse = hlua_filter_parse_fct;
11062 fkl->kw[0].private = reg_flt;
11063 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11064
11065 /* Register this new filter */
11066 flt_register_keywords(fkl);
11067
11068 return 0;
11069
11070 alloc_error:
11071 release_hlua_reg_filter(reg_flt);
11072 ha_free(&fkl);
11073 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11074 return 0; /* Never reached */
11075}
11076
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011077static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011078 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011079 char **err, unsigned int *timeout)
11080{
11081 const char *error;
11082
11083 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011084 if (error == PARSE_TIME_OVER) {
11085 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11086 args[1], args[0]);
11087 return -1;
11088 }
11089 else if (error == PARSE_TIME_UNDER) {
11090 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11091 args[1], args[0]);
11092 return -1;
11093 }
11094 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011095 memprintf(err, "%s: invalid timeout", args[0]);
11096 return -1;
11097 }
11098 return 0;
11099}
11100
11101static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011102 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011103 char **err)
11104{
11105 return hlua_read_timeout(args, section_type, curpx, defpx,
11106 file, line, err, &hlua_timeout_session);
11107}
11108
11109static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011110 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011111 char **err)
11112{
11113 return hlua_read_timeout(args, section_type, curpx, defpx,
11114 file, line, err, &hlua_timeout_task);
11115}
11116
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011117static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011118 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011119 char **err)
11120{
11121 return hlua_read_timeout(args, section_type, curpx, defpx,
11122 file, line, err, &hlua_timeout_applet);
11123}
11124
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011125static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011126 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011127 char **err)
11128{
11129 char *error;
11130
11131 hlua_nb_instruction = strtoll(args[1], &error, 10);
11132 if (*error != '\0') {
11133 memprintf(err, "%s: invalid number", args[0]);
11134 return -1;
11135 }
11136 return 0;
11137}
11138
Willy Tarreau32f61e22015-03-18 17:54:59 +010011139static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011140 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011141 char **err)
11142{
11143 char *error;
11144
11145 if (*(args[1]) == 0) {
11146 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11147 return -1;
11148 }
11149 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11150 if (*error != '\0') {
11151 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11152 return -1;
11153 }
11154 return 0;
11155}
11156
11157
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011158/* This function is called by the main configuration key "lua-load". It loads and
11159 * execute an lua file during the parsing of the HAProxy configuration file. It is
11160 * the main lua entry point.
11161 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011162 * This function runs with the HAProxy keywords API. It returns -1 if an error
11163 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011164 *
11165 * In some error case, LUA set an error message in top of the stack. This function
11166 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011167 *
11168 * This function can fail with an abort() due to an Lua critical error.
11169 * We are in the configuration parsing process of HAProxy, this abort() is
11170 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011171 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011172static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011173{
11174 int error;
11175
11176 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011177 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011178 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011179 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11180 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011181 return -1;
11182 }
11183
11184 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011185 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011186 switch (error) {
11187 case LUA_OK:
11188 break;
11189 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011190 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11191 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011192 return -1;
11193 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011194 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011195 return -1;
11196 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011197 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11198 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011199 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011200#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011201 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011202 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11203 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011204 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011205#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011206 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011207 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11208 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011209 return -1;
11210 }
11211
11212 return 0;
11213}
11214
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011215static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011216 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011217 char **err)
11218{
11219 if (*(args[1]) == 0) {
11220 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11221 return -1;
11222 }
11223
Thierry Fournier59f11be2020-11-29 00:37:41 +010011224 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011225 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011226 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011227 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011228}
11229
Thierry Fournier59f11be2020-11-29 00:37:41 +010011230static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011231 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011232 char **err)
11233{
11234 int len;
11235
11236 if (*(args[1]) == 0) {
11237 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11238 return -1;
11239 }
11240
11241 if (per_thread_load == NULL) {
11242 /* allocate the first entry large enough to store the final NULL */
11243 per_thread_load = calloc(1, sizeof(*per_thread_load));
11244 if (per_thread_load == NULL) {
11245 memprintf(err, "out of memory error");
11246 return -1;
11247 }
11248 }
11249
11250 /* count used entries */
11251 for (len = 0; per_thread_load[len] != NULL; len++)
11252 ;
11253
11254 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11255 if (per_thread_load == NULL) {
11256 memprintf(err, "out of memory error");
11257 return -1;
11258 }
11259
11260 per_thread_load[len] = strdup(args[1]);
11261 per_thread_load[len + 1] = NULL;
11262
11263 if (per_thread_load[len] == NULL) {
11264 memprintf(err, "out of memory error");
11265 return -1;
11266 }
11267
11268 /* loading for thread 1 only */
11269 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011270 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011271 return hlua_load_state(args[1], hlua_states[1], err);
11272}
11273
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011274/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11275 * in the given <ctx>.
11276 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011277static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011278{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011279 lua_getglobal(L, "package"); /* push package variable */
11280 lua_pushstring(L, path); /* push given path */
11281 lua_pushstring(L, ";"); /* push semicolon */
11282 lua_getfield(L, -3, type); /* push old path */
11283 lua_concat(L, 3); /* concatenate to new path */
11284 lua_setfield(L, -2, type); /* store new path */
11285 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011286
11287 return 0;
11288}
11289
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011290static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011291 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011292 char **err)
11293{
11294 char *path;
11295 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011296 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011297 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011298
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011299 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011300 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011301 }
11302
11303 if (!(*args[1])) {
11304 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011305 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011306 }
11307 path = args[1];
11308
11309 if (*args[2]) {
11310 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11311 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011312 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011313 }
11314 type = args[2];
11315 }
11316
Thierry Fournier59f11be2020-11-29 00:37:41 +010011317 p = calloc(1, sizeof(*p));
11318 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011319 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011320 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011321 }
11322 p->path = strdup(path);
11323 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011324 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011325 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011326 }
11327 p->type = strdup(type);
11328 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011329 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011330 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011331 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011332 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011333
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011334 /* Handle the global state and the per-thread state for the first
11335 * thread. The remaining threads will be initialized based on
11336 * prepend_path_list.
11337 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011338 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011339 lua_State *L = hlua_states[i];
11340 const char *error;
11341
11342 if (setjmp(safe_ljmp_env) != 0) {
11343 lua_atpanic(L, hlua_panic_safe);
11344 if (lua_type(L, -1) == LUA_TSTRING)
11345 error = lua_tostring(L, -1);
11346 else
11347 error = "critical error";
11348 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11349 exit(1);
11350 } else {
11351 lua_atpanic(L, hlua_panic_ljmp);
11352 }
11353
11354 hlua_prepend_path(L, type, path);
11355
11356 lua_atpanic(L, hlua_panic_safe);
11357 }
11358
Thierry Fournier59f11be2020-11-29 00:37:41 +010011359 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011360
11361err2:
11362 free(p->type);
11363 free(p->path);
11364err:
11365 free(p);
11366 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011367}
11368
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011369/* configuration keywords declaration */
11370static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011371 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011372 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011373 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011374 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11375 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011376 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011377 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011378 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011379 { 0, NULL, NULL },
11380}};
11381
Willy Tarreau0108d902018-11-25 19:14:37 +010011382INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11383
William Lallemand52139182022-03-30 15:05:42 +020011384#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011385
William Lallemand30fcca12022-03-30 12:03:12 +020011386/*
11387 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11388 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11389 * difference is that the yield in lua and for the CLI is not handled the same
11390 * way.
11391 */
11392__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11393{
11394 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11395 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11396 struct ckch_inst *ckchi = *lua_ckchi;
11397 struct ckch_store *old_ckchs = lua_ckchs[0];
11398 struct ckch_store *new_ckchs = lua_ckchs[1];
11399 struct hlua *hlua;
11400 char *err = NULL;
11401 int y = 1;
11402
11403 hlua = hlua_gethlua(L);
11404
11405 /* get the first ckchi to copy */
11406 if (ckchi == NULL)
11407 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11408
11409 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11410 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11411 struct ckch_inst *new_inst;
11412
11413 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11414 if (y % 10 == 0) {
11415
11416 *lua_ckchi = ckchi;
11417
11418 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11419 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11420 }
11421
11422 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11423 goto error;
11424
11425 /* link the new ckch_inst to the duplicate */
11426 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11427 y++;
11428 }
11429
11430 /* The generation is finished, we can insert everything */
11431 ckch_store_replace(old_ckchs, new_ckchs);
11432
11433 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11434
11435 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11436
11437 return 0;
11438
11439error:
11440 ckch_store_free(new_ckchs);
11441 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11442 WILL_LJMP(luaL_error(L, "%s", err));
11443 free(err);
11444
11445 return 0;
11446}
11447
11448/*
11449 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11450 * from the table in parameter.
11451 *
11452 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11453 * means it does not need to have a transaction since everything is done in the
11454 * same function.
11455 *
11456 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11457 *
11458 */
11459__LJMP static int hlua_ckch_set(lua_State *L)
11460{
11461 struct hlua *hlua;
11462 struct ckch_inst **lua_ckchi;
11463 struct ckch_store **lua_ckchs;
11464 struct ckch_store *old_ckchs = NULL;
11465 struct ckch_store *new_ckchs = NULL;
11466 int errcode = 0;
11467 char *err = NULL;
11468 struct cert_exts *cert_ext = NULL;
11469 char *filename;
11470 struct cert_key_and_chain *ckch;
11471 int ret;
11472
11473 if (lua_type(L, -1) != LUA_TTABLE)
11474 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11475
11476 hlua = hlua_gethlua(L);
11477
11478 /* FIXME: this should not return an error but should come back later */
11479 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11480 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11481
11482 ret = lua_getfield(L, -1, "filename");
11483 if (ret != LUA_TSTRING) {
11484 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11485 errcode |= ERR_ALERT | ERR_FATAL;
11486 goto end;
11487 }
11488 filename = (char *)lua_tostring(L, -1);
11489
11490
11491 /* look for the filename in the tree */
11492 old_ckchs = ckchs_lookup(filename);
11493 if (!old_ckchs) {
11494 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11495 errcode |= ERR_ALERT | ERR_FATAL;
11496 goto end;
11497 }
11498 /* TODO: handle extra_files_noext */
11499
11500 new_ckchs = ckchs_dup(old_ckchs);
11501 if (!new_ckchs) {
11502 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11503 errcode |= ERR_ALERT | ERR_FATAL;
11504 goto end;
11505 }
11506
11507 ckch = new_ckchs->ckch;
11508
11509 /* loop on the field in the table, which have the same name as the
11510 * possible extensions of files */
11511 lua_pushnil(L);
11512 while (lua_next(L, 1)) {
11513 int i;
11514 const char *field = lua_tostring(L, -2);
11515 char *payload = (char *)lua_tostring(L, -1);
11516
11517 if (!field || strcmp(field, "filename") == 0) {
11518 lua_pop(L, 1);
11519 continue;
11520 }
11521
11522 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11523 if (strcmp(field, cert_exts[i].ext) == 0) {
11524 cert_ext = &cert_exts[i];
11525 break;
11526 }
11527 }
11528
11529 /* this is the default type, the field is not supported */
11530 if (cert_ext == NULL) {
11531 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11532 errcode |= ERR_ALERT | ERR_FATAL;
11533 goto end;
11534 }
11535
11536 /* appply the change on the duplicate */
11537 if (cert_exts->load(filename, payload, ckch, &err) != 0) {
11538 memprintf(&err, "%sCan't load the payload\n", err ? err : "");
11539 errcode |= ERR_ALERT | ERR_FATAL;
11540 goto end;
11541 }
11542 lua_pop(L, 1);
11543 }
11544
11545 /* store the pointers on the lua stack */
11546 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11547 lua_ckchs[0] = old_ckchs;
11548 lua_ckchs[1] = new_ckchs;
11549 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11550 *lua_ckchi = NULL;
11551
11552 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11553 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11554
11555end:
11556 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11557
11558 if (errcode & ERR_CODE) {
11559 ckch_store_free(new_ckchs);
11560 WILL_LJMP(luaL_error(L, "%s", err));
11561 }
11562 free(err);
11563
11564 return 0;
11565}
11566
William Lallemand52139182022-03-30 15:05:42 +020011567#else
11568
11569__LJMP static int hlua_ckch_set(lua_State *L)
11570{
11571 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11572
11573 return 0;
11574}
11575#endif /* ! USE_OPENSSL */
11576
11577
11578
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011579/* This function can fail with an abort() due to an Lua critical error.
11580 * We are in the initialisation process of HAProxy, this abort() is
11581 * tolerated.
11582 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011583int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011584{
11585 struct hlua_init_function *init;
11586 const char *msg;
11587 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011588 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011589 const char *kind;
11590 const char *trace;
11591 int return_status = 1;
11592#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11593 int nres;
11594#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011595
Willy Tarreaucdb53462020-12-02 12:12:00 +010011596 /* disable memory limit checks if limit is not set */
11597 if (!hlua_global_allocator.limit)
11598 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11599
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011600 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011601 if (setjmp(safe_ljmp_env) != 0) {
11602 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011603 if (lua_type(L, -1) == LUA_TSTRING)
11604 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011605 else
11606 error = "critical error";
11607 fprintf(stderr, "Lua post-init: %s.\n", error);
11608 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011609 } else {
11610 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011611 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011612
Thierry Fournierb8cef172020-11-28 15:37:17 +010011613 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011614
Thierry Fournierc7492592020-11-28 23:57:24 +010011615 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011616 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011617
11618#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011619 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011620#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011621 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011622#endif
11623 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011624 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011625
11626 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011627 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011628 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011629
11630 case LUA_ERRERR:
11631 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011632 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011633 case LUA_ERRRUN:
11634 if (!kind)
11635 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011636 msg = lua_tostring(L, -1);
11637 lua_settop(L, 0); /* Empty the stack. */
11638 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011639 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011640 if (msg)
11641 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11642 else
11643 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11644 return_status = 0;
11645 break;
11646
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011647 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011648 /* Unknown error */
11649 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011650 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011651 case LUA_YIELD:
11652 /* yield is not configured at this step, this state doesn't happen */
11653 if (!kind)
11654 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011655 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011656 case LUA_ERRMEM:
11657 if (!kind)
11658 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011659 lua_settop(L, 0);
11660 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011661 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011662 ha_alert("Lua init: %s: %s\n", kind, trace);
11663 return_status = 0;
11664 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011665 }
Thierry Fournier670db242020-11-28 10:49:59 +010011666 if (!return_status)
11667 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011668 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011669
11670 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011671 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011672}
11673
Thierry Fournierb8cef172020-11-28 15:37:17 +010011674int hlua_post_init()
11675{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011676 int ret;
11677 int i;
11678 int errors;
11679 char *err = NULL;
11680 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011681 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011682
Willy Tarreaub1310492021-08-30 09:35:18 +020011683#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011684 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011685 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011686 int saved_used_backed = global.ssl_used_backend;
11687 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011688 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011689 global.ssl_used_backend = saved_used_backed;
11690 }
11691#endif
11692
Thierry Fournierc7492592020-11-28 23:57:24 +010011693 /* Perform post init of common thread */
11694 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011695 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011696 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11697 if (ret == 0)
11698 return 0;
11699
11700 /* init remaining lua states and load files */
11701 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11702
11703 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011704 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011705
11706 /* Init lua state */
11707 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11708
11709 /* Load lua files */
11710 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11711 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11712 if (ret != 0) {
11713 ha_alert("Lua init: %s\n", err);
11714 return 0;
11715 }
11716 }
11717 }
11718
11719 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011720 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011721
11722 /* Execute post init for all states */
11723 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11724
11725 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011726 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011727
11728 /* run post init */
11729 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11730 if (ret == 0)
11731 return 0;
11732 }
11733
11734 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011735 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011736
11737 /* control functions registering. Each function must have:
11738 * - only the function_ref[0] set positive and all other to -1
11739 * - only the function_ref[0] set to -1 and all other positive
11740 * This ensure a same reference is not used both in shared
11741 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011742 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011743 * complicated to found for the end user.
11744 */
11745 errors = 0;
11746 list_for_each_entry(fcn, &referenced_functions, l) {
11747 ret = 0;
11748 for (i = 1; i < global.nbthread + 1; i++) {
11749 if (fcn->function_ref[i] == -1)
11750 ret--;
11751 else
11752 ret++;
11753 }
11754 if (abs(ret) != global.nbthread) {
11755 ha_alert("Lua function '%s' is not referenced in all thread. "
11756 "Expect function in all thread or in none thread.\n", fcn->name);
11757 errors++;
11758 continue;
11759 }
11760
11761 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011762 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11763 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011764 "exclusive.\n", fcn->name);
11765 errors++;
11766 }
11767 }
11768
Christopher Faulet69c581a2021-05-31 08:54:04 +020011769 /* Do the same with registered filters */
11770 list_for_each_entry(reg_flt, &referenced_filters, l) {
11771 ret = 0;
11772 for (i = 1; i < global.nbthread + 1; i++) {
11773 if (reg_flt->flt_ref[i] == -1)
11774 ret--;
11775 else
11776 ret++;
11777 }
11778 if (abs(ret) != global.nbthread) {
11779 ha_alert("Lua filter '%s' is not referenced in all thread. "
11780 "Expect function in all thread or in none thread.\n", reg_flt->name);
11781 errors++;
11782 continue;
11783 }
11784
11785 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11786 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11787 "and per-thread Lua context (through lua-load-per-thread). these two context "
11788 "exclusive.\n", fcn->name);
11789 errors++;
11790 }
11791 }
11792
11793
Thierry Fournier59f11be2020-11-29 00:37:41 +010011794 if (errors > 0)
11795 return 0;
11796
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011797 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011798 * -1 in order to have probably a segfault if someone use it
11799 */
11800 hlua_state_id = -1;
11801
11802 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011803}
11804
Willy Tarreau32f61e22015-03-18 17:54:59 +010011805/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11806 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11807 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011808 * allocation. <nsize> is the requested new size. A new allocation is
11809 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011810 * zero. This one verifies that the limits are respected but is optimized
11811 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011812 *
11813 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11814 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11815 * that and will simply allocate zero as if it were the result of malloc(0),
11816 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11817 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011818 */
11819static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11820{
11821 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011822 size_t limit, old, new;
11823
11824 /* a limit of ~0 means unlimited and boot complete, so there's no need
11825 * for accounting anymore.
11826 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011827 if (likely(~zone->limit == 0)) {
11828 if (!nsize)
11829 ha_free(&ptr);
11830 else
11831 ptr = realloc(ptr, nsize);
11832 return ptr;
11833 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011834
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011835 if (!ptr)
11836 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011837
Willy Tarreaucdb53462020-12-02 12:12:00 +010011838 /* enforce strict limits across all threads */
11839 limit = zone->limit;
11840 old = _HA_ATOMIC_LOAD(&zone->allocated);
11841 do {
11842 new = old + nsize - osize;
11843 if (unlikely(nsize && limit && new > limit))
11844 return NULL;
11845 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011846
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011847 if (!nsize)
11848 ha_free(&ptr);
11849 else
11850 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011851
11852 if (unlikely(!ptr && nsize)) // failed
11853 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11854
11855 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011856 return ptr;
11857}
11858
Thierry Fournierecb83c22020-11-28 15:49:44 +010011859/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011860 * We are in the initialisation process of HAProxy, this abort() is
11861 * tolerated.
11862 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011863lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011864{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011865 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011866 int idx;
11867 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011868 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011869 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011870 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011871 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011872 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011873 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011874
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011875 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011876 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011877
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011878 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011879 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011880 *context = NULL;
11881
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011882 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011883 * the Lua function can fail with an abort. We are in the initialisation
11884 * process of HAProxy, this abort() is tolerated.
11885 */
11886
Thierry Fournier3c539322020-11-28 16:05:05 +010011887 /* Call post initialisation function in safe environment. */
11888 if (setjmp(safe_ljmp_env) != 0) {
11889 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011890 if (lua_type(L, -1) == LUA_TSTRING)
11891 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011892 else
11893 error_msg = "critical error";
11894 fprintf(stderr, "Lua init: %s.\n", error_msg);
11895 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011896 } else {
11897 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011898 }
11899
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011900 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011901 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011902#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11903#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11904#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011905 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011906#endif
11907#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011908 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011909#endif
11910#undef HLUA_PREPEND_PATH_TOSTRING
11911#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011912
Thierry Fournier59f11be2020-11-29 00:37:41 +010011913 /* Apply configured prepend path */
11914 list_for_each_entry(pp, &prepend_path_list, l)
11915 hlua_prepend_path(L, pp->type, pp->path);
11916
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011917 /*
11918 *
11919 * Create "core" object.
11920 *
11921 */
11922
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011923 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011924 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011925
Thierry Fournierecb83c22020-11-28 15:49:44 +010011926 /* set the thread id */
11927 hlua_class_const_int(L, "thread", thread_num);
11928
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011929 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011930 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011931 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011932
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011933 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011934 hlua_class_function(L, "register_init", hlua_register_init);
11935 hlua_class_function(L, "register_task", hlua_register_task);
11936 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11937 hlua_class_function(L, "register_converters", hlua_register_converters);
11938 hlua_class_function(L, "register_action", hlua_register_action);
11939 hlua_class_function(L, "register_service", hlua_register_service);
11940 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011941 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011942 hlua_class_function(L, "yield", hlua_yield);
11943 hlua_class_function(L, "set_nice", hlua_set_nice);
11944 hlua_class_function(L, "sleep", hlua_sleep);
11945 hlua_class_function(L, "msleep", hlua_msleep);
11946 hlua_class_function(L, "add_acl", hlua_add_acl);
11947 hlua_class_function(L, "del_acl", hlua_del_acl);
11948 hlua_class_function(L, "set_map", hlua_set_map);
11949 hlua_class_function(L, "del_map", hlua_del_map);
11950 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011951 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011952 hlua_class_function(L, "log", hlua_log);
11953 hlua_class_function(L, "Debug", hlua_log_debug);
11954 hlua_class_function(L, "Info", hlua_log_info);
11955 hlua_class_function(L, "Warning", hlua_log_warning);
11956 hlua_class_function(L, "Alert", hlua_log_alert);
11957 hlua_class_function(L, "done", hlua_done);
11958 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011959
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011960 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011961
11962 /*
11963 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011964 * Create "act" object.
11965 *
11966 */
11967
11968 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011969 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011970
11971 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011972 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11973 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11974 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11975 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11976 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11977 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11978 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11979 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011980
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011981 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011982
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011983 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011984
11985 /*
11986 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011987 * Create "Filter" object.
11988 *
11989 */
11990
11991 /* This table entry is the object "filter" base. */
11992 lua_newtable(L);
11993
11994 /* push flags and constants */
11995 hlua_class_const_int(L, "CONTINUE", 1);
11996 hlua_class_const_int(L, "WAIT", 0);
11997 hlua_class_const_int(L, "ERROR", -1);
11998
11999 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12000
Christopher Fauletc404f112020-02-26 15:03:09 +010012001 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12002 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12003 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12004
Christopher Faulet69c581a2021-05-31 08:54:04 +020012005 lua_setglobal(L, "filter");
12006
12007 /*
12008 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012009 * Register class Map
12010 *
12011 */
12012
12013 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012014 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012015
12016 /* register pattern types. */
12017 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012018 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012019 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012020 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012021 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012022 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012023
12024 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012025 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012026
12027 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012028 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012029
Ilya Shipitsind4259502020-04-08 01:07:56 +050012030 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012031 lua_pushstring(L, "__index");
12032 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012033
12034 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012035 hlua_class_function(L, "lookup", hlua_map_lookup);
12036 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012037
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012038 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012039
Thierry Fournier45e78d72016-02-19 18:34:46 +010012040 /* Register previous table in the registry with reference and named entry.
12041 * The function hlua_register_metatable() pops the stack, so we
12042 * previously create a copy of the table.
12043 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012044 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12045 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012046
12047 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012048 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012049
12050 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012051 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012052
12053 /*
12054 *
William Lallemand30fcca12022-03-30 12:03:12 +020012055 * Register "CertCache" class
12056 *
12057 */
12058
12059 /* Create and fill the metatable. */
12060 lua_newtable(L);
12061 /* Register */
12062 hlua_class_function(L, "set", hlua_ckch_set);
12063 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12064
12065 /*
12066 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012067 * Register class Channel
12068 *
12069 */
12070
12071 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012072 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012073
Ilya Shipitsind4259502020-04-08 01:07:56 +050012074 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012075 lua_pushstring(L, "__index");
12076 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012077
12078 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012079 hlua_class_function(L, "data", hlua_channel_get_data);
12080 hlua_class_function(L, "line", hlua_channel_get_line);
12081 hlua_class_function(L, "set", hlua_channel_set_data);
12082 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012083 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012084 hlua_class_function(L, "prepend", hlua_channel_prepend);
12085 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012086 hlua_class_function(L, "send", hlua_channel_send);
12087 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012088 hlua_class_function(L, "input", hlua_channel_get_in_len);
12089 hlua_class_function(L, "output", hlua_channel_get_out_len);
12090 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012091 hlua_class_function(L, "is_full", hlua_channel_is_full);
12092 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012093
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012094 /* Deprecated API */
12095 hlua_class_function(L, "get", hlua_channel_get);
12096 hlua_class_function(L, "dup", hlua_channel_dup);
12097 hlua_class_function(L, "getline", hlua_channel_getline);
12098 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12099 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12100
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012101 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012102
12103 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012104 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012105
12106 /*
12107 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012108 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012109 *
12110 */
12111
12112 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012113 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012114
Ilya Shipitsind4259502020-04-08 01:07:56 +050012115 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012116 lua_pushstring(L, "__index");
12117 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012118
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012119 /* Browse existing fetches and create the associated
12120 * object method.
12121 */
12122 sf = NULL;
12123 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012124 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12125 * by an underscore.
12126 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012127 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012128 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012129 if (*p == '.' || *p == '-' || *p == '+')
12130 *p = '_';
12131
12132 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012133 lua_pushstring(L, trash.area);
12134 lua_pushlightuserdata(L, sf);
12135 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12136 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012137 }
12138
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012139 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012140
12141 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012142 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012143
12144 /*
12145 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012146 * Register class Converters
12147 *
12148 */
12149
12150 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012151 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012152
12153 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012154 lua_pushstring(L, "__index");
12155 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012156
12157 /* Browse existing converters and create the associated
12158 * object method.
12159 */
12160 sc = NULL;
12161 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012162 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12163 * by an underscore.
12164 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012165 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012166 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012167 if (*p == '.' || *p == '-' || *p == '+')
12168 *p = '_';
12169
12170 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012171 lua_pushstring(L, trash.area);
12172 lua_pushlightuserdata(L, sc);
12173 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12174 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012175 }
12176
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012177 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012178
12179 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012180 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012181
12182 /*
12183 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012184 * Register class HTTP
12185 *
12186 */
12187
12188 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012189 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012190
Ilya Shipitsind4259502020-04-08 01:07:56 +050012191 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012192 lua_pushstring(L, "__index");
12193 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012194
12195 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012196 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12197 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12198 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12199 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12200 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12201 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12202 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12203 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12204 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12205 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012206
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012207 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12208 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12209 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12210 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12211 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12212 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12213 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012214
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012215 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012216
12217 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012218 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012219
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012220 /*
12221 *
12222 * Register class HTTPMessage
12223 *
12224 */
12225
12226 /* Create and fill the metatable. */
12227 lua_newtable(L);
12228
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012229 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012230 lua_pushstring(L, "__index");
12231 lua_newtable(L);
12232
12233 /* Register Lua functions. */
12234 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12235 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12236 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12237 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12238 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12239 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12240 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12241 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12242 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12243 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12244 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12245 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12246 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12247 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12248 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12249 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12250 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12251 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12252
12253 hlua_class_function(L, "body", hlua_http_msg_get_body);
12254 hlua_class_function(L, "set", hlua_http_msg_set_data);
12255 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12256 hlua_class_function(L, "append", hlua_http_msg_append);
12257 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12258 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12259 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12260 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12261
12262 hlua_class_function(L, "send", hlua_http_msg_send);
12263 hlua_class_function(L, "forward", hlua_http_msg_forward);
12264
12265 lua_rawset(L, -3);
12266
12267 /* Register previous table in the registry with reference and named entry. */
12268 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012269
12270 /*
12271 *
12272 * Register class HTTPClient
12273 *
12274 */
12275
12276 /* Create and fill the metatable. */
12277 lua_newtable(L);
12278 lua_pushstring(L, "__index");
12279 lua_newtable(L);
12280 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012281 hlua_class_function(L, "head", hlua_httpclient_head);
12282 hlua_class_function(L, "put", hlua_httpclient_put);
12283 hlua_class_function(L, "post", hlua_httpclient_post);
12284 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012285 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012286 /* Register the garbage collector entry. */
12287 lua_pushstring(L, "__gc");
12288 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12289 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12290
William Lallemand3956c4e2021-09-21 16:25:15 +020012291
12292
12293 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012294 /*
12295 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012296 * Register class AppletTCP
12297 *
12298 */
12299
12300 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012301 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012302
Ilya Shipitsind4259502020-04-08 01:07:56 +050012303 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012304 lua_pushstring(L, "__index");
12305 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012306
12307 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012308 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12309 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12310 hlua_class_function(L, "send", hlua_applet_tcp_send);
12311 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12312 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12313 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12314 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12315 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012316
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012317 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012318
12319 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012320 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012321
12322 /*
12323 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012324 * Register class AppletHTTP
12325 *
12326 */
12327
12328 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012329 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012330
Ilya Shipitsind4259502020-04-08 01:07:56 +050012331 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012332 lua_pushstring(L, "__index");
12333 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012334
12335 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012336 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12337 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12338 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12339 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12340 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12341 hlua_class_function(L, "getline", hlua_applet_http_getline);
12342 hlua_class_function(L, "receive", hlua_applet_http_recv);
12343 hlua_class_function(L, "send", hlua_applet_http_send);
12344 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12345 hlua_class_function(L, "set_status", hlua_applet_http_status);
12346 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012347
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012348 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012349
12350 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012351 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012352
12353 /*
12354 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012355 * Register class TXN
12356 *
12357 */
12358
12359 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012360 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012361
Ilya Shipitsind4259502020-04-08 01:07:56 +050012362 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012363 lua_pushstring(L, "__index");
12364 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012365
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012366 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012367 hlua_class_function(L, "set_priv", hlua_set_priv);
12368 hlua_class_function(L, "get_priv", hlua_get_priv);
12369 hlua_class_function(L, "set_var", hlua_set_var);
12370 hlua_class_function(L, "unset_var", hlua_unset_var);
12371 hlua_class_function(L, "get_var", hlua_get_var);
12372 hlua_class_function(L, "done", hlua_txn_done);
12373 hlua_class_function(L, "reply", hlua_txn_reply_new);
12374 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12375 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12376 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12377 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12378 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12379 hlua_class_function(L, "deflog", hlua_txn_deflog);
12380 hlua_class_function(L, "log", hlua_txn_log);
12381 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12382 hlua_class_function(L, "Info", hlua_txn_log_info);
12383 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12384 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012385
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012386 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012387
12388 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012389 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012390
12391 /*
12392 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012393 * Register class reply
12394 *
12395 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012396 lua_newtable(L);
12397 lua_pushstring(L, "__index");
12398 lua_newtable(L);
12399 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12400 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12401 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12402 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12403 lua_settable(L, -3); /* Sets the __index entry. */
12404 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012405
12406
12407 /*
12408 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012409 * Register class Socket
12410 *
12411 */
12412
12413 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012414 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012415
Ilya Shipitsind4259502020-04-08 01:07:56 +050012416 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012417 lua_pushstring(L, "__index");
12418 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012419
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012420#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012421 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012422#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012423 hlua_class_function(L, "connect", hlua_socket_connect);
12424 hlua_class_function(L, "send", hlua_socket_send);
12425 hlua_class_function(L, "receive", hlua_socket_receive);
12426 hlua_class_function(L, "close", hlua_socket_close);
12427 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12428 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12429 hlua_class_function(L, "setoption", hlua_socket_setoption);
12430 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012431
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012432 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012433
12434 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012435 lua_pushstring(L, "__gc");
12436 lua_pushcclosure(L, hlua_socket_gc, 0);
12437 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012438
12439 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012440 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012441
Thierry Fournieraafc7772020-12-04 11:47:47 +010012442 lua_atpanic(L, hlua_panic_safe);
12443
12444 return L;
12445}
12446
12447void hlua_init(void) {
12448 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012449 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012450#ifdef USE_OPENSSL
12451 struct srv_kw *kw;
12452 int tmp_error;
12453 char *error;
12454 char *args[] = { /* SSL client configuration. */
12455 "ssl",
12456 "verify",
12457 "none",
12458 NULL
12459 };
12460#endif
12461
12462 /* Init post init function list head */
12463 for (i = 0; i < MAX_THREADS + 1; i++)
12464 LIST_INIT(&hlua_init_functions[i]);
12465
12466 /* Init state for common/shared lua parts */
12467 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012468 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012469 hlua_states[0] = hlua_init_state(0);
12470
12471 /* Init state 1 for thread 0. We have at least one thread. */
12472 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012473 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012474 hlua_states[1] = hlua_init_state(1);
12475
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012476 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012477 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012478 if (!socket_proxy) {
12479 fprintf(stderr, "Lua init: %s\n", errmsg);
12480 exit(1);
12481 }
12482 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012483
12484 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012485 socket_tcp = new_server(socket_proxy);
12486 if (!socket_tcp) {
12487 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12488 exit(1);
12489 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012490
12491#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012492 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012493 socket_ssl = new_server(socket_proxy);
12494 if (!socket_ssl) {
12495 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12496 exit(1);
12497 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012498
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012499 socket_ssl->use_ssl = 1;
12500 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012501
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012502 for (i = 0; args[i] != NULL; i++) {
12503 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012504 /*
12505 *
12506 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012507 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012508 * features like client certificates and ssl_verify.
12509 *
12510 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012511 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012512 if (tmp_error != 0) {
12513 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12514 abort(); /* This must be never arrives because the command line
12515 not editable by the user. */
12516 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012517 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012518 }
12519 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012520#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012521
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012522}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012523
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012524static void hlua_deinit()
12525{
Willy Tarreau186f3762020-12-04 11:48:12 +010012526 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012527 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12528
12529 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12530 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012531
12532 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12533 if (hlua_states[thr])
12534 lua_close(hlua_states[thr]);
12535 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012536
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012537 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012538
Willy Tarreau0f143af2021-03-05 10:41:48 +010012539#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012540 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012541#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012542
12543 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012544}
12545
12546REGISTER_POST_DEINIT(hlua_deinit);
12547
Willy Tarreau80713382018-11-26 10:19:54 +010012548static void hlua_register_build_options(void)
12549{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012550 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012551
Willy Tarreaubb57d942016-12-21 19:04:56 +010012552 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12553 hap_register_build_opts(ptr, 1);
12554}
Willy Tarreau80713382018-11-26 10:19:54 +010012555
12556INITCALL0(STG_REGISTER, hlua_register_build_options);