blob: af26aae03c7dc480e4a630d93eaeeec6ae608e30 [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;
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002922 struct stream *s;
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 */
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +01002948 appctx = appctx_new(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002949 if (!appctx) {
2950 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002951 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 Faulet9ec2f4d2022-03-23 15:15:29 +01002966 cs = cs_new_from_applet(appctx->endp, sess, &BUF_NULL);
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002967 if (!cs) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002968 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet2479e5f2022-01-19 14:50:11 +01002969 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970 }
2971
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002972 s = DISGUISE(cs_strm(cs));
Christopher Faulet2479e5f2022-01-19 14:50:11 +01002973
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002974 /* Initialise cross reference between stream and Lua socket object. */
2975 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002976
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002977 /* Configure "right" stream interface. this "si" is used to connect
2978 * and retrieve data from the server. The connection is initialized
2979 * with the "struct server".
2980 */
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002981 si_set_state(cs_si(s->csb), SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002982
2983 /* Force destination server. */
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002984 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2985 s->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002986
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002987 return 1;
2988
Willy Tarreaud420a972015-04-06 00:39:18 +02002989 out_fail_sess:
Christopher Faulet13a35e52021-12-20 15:34:16 +01002990 session_free(sess);
2991 out_fail_appctx:
Willy Tarreaud420a972015-04-06 00:39:18 +02002992 appctx_free(appctx);
2993 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002994 WILL_LJMP(lua_error(L));
2995 return 0;
2996}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002997
2998/*
2999 *
3000 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003001 * Class Channel
3002 *
3003 *
3004 */
3005
3006/* Returns the struct hlua_channel join to the class channel in the
3007 * stack entry "ud" or throws an argument error.
3008 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003009__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003010{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003011 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003012}
3013
Willy Tarreau47860ed2015-03-10 14:07:50 +01003014/* Pushes the channel onto the top of the stack. If the stask does not have a
3015 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003016 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003017static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003018{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003019 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003020 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003021 return 0;
3022
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003023 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003024 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003025 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003026
3027 /* Pop a class sesison metatable and affect it to the userdata. */
3028 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3029 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003030 return 1;
3031}
3032
Christopher Faulet9f55a502020-02-25 15:21:02 +01003033/* Helper function returning a filter attached to a channel at the position <ud>
3034 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003035 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003036 * initialized.
3037 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003038static 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 +01003039{
3040 struct filter *filter = NULL;
3041
3042 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3043 struct hlua_flt_ctx *flt_ctx;
3044
3045 filter = lua_touserdata (L, -1);
3046 flt_ctx = filter->ctx;
3047 if (hlua_filter_from_payload(filter)) {
3048 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3049 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3050 }
3051 }
3052
3053 lua_pop(L, 1);
3054 return filter;
3055}
3056
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003057/* Copies <len> bytes of data present in the channel's buffer, starting at the
3058* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003059* responsibility to ensure <len> and <offset> are valid. It always return the
3060* length of the built string. <len> may be 0, in this case, an empty string is
3061* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003062*/
3063static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003064{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003065 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003066 luaL_Buffer b;
3067
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003068 block1 = len;
3069 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3070 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3071 block2 = len - block1;
3072
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003073 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003074 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3075 if (block2)
3076 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003077 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003078 return len;
3079}
3080
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003081/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3082 * function returns -1 if data cannot be copied. Otherwise, it returns the
3083 * number of bytes copied.
3084 */
3085static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3086{
3087 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003088
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003089 /* Nothing to do, just return */
3090 if (unlikely(istlen(str) == 0))
3091 goto end;
3092
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003093 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003094 ret = -1;
3095 goto end;
3096 }
3097 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3098
3099 end:
3100 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003101}
3102
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003103/* Removes <len> bytes of data at the absolute position <offset>.
3104 */
3105static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3106{
3107 size_t end = offset + len;
3108
3109 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3110 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3111 b_data(&chn->buf) - end, -len);
3112 b_sub(&chn->buf, len);
3113}
3114
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003115/* Copies input data in the channel's buffer. It is possible to set a specific
3116 * offset (0 by default) and a length (all remaining input data starting for the
3117 * offset by default). If there is not enough input data and more data can be
3118 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003119 *
3120 * From an action, All input data are considered. For a filter, the offset and
3121 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003122 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003123__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003124{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003125 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003126 struct filter *filter;
3127 size_t input, output;
3128 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003129
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003130 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003131
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003132 output = co_data(chn);
3133 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003134
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003135 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3136 if (filter && !hlua_filter_from_payload(filter))
3137 WILL_LJMP(lua_error(L));
3138
3139 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003140 if (lua_gettop(L) > 1) {
3141 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3142 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003143 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003144 offset += output;
3145 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003146 lua_pushfstring(L, "offset out of range.");
3147 WILL_LJMP(lua_error(L));
3148 }
3149 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003150 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003151 if (lua_gettop(L) == 3) {
3152 len = MAY_LJMP(luaL_checkinteger(L, 3));
3153 if (!len)
3154 goto dup;
3155 if (len == -1)
3156 len = global.tune.bufsize;
3157 if (len < 0) {
3158 lua_pushfstring(L, "length out of range.");
3159 WILL_LJMP(lua_error(L));
3160 }
3161 }
3162
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003163 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003164 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3165 /* Yield waiting for more data, as requested */
3166 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3167 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003168 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003169 }
3170
3171 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003172 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003173 return 1;
3174}
3175
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003176/* Copies the first line (including the trailing LF) of input data in the
3177 * channel's buffer. It is possible to set a specific offset (0 by default) and
3178 * a length (all remaining input data starting for the offset by default). If
3179 * there is not enough input data and more data can be received, the function
3180 * yields. If a length is explicitly specified, no more data are
3181 * copied. Otherwise, if no LF is found and more data can be received, this
3182 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003183 *
3184 * From an action, All input data are considered. For a filter, the offset and
3185 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003186 */
3187__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003188{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003189 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003190 struct filter *filter;
3191 size_t l, input, output;
3192 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003193
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003194 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003195 output = co_data(chn);
3196 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003197
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003198 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3199 if (filter && !hlua_filter_from_payload(filter))
3200 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003201
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003202 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003203 if (lua_gettop(L) > 1) {
3204 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3205 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003206 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003207 offset += output;
3208 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003209 lua_pushfstring(L, "offset out of range.");
3210 WILL_LJMP(lua_error(L));
3211 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003212 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003213
3214 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003215 if (lua_gettop(L) == 3) {
3216 len = MAY_LJMP(luaL_checkinteger(L, 3));
3217 if (!len)
3218 goto dup;
3219 if (len == -1)
3220 len = global.tune.bufsize;
3221 if (len < 0) {
3222 lua_pushfstring(L, "length out of range.");
3223 WILL_LJMP(lua_error(L));
3224 }
3225 }
3226
3227 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003228 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003229 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003230 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003231 len = l+1;
3232 goto dup;
3233 }
3234 }
3235
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003236 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003237 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3238 /* Yield waiting for more data */
3239 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3240 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003241 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003242 }
3243
3244 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003245 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003246 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003247}
3248
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003249/* [ DEPRECATED ]
3250 *
3251 * Duplicate all input data foud in the channel's buffer. The data are not
3252 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003253 *
3254 * From an action, All input data are considered. For a filter, the offset and
3255 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003256 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003257__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003258{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003259 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003260 struct filter *filter;
3261 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003262
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003263 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003264 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003265 if (IS_HTX_STRM(chn_strm(chn))) {
3266 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3267 WILL_LJMP(lua_error(L));
3268 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003269
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003270 offset = co_data(chn);
3271 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003272
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003273 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3274 if (filter && !hlua_filter_from_payload(filter))
3275 WILL_LJMP(lua_error(L));
3276
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003277 if (!ci_data(chn) && channel_input_closed(chn)) {
3278 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003279 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003280 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003281
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003282 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003283 return 1;
3284}
3285
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003286/* [ DEPRECATED ]
3287 *
3288 * Get all input data foud in the channel's buffer. The data are removed from
3289 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3290 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003291 *
3292 * From an action, All input data are considered. For a filter, the offset and
3293 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003294 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003295__LJMP static int hlua_channel_get(lua_State *L)
3296{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003297 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003298 struct filter *filter;
3299 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003300 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003301
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003302 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003303 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3304 if (IS_HTX_STRM(chn_strm(chn))) {
3305 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3306 WILL_LJMP(lua_error(L));
3307 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003308
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003309 offset = co_data(chn);
3310 len = ci_data(chn);
3311
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003312 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3313 if (filter && !hlua_filter_from_payload(filter))
3314 WILL_LJMP(lua_error(L));
3315
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003316 if (!ci_data(chn) && channel_input_closed(chn)) {
3317 lua_pushnil(L);
3318 return 1;
3319 }
3320
3321 ret = _hlua_channel_dup(chn, L, offset, len);
3322 _hlua_channel_delete(chn, offset, ret);
3323 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003324}
3325
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003326/* This functions consumes and returns one line. If the channel is closed,
3327 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003328 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003329 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003330 *
3331 * From an action, All input data are considered. For a filter, the offset and
3332 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003333 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003334__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003335{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003336 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003337 struct filter *filter;
3338 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003339 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003340
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003341 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003342
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003343 offset = co_data(chn);
3344 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003345
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003346 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3347 if (filter && !hlua_filter_from_payload(filter))
3348 WILL_LJMP(lua_error(L));
3349
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003350 if (!ci_data(chn) && channel_input_closed(chn)) {
3351 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003352 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003353 }
3354
3355 for (l = 0; l < len; l++) {
3356 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3357 len = l+1;
3358 goto dup;
3359 }
3360 }
3361
3362 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3363 /* Yield waiting for more data */
3364 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3365 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003366
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003367 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003368 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003369 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003370 return 1;
3371}
3372
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003373/* [ DEPRECATED ]
3374 *
3375 * Check arguments for the function "hlua_channel_getline_yield".
3376 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003377__LJMP static int hlua_channel_getline(lua_State *L)
3378{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003379 struct channel *chn;
3380
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003381 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003382 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3383 if (IS_HTX_STRM(chn_strm(chn))) {
3384 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3385 WILL_LJMP(lua_error(L));
3386 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003387 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3388}
3389
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003390/* Retrieves a given amount of input data at the given offset. By default all
3391 * available input data are returned. The offset may be negactive to start from
3392 * the end of input data. The length may be -1 to set it to the maximum buffer
3393 * size.
3394 */
3395__LJMP static int hlua_channel_get_data(lua_State *L)
3396{
3397 struct channel *chn;
3398
3399 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3400 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3401 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3402 if (IS_HTX_STRM(chn_strm(chn))) {
3403 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3404 WILL_LJMP(lua_error(L));
3405 }
3406 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3407}
3408
3409/* Retrieves a given amount of input data at the given offset. By default all
3410 * available input data are returned. The offset may be negactive to start from
3411 * the end of input data. The length may be -1 to set it to the maximum buffer
3412 * size.
3413 */
3414__LJMP static int hlua_channel_get_line(lua_State *L)
3415{
3416 struct channel *chn;
3417
3418 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3419 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3420 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3421 if (IS_HTX_STRM(chn_strm(chn))) {
3422 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3423 WILL_LJMP(lua_error(L));
3424 }
3425 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3426}
3427
3428/* Appends a string into the input side of channel. It returns the length of the
3429 * written string, or -1 if the channel is closed or if the buffer size is too
3430 * little for the data. 0 may be returned if nothing is copied. This function
3431 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003432 *
3433 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003434 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003435__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003436{
Christopher Faulet23976d92021-08-06 09:59:49 +02003437 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003438 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003439 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003440 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003441 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003442
3443 MAY_LJMP(check_args(L, 2, "append"));
3444 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003445 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003446 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003447 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003448 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003449 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003450
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003451 offset = co_data(chn);
3452 len = ci_data(chn);
3453
3454 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3455 if (filter && !hlua_filter_from_payload(filter))
3456 WILL_LJMP(lua_error(L));
3457
3458 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3459 if (ret > 0 && filter) {
3460 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3461
3462 flt_update_offsets(filter, chn, ret);
3463 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3464 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003465 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003466 return 1;
3467}
3468
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003469/* Prepends a string into the input side of channel. It returns the length of the
3470 * written string, or -1 if the channel is closed or if the buffer size is too
3471 * little for the data. 0 may be returned if nothing is copied. This function
3472 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003473 *
3474 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003475 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003476__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003477{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003478 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003479 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003480 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003481 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003482 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003483
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003484 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003485 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003486 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3487 if (IS_HTX_STRM(chn_strm(chn))) {
3488 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3489 WILL_LJMP(lua_error(L));
3490 }
3491
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003492 offset = co_data(chn);
3493 len = ci_data(chn);
3494
3495 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3496 if (filter && !hlua_filter_from_payload(filter))
3497 WILL_LJMP(lua_error(L));
3498
3499 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3500 if (ret > 0 && filter) {
3501 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3502
3503 flt_update_offsets(filter, chn, ret);
3504 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3505 }
3506
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003507 lua_pushinteger(L, ret);
3508 return 1;
3509}
3510
3511/* Inserts a given amount of input data at the given offset by a string
3512 * content. By default the string is appended at the end of input data. It
3513 * returns the length of the written string, or -1 if the channel is closed or
3514 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003515 *
3516 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003517 */
3518__LJMP static int hlua_channel_insert_data(lua_State *L)
3519{
3520 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003521 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003522 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003523 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003524 int ret, offset;
3525
3526 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3527 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3528 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3529 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003530
3531 output = co_data(chn);
3532 input = ci_data(chn);
3533
3534 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3535 if (filter && !hlua_filter_from_payload(filter))
3536 WILL_LJMP(lua_error(L));
3537
3538 offset = input + output;
3539 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003540 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003541 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003542 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003543 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003544 if (offset < output || offset > output + input) {
3545 lua_pushfstring(L, "offset out of range.");
3546 WILL_LJMP(lua_error(L));
3547 }
3548 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003549 if (IS_HTX_STRM(chn_strm(chn))) {
3550 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3551 WILL_LJMP(lua_error(L));
3552 }
3553
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003554 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3555 if (ret > 0 && filter) {
3556 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003557
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003558 flt_update_offsets(filter, chn, ret);
3559 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003560 }
3561
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003562 lua_pushinteger(L, ret);
3563 return 1;
3564}
3565/* Replaces a given amount of input data at the given offset by a string
3566 * content. By default all remaining data are removed (offset = 0 and len =
3567 * -1). It returns the length of the written string, or -1 if the channel is
3568 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003569 *
3570 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003571 */
3572__LJMP static int hlua_channel_set_data(lua_State *L)
3573{
3574 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003575 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003576 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003577 size_t sz, input, output;
3578 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003579
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003580 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3581 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3582 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3583 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003584
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003585 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003586 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003587 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003588 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003589
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003590 output = co_data(chn);
3591 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003592
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003593 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3594 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003595 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003596
3597 offset = output;
3598 if (lua_gettop(L) > 2) {
3599 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3600 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003601 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003602 offset += output;
3603 if (offset < output || offset > input + output) {
3604 lua_pushfstring(L, "offset out of range.");
3605 WILL_LJMP(lua_error(L));
3606 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003607 }
3608
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003609 len = output + input - offset;
3610 if (lua_gettop(L) == 4) {
3611 len = MAY_LJMP(luaL_checkinteger(L, 4));
3612 if (!len)
3613 goto set;
3614 if (len == -1)
3615 len = output + input - offset;
3616 if (len < 0 || offset + len > output + input) {
3617 lua_pushfstring(L, "length out of range.");
3618 WILL_LJMP(lua_error(L));
3619 }
3620 }
3621
3622 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003623 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003624 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003625 lua_pushinteger(L, -1);
3626 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003627 _hlua_channel_delete(chn, offset, len);
3628 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3629 if (filter) {
3630 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3631
3632 len -= (ret > 0 ? ret : 0);
3633 flt_update_offsets(filter, chn, -len);
3634 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3635 }
3636
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003637 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003638 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003639 return 1;
3640}
3641
3642/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003643 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003644 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003645 *
3646 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003647 */
3648__LJMP static int hlua_channel_del_data(lua_State *L)
3649{
3650 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003651 struct filter *filter;
3652 size_t input, output;
3653 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003654
3655 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3656 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3657 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003658
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003659 if (IS_HTX_STRM(chn_strm(chn))) {
3660 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3661 WILL_LJMP(lua_error(L));
3662 }
3663
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003664 output = co_data(chn);
3665 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003666
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003667 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3668 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003669 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003670
3671 offset = output;
3672 if (lua_gettop(L) > 2) {
3673 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3674 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003675 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003676 offset += output;
3677 if (offset < output || offset > input + output) {
3678 lua_pushfstring(L, "offset out of range.");
3679 WILL_LJMP(lua_error(L));
3680 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003681 }
3682
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003683 len = output + input - offset;
3684 if (lua_gettop(L) == 4) {
3685 len = MAY_LJMP(luaL_checkinteger(L, 4));
3686 if (!len)
3687 goto end;
3688 if (len == -1)
3689 len = output + input - offset;
3690 if (len < 0 || offset + len > output + input) {
3691 lua_pushfstring(L, "length out of range.");
3692 WILL_LJMP(lua_error(L));
3693 }
3694 }
3695
3696 _hlua_channel_delete(chn, offset, len);
3697 if (filter) {
3698 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3699
3700 flt_update_offsets(filter, chn, -len);
3701 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3702 }
3703
3704 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003705 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003706 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003707}
3708
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003709/* Append data in the output side of the buffer. This data is immediately
3710 * sent. The function returns the amount of data written. If the buffer
3711 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003712 * if the channel is closed.
3713 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003714__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003715{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003716 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003717 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003718 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003719 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003720 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003721 struct hlua *hlua;
3722
3723 /* Get hlua struct, or NULL if we execute from main lua state */
3724 hlua = hlua_gethlua(L);
3725 if (!hlua) {
3726 lua_pushnil(L);
3727 return 1;
3728 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003729
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003730 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3731 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3732 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003733
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003734 offset = co_data(chn);
3735 len = ci_data(chn);
3736
3737 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3738 if (filter && !hlua_filter_from_payload(filter))
3739 WILL_LJMP(lua_error(L));
3740
3741
Willy Tarreau47860ed2015-03-10 14:07:50 +01003742 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003743 lua_pushinteger(L, -1);
3744 return 1;
3745 }
3746
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003747 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003748 if (len > sz -l) {
3749 if (filter) {
3750 lua_pushinteger(L, -1);
3751 return 1;
3752 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003753 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003754 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003755
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003756 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003757 if (ret == -1) {
3758 lua_pop(L, 1);
3759 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003760 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003761 }
3762 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003763 if (filter) {
3764 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3765
3766
3767 flt_update_offsets(filter, chn, ret);
3768 FLT_OFF(filter, chn) += ret;
3769 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3770 }
3771 else
3772 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003773
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003774 l += ret;
3775 lua_pop(L, 1);
3776 lua_pushinteger(L, l);
3777 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003778
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003779 if (l < sz) {
3780 /* Yield only if the channel's output is not empty.
3781 * Otherwise it means we cannot add more data. */
3782 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003783 return 1;
3784
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003785 /* If we are waiting for space in the response buffer, we
3786 * must set the flag WAKERESWR. This flag required the task
3787 * wake up if any activity is detected on the response buffer.
3788 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003789 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003790 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003791 else
3792 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003793 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003794 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003795
3796 return 1;
3797}
3798
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003799/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003800 * yield the LUA process, and resume it without checking the
3801 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003802 *
3803 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003804 */
3805__LJMP static int hlua_channel_send(lua_State *L)
3806{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003807 struct channel *chn;
3808
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003809 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003810 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3811 if (IS_HTX_STRM(chn_strm(chn))) {
3812 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3813 WILL_LJMP(lua_error(L));
3814 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003815 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003816 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003817}
3818
3819/* This function forward and amount of butes. The data pass from
3820 * the input side of the buffer to the output side, and can be
3821 * forwarded. This function never fails.
3822 *
3823 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003824 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003825 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003826__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003827{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003828 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003829 struct filter *filter;
3830 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003831 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003832 struct hlua *hlua;
3833
3834 /* Get hlua struct, or NULL if we execute from main lua state */
3835 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003836 if (!hlua) {
3837 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003838 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003839 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003840
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003841 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003842 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003843 l = MAY_LJMP(luaL_checkinteger(L, -1));
3844
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003845 offset = co_data(chn);
3846 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003847
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003848 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3849 if (filter && !hlua_filter_from_payload(filter))
3850 WILL_LJMP(lua_error(L));
3851
3852 max = fwd - l;
3853 if (max > len)
3854 max = len;
3855
3856 if (filter) {
3857 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3858
3859 FLT_OFF(filter, chn) += max;
3860 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3861 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3862 }
3863 else
3864 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003865
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003866 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003867 lua_pop(L, 1);
3868 lua_pushinteger(L, l);
3869
3870 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003871 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003872 /* The the input channel or the output channel are closed, we
3873 * must return the amount of data forwarded.
3874 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003875 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003876 return 1;
3877
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003878 /* If we are waiting for space data in the response buffer, we
3879 * must set the flag WAKERESWR. This flag required the task
3880 * wake up if any activity is detected on the response buffer.
3881 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003882 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003883 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003884 else
3885 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003886
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003887 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003888 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003889 }
3890
3891 return 1;
3892}
3893
3894/* Just check the input and prepare the stack for the previous
3895 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003896 *
3897 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003898 */
3899__LJMP static int hlua_channel_forward(lua_State *L)
3900{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003901 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003902
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003903 MAY_LJMP(check_args(L, 2, "forward"));
3904 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3905 if (IS_HTX_STRM(chn_strm(chn))) {
3906 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3907 WILL_LJMP(lua_error(L));
3908 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003909 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003910 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003911}
3912
3913/* Just returns the number of bytes available in the input
3914 * side of the buffer. This function never fails.
3915 */
3916__LJMP static int hlua_channel_get_in_len(lua_State *L)
3917{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003918 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003919 struct filter *filter;
3920 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003921
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003922 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003923 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003924
3925 output = co_data(chn);
3926 input = ci_data(chn);
3927 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3928 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3929 lua_pushinteger(L, input);
3930 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003931 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003932
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003933 lua_pushinteger(L, htx->data - co_data(chn));
3934 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003935 return 1;
3936}
3937
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003938/* Returns true if the channel is full. */
3939__LJMP static int hlua_channel_is_full(lua_State *L)
3940{
3941 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003942
3943 MAY_LJMP(check_args(L, 1, "is_full"));
3944 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003945 /* ignore the reserve, we are not on a producer side (ie in an
3946 * applet).
3947 */
3948 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003949 return 1;
3950}
3951
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003952/* Returns true if the channel may still receive data. */
3953__LJMP static int hlua_channel_may_recv(lua_State *L)
3954{
3955 struct channel *chn;
3956
3957 MAY_LJMP(check_args(L, 1, "may_recv"));
3958 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3959 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3960 return 1;
3961}
3962
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003963/* Returns true if the channel is the response channel. */
3964__LJMP static int hlua_channel_is_resp(lua_State *L)
3965{
3966 struct channel *chn;
3967
3968 MAY_LJMP(check_args(L, 1, "is_resp"));
3969 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3970
3971 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3972 return 1;
3973}
3974
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003975/* Just returns the number of bytes available in the output
3976 * side of the buffer. This function never fails.
3977 */
3978__LJMP static int hlua_channel_get_out_len(lua_State *L)
3979{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003980 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003981 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003982
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003983 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003984 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003985
3986 output = co_data(chn);
3987 input = ci_data(chn);
3988 hlua_channel_filter(L, 1, chn, &output, &input);
3989
3990 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003991 return 1;
3992}
3993
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003994/*
3995 *
3996 *
3997 * Class Fetches
3998 *
3999 *
4000 */
4001
4002/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004003 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004004 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004005__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004006{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004007 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004008}
4009
4010/* This function creates and push in the stack a fetch object according
4011 * with a current TXN.
4012 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004013static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004014{
Willy Tarreau7073c472015-04-06 11:15:40 +02004015 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004016
4017 /* Check stack size. */
4018 if (!lua_checkstack(L, 3))
4019 return 0;
4020
4021 /* Create the object: obj[0] = userdata.
4022 * Note that the base of the Fetches object is the
4023 * transaction object.
4024 */
4025 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004026 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004027 lua_rawseti(L, -2, 0);
4028
Willy Tarreau7073c472015-04-06 11:15:40 +02004029 hsmp->s = txn->s;
4030 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004031 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004032 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004033
4034 /* Pop a class sesison metatable and affect it to the userdata. */
4035 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4036 lua_setmetatable(L, -2);
4037
4038 return 1;
4039}
4040
4041/* This function is an LUA binding. It is called with each sample-fetch.
4042 * It uses closure argument to store the associated sample-fetch. It
4043 * returns only one argument or throws an error. An error is thrown
4044 * only if an error is encountered during the argument parsing. If
4045 * the "sample-fetch" function fails, nil is returned.
4046 */
4047__LJMP static int hlua_run_sample_fetch(lua_State *L)
4048{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004049 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004050 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004051 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004052 int i;
4053 struct sample smp;
4054
4055 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004056 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004057
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004058 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004059 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004060
Thierry FOURNIERca988662015-12-20 18:43:03 +01004061 /* Check execution authorization. */
4062 if (f->use & SMP_USE_HTTP_ANY &&
4063 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4064 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4065 "is not available in Lua services", f->kw);
4066 WILL_LJMP(lua_error(L));
4067 }
4068
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004069 /* Get extra arguments. */
4070 for (i = 0; i < lua_gettop(L) - 1; i++) {
4071 if (i >= ARGM_NBARGS)
4072 break;
4073 hlua_lua2arg(L, i + 2, &args[i]);
4074 }
4075 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004076 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004077
4078 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004079 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004080
4081 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004082 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004083 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004084 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004085 }
4086
4087 /* Initialise the sample. */
4088 memset(&smp, 0, sizeof(smp));
4089
4090 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004091 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004092 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004093 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004094 lua_pushstring(L, "");
4095 else
4096 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004097 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004098 }
4099
4100 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004101 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004102 hlua_smp2lua_str(L, &smp);
4103 else
4104 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004105
4106 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004107 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004108 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004109
4110 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004111 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004112 WILL_LJMP(lua_error(L));
4113 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004114}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004115
4116/*
4117 *
4118 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004119 * Class Converters
4120 *
4121 *
4122 */
4123
4124/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004125 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004126 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004127__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004128{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004129 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004130}
4131
4132/* This function creates and push in the stack a Converters object
4133 * according with a current TXN.
4134 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004135static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004136{
Willy Tarreau7073c472015-04-06 11:15:40 +02004137 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004138
4139 /* Check stack size. */
4140 if (!lua_checkstack(L, 3))
4141 return 0;
4142
4143 /* Create the object: obj[0] = userdata.
4144 * Note that the base of the Converters object is the
4145 * same than the TXN object.
4146 */
4147 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004148 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004149 lua_rawseti(L, -2, 0);
4150
Willy Tarreau7073c472015-04-06 11:15:40 +02004151 hsmp->s = txn->s;
4152 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004153 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004154 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004155
Willy Tarreau87b09662015-04-03 00:22:06 +02004156 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004157 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4158 lua_setmetatable(L, -2);
4159
4160 return 1;
4161}
4162
4163/* This function is an LUA binding. It is called with each converter.
4164 * It uses closure argument to store the associated converter. It
4165 * returns only one argument or throws an error. An error is thrown
4166 * only if an error is encountered during the argument parsing. If
4167 * the converter function function fails, nil is returned.
4168 */
4169__LJMP static int hlua_run_sample_conv(lua_State *L)
4170{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004171 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004172 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004173 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004174 int i;
4175 struct sample smp;
4176
4177 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004178 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004179
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004180 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004181 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004182
4183 /* Get extra arguments. */
4184 for (i = 0; i < lua_gettop(L) - 2; i++) {
4185 if (i >= ARGM_NBARGS)
4186 break;
4187 hlua_lua2arg(L, i + 3, &args[i]);
4188 }
4189 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004190 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004191
4192 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004193 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004194
4195 /* Run the special args checker. */
4196 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4197 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004198 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004199 }
4200
4201 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004202 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004203 if (!hlua_lua2smp(L, 2, &smp)) {
4204 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004205 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004206 }
4207
Willy Tarreau1777ea62016-03-10 16:15:46 +01004208 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4209
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004211 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004212 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004213 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004214 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004215 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004216 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4217 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004218 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004219 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004220 }
4221
4222 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004223 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004224 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004225 lua_pushstring(L, "");
4226 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004227 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004228 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004229 }
4230
4231 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004232 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004233 hlua_smp2lua_str(L, &smp);
4234 else
4235 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004236 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004237 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004238 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004239
4240 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004241 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004242 WILL_LJMP(lua_error(L));
4243 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004244}
4245
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004246/*
4247 *
4248 *
4249 * Class AppletTCP
4250 *
4251 *
4252 */
4253
4254/* Returns a struct hlua_txn if the stack entry "ud" is
4255 * a class stream, otherwise it throws an error.
4256 */
4257__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4258{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004259 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004260}
4261
4262/* This function creates and push in the stack an Applet object
4263 * according with a current TXN.
4264 */
4265static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4266{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004267 struct hlua_appctx *luactx;
Christopher Faulet86e1c332021-12-20 17:09:39 +01004268 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004269 struct stream *s = si_strm(si);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004270 struct proxy *p;
4271
4272 ALREADY_CHECKED(s);
4273 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004274
4275 /* Check stack size. */
4276 if (!lua_checkstack(L, 3))
4277 return 0;
4278
4279 /* Create the object: obj[0] = userdata.
4280 * Note that the base of the Converters object is the
4281 * same than the TXN object.
4282 */
4283 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004284 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004285 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004286 luactx->appctx = ctx;
4287 luactx->htxn.s = s;
4288 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004289
4290 /* Create the "f" field that contains a list of fetches. */
4291 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004292 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004293 return 0;
4294 lua_settable(L, -3);
4295
4296 /* Create the "sf" field that contains a list of stringsafe fetches. */
4297 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004298 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004299 return 0;
4300 lua_settable(L, -3);
4301
4302 /* Create the "c" field that contains a list of converters. */
4303 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004304 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004305 return 0;
4306 lua_settable(L, -3);
4307
4308 /* Create the "sc" field that contains a list of stringsafe converters. */
4309 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004310 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004311 return 0;
4312 lua_settable(L, -3);
4313
4314 /* Pop a class stream metatable and affect it to the table. */
4315 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4316 lua_setmetatable(L, -2);
4317
4318 return 1;
4319}
4320
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004321__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4322{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004323 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004324 struct stream *s;
4325 const char *name;
4326 size_t len;
4327 struct sample smp;
4328
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004329 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4330 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004331
4332 /* It is useles to retrieve the stream, but this function
4333 * runs only in a stream context.
4334 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004335 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004336 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004337 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004338
4339 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004340 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004341 hlua_lua2smp(L, 3, &smp);
4342
4343 /* Store the sample in a variable. */
4344 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004345
4346 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4347 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4348 else
4349 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4350
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004351 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004352}
4353
4354__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4355{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004356 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004357 struct stream *s;
4358 const char *name;
4359 size_t len;
4360 struct sample smp;
4361
4362 MAY_LJMP(check_args(L, 2, "unset_var"));
4363
4364 /* It is useles to retrieve the stream, but this function
4365 * runs only in a stream context.
4366 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004367 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004368 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004369 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004370
4371 /* Unset the variable. */
4372 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004373 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4374 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004375}
4376
4377__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4378{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004379 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004380 struct stream *s;
4381 const char *name;
4382 size_t len;
4383 struct sample smp;
4384
4385 MAY_LJMP(check_args(L, 2, "get_var"));
4386
4387 /* It is useles to retrieve the stream, but this function
4388 * runs only in a stream context.
4389 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004390 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004391 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004392 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004393
4394 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004395 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004396 lua_pushnil(L);
4397 return 1;
4398 }
4399
4400 return hlua_smp2lua(L, &smp);
4401}
4402
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004403__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4404{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004405 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4406 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004407 struct hlua *hlua;
4408
4409 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004410 if (!s->hlua)
4411 return 0;
4412 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004413
4414 MAY_LJMP(check_args(L, 2, "set_priv"));
4415
4416 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004417 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004418
4419 /* Get and store new value. */
4420 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4421 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4422
4423 return 0;
4424}
4425
4426__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4427{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004428 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4429 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004430 struct hlua *hlua;
4431
4432 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004433 if (!s->hlua) {
4434 lua_pushnil(L);
4435 return 1;
4436 }
4437 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004438
4439 /* Push configuration index in the stack. */
4440 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4441
4442 return 1;
4443}
4444
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004445/* If expected data not yet available, it returns a yield. This function
4446 * consumes the data in the buffer. It returns a string containing the
4447 * data. This string can be empty.
4448 */
4449__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4450{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004451 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004452 struct stream_interface *si = cs_si(luactx->appctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004453 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004454 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004455 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004456 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004457 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004458
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004459 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004460 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004461
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004462 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004463 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004464 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004465 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004466 }
4467
4468 /* End of data: commit the total strings and return. */
4469 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004470 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004471 return 1;
4472 }
4473
4474 /* Ensure that the block 2 length is usable. */
4475 if (ret == 1)
4476 len2 = 0;
4477
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004478 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004479 luaL_addlstring(&luactx->b, blk1, len1);
4480 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004481
4482 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004483 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004484 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004485 return 1;
4486}
4487
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004488/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004489__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4490{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004491 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004492
4493 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004494 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004495
4496 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4497}
4498
4499/* If expected data not yet available, it returns a yield. This function
4500 * consumes the data in the buffer. It returns a string containing the
4501 * data. This string can be empty.
4502 */
4503__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4504{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004505 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004506 struct stream_interface *si = cs_si(luactx->appctx->owner);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004507 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004508 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004509 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004510 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004511 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004512 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004513
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004514 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004515 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004516
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004517 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004518 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004519 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004520 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004521 }
4522
4523 /* End of data: commit the total strings and return. */
4524 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004525 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004526 return 1;
4527 }
4528
4529 /* Ensure that the block 2 length is usable. */
4530 if (ret == 1)
4531 len2 = 0;
4532
4533 if (len == -1) {
4534
4535 /* If len == -1, catenate all the data avalaile and
4536 * yield because we want to get all the data until
4537 * the end of data stream.
4538 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004539 luaL_addlstring(&luactx->b, blk1, len1);
4540 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004541 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004542 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004543 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004544
4545 } else {
4546
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004547 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004548 if (len1 > len)
4549 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004550 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004551 len -= len1;
4552
4553 /* Copy the second block. */
4554 if (len2 > len)
4555 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004556 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004557 len -= len2;
4558
4559 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004560 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004561
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004562 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004563 if (len > 0) {
4564 lua_pushinteger(L, len);
4565 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004566 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004567 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004568 }
4569
4570 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004571 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004572 return 1;
4573 }
4574
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004575 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004576 hlua_pusherror(L, "Lua: internal error");
4577 WILL_LJMP(lua_error(L));
4578 return 0;
4579}
4580
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004581/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004582__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4583{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004584 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004585 int len = -1;
4586
4587 if (lua_gettop(L) > 2)
4588 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4589 if (lua_gettop(L) >= 2) {
4590 len = MAY_LJMP(luaL_checkinteger(L, 2));
4591 lua_pop(L, 1);
4592 }
4593
4594 /* Confirm or set the required length */
4595 lua_pushinteger(L, len);
4596
4597 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004598 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004599
4600 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4601}
4602
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004603/* Append data in the output side of the buffer. This data is immediately
4604 * sent. The function returns the amount of data written. If the buffer
4605 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004606 * if the channel is closed.
4607 */
4608__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4609{
4610 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004611 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004612 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4613 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004614 struct stream_interface *si = cs_si(luactx->appctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004615 struct channel *chn = si_ic(si);
4616 int max;
4617
4618 /* Get the max amount of data which can write as input in the channel. */
4619 max = channel_recv_max(chn);
4620 if (max > (len - l))
4621 max = len - l;
4622
4623 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004624 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004625
4626 /* update counters. */
4627 l += max;
4628 lua_pop(L, 1);
4629 lua_pushinteger(L, l);
4630
4631 /* If some data is not send, declares the situation to the
4632 * applet, and returns a yield.
4633 */
4634 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004635 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004636 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004637 }
4638
4639 return 1;
4640}
4641
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004642/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004643 * yield the LUA process, and resume it without checking the
4644 * input arguments.
4645 */
4646__LJMP static int hlua_applet_tcp_send(lua_State *L)
4647{
4648 MAY_LJMP(check_args(L, 2, "send"));
4649 lua_pushinteger(L, 0);
4650
4651 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4652}
4653
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004654/*
4655 *
4656 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004657 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004658 *
4659 *
4660 */
4661
4662/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004663 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004664 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004665__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004666{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004667 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004668}
4669
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004670/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004671 * according with a current TXN.
4672 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004673static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004674{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004675 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004676 struct hlua_txn htxn;
Christopher Faulet86e1c332021-12-20 17:09:39 +01004677 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004678 struct stream *s = si_strm(si);
4679 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004680 struct htx *htx;
4681 struct htx_blk *blk;
4682 struct htx_sl *sl;
4683 struct ist path;
4684 unsigned long long len = 0;
4685 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004686 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004687
4688 /* Check stack size. */
4689 if (!lua_checkstack(L, 3))
4690 return 0;
4691
4692 /* Create the object: obj[0] = userdata.
4693 * Note that the base of the Converters object is the
4694 * same than the TXN object.
4695 */
4696 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004697 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004698 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004699 luactx->appctx = ctx;
4700 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4701 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4702 luactx->htxn.s = s;
4703 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004704
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004705 /* Create the "f" field that contains a list of fetches. */
4706 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004707 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004708 return 0;
4709 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004710
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004711 /* Create the "sf" field that contains a list of stringsafe fetches. */
4712 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004713 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004714 return 0;
4715 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004716
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004717 /* Create the "c" field that contains a list of converters. */
4718 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004719 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004720 return 0;
4721 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004722
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004723 /* Create the "sc" field that contains a list of stringsafe converters. */
4724 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004725 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004726 return 0;
4727 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004728
Christopher Fauleta2097962019-07-15 16:25:33 +02004729 htx = htxbuf(&s->req.buf);
4730 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004731 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004732 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004733
Christopher Fauleta2097962019-07-15 16:25:33 +02004734 /* Stores the request method. */
4735 lua_pushstring(L, "method");
4736 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4737 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004738
Christopher Fauleta2097962019-07-15 16:25:33 +02004739 /* Stores the http version. */
4740 lua_pushstring(L, "version");
4741 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4742 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004743
Christopher Fauleta2097962019-07-15 16:25:33 +02004744 /* creates an array of headers. hlua_http_get_headers() crates and push
4745 * the array on the top of the stack.
4746 */
4747 lua_pushstring(L, "headers");
4748 htxn.s = s;
4749 htxn.p = px;
4750 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004751 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004752 return 0;
4753 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004754
Amaury Denoyellec453f952021-07-06 11:40:12 +02004755 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4756 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004757 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004758 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004759
Christopher Fauleta2097962019-07-15 16:25:33 +02004760 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004761 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004762 q = p;
4763 while (q < end && *q != '?')
4764 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004765
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004766 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004767 lua_pushstring(L, "path");
4768 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004769 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004770
Christopher Fauleta2097962019-07-15 16:25:33 +02004771 /* Stores the query string. */
4772 lua_pushstring(L, "qs");
4773 if (*q == '?')
4774 q++;
4775 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004776 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004777 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004778
Christopher Fauleta2097962019-07-15 16:25:33 +02004779 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4780 struct htx_blk *blk = htx_get_blk(htx, pos);
4781 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004782
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004783 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004784 break;
4785 if (type == HTX_BLK_DATA)
4786 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004787 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004788 if (htx->extra != ULLONG_MAX)
4789 len += htx->extra;
4790
4791 /* Stores the request path. */
4792 lua_pushstring(L, "length");
4793 lua_pushinteger(L, len);
4794 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004795
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004796 /* Create an empty array of HTTP request headers. */
4797 lua_pushstring(L, "response");
4798 lua_newtable(L);
4799 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004800
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004801 /* Pop a class stream metatable and affect it to the table. */
4802 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4803 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004804
4805 return 1;
4806}
4807
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004808__LJMP static int hlua_applet_http_set_var(lua_State *L)
4809{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004810 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004811 struct stream *s;
4812 const char *name;
4813 size_t len;
4814 struct sample smp;
4815
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004816 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4817 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004818
4819 /* It is useles to retrieve the stream, but this function
4820 * runs only in a stream context.
4821 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004822 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004823 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004824 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004825
4826 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004827 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004828 hlua_lua2smp(L, 3, &smp);
4829
4830 /* Store the sample in a variable. */
4831 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004832
4833 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4834 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4835 else
4836 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4837
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004838 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004839}
4840
4841__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4842{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004843 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004844 struct stream *s;
4845 const char *name;
4846 size_t len;
4847 struct sample smp;
4848
4849 MAY_LJMP(check_args(L, 2, "unset_var"));
4850
4851 /* It is useles to retrieve the stream, but this function
4852 * runs only in a stream context.
4853 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004854 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004855 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004856 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004857
4858 /* Unset the variable. */
4859 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004860 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4861 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004862}
4863
4864__LJMP static int hlua_applet_http_get_var(lua_State *L)
4865{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004866 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004867 struct stream *s;
4868 const char *name;
4869 size_t len;
4870 struct sample smp;
4871
4872 MAY_LJMP(check_args(L, 2, "get_var"));
4873
4874 /* It is useles to retrieve the stream, but this function
4875 * runs only in a stream context.
4876 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004877 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004878 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004879 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004880
4881 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004882 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004883 lua_pushnil(L);
4884 return 1;
4885 }
4886
4887 return hlua_smp2lua(L, &smp);
4888}
4889
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004890__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4891{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004892 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4893 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004894 struct hlua *hlua;
4895
4896 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004897 if (!s->hlua)
4898 return 0;
4899 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004900
4901 MAY_LJMP(check_args(L, 2, "set_priv"));
4902
4903 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004904 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004905
4906 /* Get and store new value. */
4907 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4908 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4909
4910 return 0;
4911}
4912
4913__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4914{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004915 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4916 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004917 struct hlua *hlua;
4918
4919 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004920 if (!s->hlua) {
4921 lua_pushnil(L);
4922 return 1;
4923 }
4924 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004925
4926 /* Push configuration index in the stack. */
4927 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4928
4929 return 1;
4930}
4931
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004932/* If expected data not yet available, it returns a yield. This function
4933 * consumes the data in the buffer. It returns a string containing the
4934 * data. This string can be empty.
4935 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004936__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004937{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004938 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004939 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004940 struct channel *req = si_oc(si);
4941 struct htx *htx;
4942 struct htx_blk *blk;
4943 size_t count;
4944 int stop = 0;
4945
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004946 htx = htx_from_buf(&req->buf);
4947 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004948 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004949
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004950 while (count && !stop && blk) {
4951 enum htx_blk_type type = htx_get_blk_type(blk);
4952 uint32_t sz = htx_get_blksz(blk);
4953 struct ist v;
4954 uint32_t vlen;
4955 char *nl;
4956
4957 vlen = sz;
4958 if (vlen > count) {
4959 if (type != HTX_BLK_DATA)
4960 break;
4961 vlen = count;
4962 }
4963
4964 switch (type) {
4965 case HTX_BLK_UNUSED:
4966 break;
4967
4968 case HTX_BLK_DATA:
4969 v = htx_get_blk_value(htx, blk);
4970 v.len = vlen;
4971 nl = istchr(v, '\n');
4972 if (nl != NULL) {
4973 stop = 1;
4974 vlen = nl - v.ptr + 1;
4975 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004976 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004977 break;
4978
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004979 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004980 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004981 stop = 1;
4982 break;
4983
4984 default:
4985 break;
4986 }
4987
Willy Tarreau84240042022-02-28 16:51:23 +01004988 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004989 count -= vlen;
4990 if (sz == vlen)
4991 blk = htx_remove_blk(htx, blk);
4992 else {
4993 htx_cut_data_blk(htx, blk, vlen);
4994 break;
4995 }
4996 }
4997
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004998 /* The message was fully consumed and no more data are expected
4999 * (EOM flag set).
5000 */
5001 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5002 stop = 1;
5003
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005004 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005005 if (!stop) {
5006 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005007 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005008 }
5009
5010 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005011 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005012 return 1;
5013}
5014
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005015
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005016/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005017__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005018{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005019 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005020
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005021 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005022 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005023
Christopher Fauleta2097962019-07-15 16:25:33 +02005024 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005025}
5026
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005027/* If expected data not yet available, it returns a yield. This function
5028 * consumes the data in the buffer. It returns a string containing the
5029 * data. This string can be empty.
5030 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005031__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005032{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005033 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005034 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005035 struct channel *req = si_oc(si);
5036 struct htx *htx;
5037 struct htx_blk *blk;
5038 size_t count;
5039 int len;
5040
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005041 htx = htx_from_buf(&req->buf);
5042 len = MAY_LJMP(luaL_checkinteger(L, 2));
5043 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005044 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005045 while (count && len && blk) {
5046 enum htx_blk_type type = htx_get_blk_type(blk);
5047 uint32_t sz = htx_get_blksz(blk);
5048 struct ist v;
5049 uint32_t vlen;
5050
5051 vlen = sz;
5052 if (len > 0 && vlen > len)
5053 vlen = len;
5054 if (vlen > count) {
5055 if (type != HTX_BLK_DATA)
5056 break;
5057 vlen = count;
5058 }
5059
5060 switch (type) {
5061 case HTX_BLK_UNUSED:
5062 break;
5063
5064 case HTX_BLK_DATA:
5065 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005066 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005067 break;
5068
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005069 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005070 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005071 len = 0;
5072 break;
5073
5074 default:
5075 break;
5076 }
5077
Willy Tarreau84240042022-02-28 16:51:23 +01005078 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005079 count -= vlen;
5080 if (len > 0)
5081 len -= vlen;
5082 if (sz == vlen)
5083 blk = htx_remove_blk(htx, blk);
5084 else {
5085 htx_cut_data_blk(htx, blk, vlen);
5086 break;
5087 }
5088 }
5089
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005090 /* The message was fully consumed and no more data are expected
5091 * (EOM flag set).
5092 */
5093 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5094 len = 0;
5095
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005096 htx_to_buf(htx, &req->buf);
5097
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005098 /* If we are no other data available, yield waiting for new data. */
5099 if (len) {
5100 if (len > 0) {
5101 lua_pushinteger(L, len);
5102 lua_replace(L, 2);
5103 }
5104 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005105 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005106 }
5107
5108 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005109 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005110 return 1;
5111}
5112
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005113/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005114__LJMP static int hlua_applet_http_recv(lua_State *L)
5115{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005116 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005117 int len = -1;
5118
5119 /* Check arguments. */
5120 if (lua_gettop(L) > 2)
5121 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5122 if (lua_gettop(L) >= 2) {
5123 len = MAY_LJMP(luaL_checkinteger(L, 2));
5124 lua_pop(L, 1);
5125 }
5126
Christopher Fauleta2097962019-07-15 16:25:33 +02005127 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005128
Christopher Fauleta2097962019-07-15 16:25:33 +02005129 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005130 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005131
Christopher Fauleta2097962019-07-15 16:25:33 +02005132 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005133}
5134
5135/* Append data in the output side of the buffer. This data is immediately
5136 * sent. The function returns the amount of data written. If the buffer
5137 * cannot contain the data, the function yields. The function returns -1
5138 * if the channel is closed.
5139 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005140__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005141{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005142 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005143 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005144 struct channel *res = si_ic(si);
5145 struct htx *htx = htx_from_buf(&res->buf);
5146 const char *data;
5147 size_t len;
5148 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5149 int max;
5150
Christopher Faulet9060fc02019-07-03 11:39:30 +02005151 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005152 if (!max)
5153 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005154
5155 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5156
5157 /* Get the max amount of data which can write as input in the channel. */
5158 if (max > (len - l))
5159 max = len - l;
5160
5161 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005162 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005163 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005164
5165 /* update counters. */
5166 l += max;
5167 lua_pop(L, 1);
5168 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005169
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005170 /* If some data is not send, declares the situation to the
5171 * applet, and returns a yield.
5172 */
5173 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005174 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005175 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005176 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005177 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005178 }
5179
Christopher Fauleta2097962019-07-15 16:25:33 +02005180 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005181 return 1;
5182}
5183
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005184/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005185 * yield the LUA process, and resume it without checking the
5186 * input arguments.
5187 */
5188__LJMP static int hlua_applet_http_send(lua_State *L)
5189{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005190 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005191
5192 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005193 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005194 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5195 WILL_LJMP(lua_error(L));
5196 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005197
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005198 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005199 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005200
Christopher Fauleta2097962019-07-15 16:25:33 +02005201 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005202}
5203
5204__LJMP static int hlua_applet_http_addheader(lua_State *L)
5205{
5206 const char *name;
5207 int ret;
5208
5209 MAY_LJMP(hlua_checkapplet_http(L, 1));
5210 name = MAY_LJMP(luaL_checkstring(L, 2));
5211 MAY_LJMP(luaL_checkstring(L, 3));
5212
5213 /* Push in the stack the "response" entry. */
5214 ret = lua_getfield(L, 1, "response");
5215 if (ret != LUA_TTABLE) {
5216 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5217 "is expected as an array. %s found", lua_typename(L, ret));
5218 WILL_LJMP(lua_error(L));
5219 }
5220
5221 /* check if the header is already registered if it is not
5222 * the case, register it.
5223 */
5224 ret = lua_getfield(L, -1, name);
5225 if (ret == LUA_TNIL) {
5226
5227 /* Entry not found. */
5228 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5229
5230 /* Insert the new header name in the array in the top of the stack.
5231 * It left the new array in the top of the stack.
5232 */
5233 lua_newtable(L);
5234 lua_pushvalue(L, 2);
5235 lua_pushvalue(L, -2);
5236 lua_settable(L, -4);
5237
5238 } else if (ret != LUA_TTABLE) {
5239
5240 /* corruption error. */
5241 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5242 "is expected as an array. %s found", name, lua_typename(L, ret));
5243 WILL_LJMP(lua_error(L));
5244 }
5245
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005246 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005247 * the header value as new entry.
5248 */
5249 lua_pushvalue(L, 3);
5250 ret = lua_rawlen(L, -2);
5251 lua_rawseti(L, -2, ret + 1);
5252 lua_pushboolean(L, 1);
5253 return 1;
5254}
5255
5256__LJMP static int hlua_applet_http_status(lua_State *L)
5257{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005258 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005259 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005260 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005261
5262 if (status < 100 || status > 599) {
5263 lua_pushboolean(L, 0);
5264 return 1;
5265 }
5266
Willy Tarreau7e702d12021-04-28 17:59:21 +02005267 luactx->appctx->ctx.hlua_apphttp.status = status;
5268 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005269 lua_pushboolean(L, 1);
5270 return 1;
5271}
5272
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005273
Christopher Fauleta2097962019-07-15 16:25:33 +02005274__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005275{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005276 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005277 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005278 struct channel *res = si_ic(si);
5279 struct htx *htx;
5280 struct htx_sl *sl;
5281 struct h1m h1m;
5282 const char *status, *reason;
5283 const char *name, *value;
5284 size_t nlen, vlen;
5285 unsigned int flags;
5286
5287 /* Send the message at once. */
5288 htx = htx_from_buf(&res->buf);
5289 h1m_init_res(&h1m);
5290
5291 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005292 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5293 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005294 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005295 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5296 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005297 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5298 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5299 }
5300 else {
5301 flags = HTX_SL_F_IS_RESP;
5302 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5303 }
5304 if (!sl) {
5305 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005306 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005307 WILL_LJMP(lua_error(L));
5308 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005309 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005310
5311 /* Get the array associated to the field "response" in the object AppletHTTP. */
5312 lua_pushvalue(L, 0);
5313 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5314 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005315 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005316 WILL_LJMP(lua_error(L));
5317 }
5318
5319 /* Browse the list of headers. */
5320 lua_pushnil(L);
5321 while(lua_next(L, -2) != 0) {
5322 /* We expect a string as -2. */
5323 if (lua_type(L, -2) != LUA_TSTRING) {
5324 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005325 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005326 lua_typename(L, lua_type(L, -2)));
5327 WILL_LJMP(lua_error(L));
5328 }
5329 name = lua_tolstring(L, -2, &nlen);
5330
5331 /* We expect an array as -1. */
5332 if (lua_type(L, -1) != LUA_TTABLE) {
5333 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 +02005334 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005335 name,
5336 lua_typename(L, lua_type(L, -1)));
5337 WILL_LJMP(lua_error(L));
5338 }
5339
5340 /* Browse the table who is on the top of the stack. */
5341 lua_pushnil(L);
5342 while(lua_next(L, -2) != 0) {
5343 int id;
5344
5345 /* We expect a number as -2. */
5346 if (lua_type(L, -2) != LUA_TNUMBER) {
5347 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 +02005348 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005349 name,
5350 lua_typename(L, lua_type(L, -2)));
5351 WILL_LJMP(lua_error(L));
5352 }
5353 id = lua_tointeger(L, -2);
5354
5355 /* We expect a string as -2. */
5356 if (lua_type(L, -1) != LUA_TSTRING) {
5357 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 +02005358 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005359 name, id,
5360 lua_typename(L, lua_type(L, -1)));
5361 WILL_LJMP(lua_error(L));
5362 }
5363 value = lua_tolstring(L, -1, &vlen);
5364
5365 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005366 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5367 int ret;
5368
5369 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5370 if (ret < 0) {
5371 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5372 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5373 name);
5374 WILL_LJMP(lua_error(L));
5375 }
5376 else if (ret == 0)
5377 goto next; /* Skip it */
5378 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005379 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5380 struct ist v = ist2(value, vlen);
5381 int ret;
5382
5383 ret = h1_parse_cont_len_header(&h1m, &v);
5384 if (ret < 0) {
5385 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005386 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005387 name);
5388 WILL_LJMP(lua_error(L));
5389 }
5390 else if (ret == 0)
5391 goto next; /* Skip it */
5392 }
5393
5394 /* Add a new header */
5395 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5396 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005397 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005398 name);
5399 WILL_LJMP(lua_error(L));
5400 }
5401 next:
5402 /* Remove the array from the stack, and get next element with a remaining string. */
5403 lua_pop(L, 1);
5404 }
5405
5406 /* Remove the array from the stack, and get next element with a remaining string. */
5407 lua_pop(L, 1);
5408 }
5409
5410 if (h1m.flags & H1_MF_CHNK)
5411 h1m.flags &= ~H1_MF_CLEN;
5412 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5413 h1m.flags |= H1_MF_XFER_LEN;
5414
5415 /* Uset HTX start-line flags */
5416 if (h1m.flags & H1_MF_XFER_ENC)
5417 flags |= HTX_SL_F_XFER_ENC;
5418 if (h1m.flags & H1_MF_XFER_LEN) {
5419 flags |= HTX_SL_F_XFER_LEN;
5420 if (h1m.flags & H1_MF_CHNK)
5421 flags |= HTX_SL_F_CHNK;
5422 else if (h1m.flags & H1_MF_CLEN)
5423 flags |= HTX_SL_F_CLEN;
5424 if (h1m.body_len == 0)
5425 flags |= HTX_SL_F_BODYLESS;
5426 }
5427 sl->flags |= flags;
5428
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005429 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005430 * and the status code implies the presence of a message body, we must
5431 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005432 * for the keepalive compliance. If the applet announces a transfer-encoding
5433 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005434 */
5435 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005436 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5437 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5438 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005439 /* Add a new header */
5440 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5441 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5442 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005443 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005444 WILL_LJMP(lua_error(L));
5445 }
5446 }
5447
5448 /* Finalize headers. */
5449 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5450 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005451 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005452 WILL_LJMP(lua_error(L));
5453 }
5454
5455 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5456 b_reset(&res->buf);
5457 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5458 WILL_LJMP(lua_error(L));
5459 }
5460
5461 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005462 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005463
5464 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005465 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005466 return 0;
5467
5468}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005469/* We will build the status line and the headers of the HTTP response.
5470 * We will try send at once if its not possible, we give back the hand
5471 * waiting for more room.
5472 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005473__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005474{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005475 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005476 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005477 struct channel *res = si_ic(si);
5478
5479 if (co_data(res)) {
5480 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005481 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005482 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005483 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005484}
5485
5486
Christopher Fauleta2097962019-07-15 16:25:33 +02005487__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005488{
Christopher Fauleta2097962019-07-15 16:25:33 +02005489 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005490}
5491
Christopher Fauleta2097962019-07-15 16:25:33 +02005492/*
5493 *
5494 *
5495 * Class HTTP
5496 *
5497 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005498 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005499
5500/* Returns a struct hlua_txn if the stack entry "ud" is
5501 * a class stream, otherwise it throws an error.
5502 */
5503__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005504{
Christopher Fauleta2097962019-07-15 16:25:33 +02005505 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5506}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005507
Christopher Fauleta2097962019-07-15 16:25:33 +02005508/* This function creates and push in the stack a HTTP object
5509 * according with a current TXN.
5510 */
5511static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5512{
5513 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005514
Christopher Fauleta2097962019-07-15 16:25:33 +02005515 /* Check stack size. */
5516 if (!lua_checkstack(L, 3))
5517 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005518
Christopher Fauleta2097962019-07-15 16:25:33 +02005519 /* Create the object: obj[0] = userdata.
5520 * Note that the base of the Converters object is the
5521 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005522 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005523 lua_newtable(L);
5524 htxn = lua_newuserdata(L, sizeof(*htxn));
5525 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005526
5527 htxn->s = txn->s;
5528 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005529 htxn->dir = txn->dir;
5530 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005531
5532 /* Pop a class stream metatable and affect it to the table. */
5533 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5534 lua_setmetatable(L, -2);
5535
5536 return 1;
5537}
5538
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005539/* This function creates and returns an array containing the status-line
5540 * elements. This function does not fails.
5541 */
5542__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5543{
5544 /* Create the table. */
5545 lua_newtable(L);
5546
5547 if (sl->flags & HTX_SL_F_IS_RESP) {
5548 lua_pushstring(L, "version");
5549 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5550 lua_settable(L, -3);
5551 lua_pushstring(L, "code");
5552 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5553 lua_settable(L, -3);
5554 lua_pushstring(L, "reason");
5555 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5556 lua_settable(L, -3);
5557 }
5558 else {
5559 lua_pushstring(L, "method");
5560 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5561 lua_settable(L, -3);
5562 lua_pushstring(L, "uri");
5563 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5564 lua_settable(L, -3);
5565 lua_pushstring(L, "version");
5566 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5567 lua_settable(L, -3);
5568 }
5569 return 1;
5570}
5571
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005572/* This function creates ans returns an array of HTTP headers.
5573 * This function does not fails. It is used as wrapper with the
5574 * 2 following functions.
5575 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005576__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005577{
Christopher Fauleta2097962019-07-15 16:25:33 +02005578 struct htx *htx;
5579 int32_t pos;
5580
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005581 /* Create the table. */
5582 lua_newtable(L);
5583
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005584
Christopher Fauleta2097962019-07-15 16:25:33 +02005585 htx = htxbuf(&msg->chn->buf);
5586 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5587 struct htx_blk *blk = htx_get_blk(htx, pos);
5588 enum htx_blk_type type = htx_get_blk_type(blk);
5589 struct ist n, v;
5590 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005591
Christopher Fauleta2097962019-07-15 16:25:33 +02005592 if (type == HTX_BLK_HDR) {
5593 n = htx_get_blk_name(htx,blk);
5594 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005595 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005596 else if (type == HTX_BLK_EOH)
5597 break;
5598 else
5599 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005600
Christopher Fauleta2097962019-07-15 16:25:33 +02005601 /* Check for existing entry:
5602 * assume that the table is on the top of the stack, and
5603 * push the key in the stack, the function lua_gettable()
5604 * perform the lookup.
5605 */
5606 lua_pushlstring(L, n.ptr, n.len);
5607 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005608
Christopher Fauleta2097962019-07-15 16:25:33 +02005609 switch (lua_type(L, -1)) {
5610 case LUA_TNIL:
5611 /* Table not found, create it. */
5612 lua_pop(L, 1); /* remove the nil value. */
5613 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5614 lua_newtable(L); /* create and push empty table. */
5615 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5616 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5617 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005618 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005619
Christopher Fauleta2097962019-07-15 16:25:33 +02005620 case LUA_TTABLE:
5621 /* Entry found: push the value in the table. */
5622 len = lua_rawlen(L, -1);
5623 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5624 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5625 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5626 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005627
Christopher Fauleta2097962019-07-15 16:25:33 +02005628 default:
5629 /* Other cases are errors. */
5630 hlua_pusherror(L, "internal error during the parsing of headers.");
5631 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005632 }
5633 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005634 return 1;
5635}
5636
5637__LJMP static int hlua_http_req_get_headers(lua_State *L)
5638{
5639 struct hlua_txn *htxn;
5640
5641 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5642 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5643
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005644 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005645 WILL_LJMP(lua_error(L));
5646
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005647 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005648}
5649
5650__LJMP static int hlua_http_res_get_headers(lua_State *L)
5651{
5652 struct hlua_txn *htxn;
5653
5654 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5655 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5656
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005657 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005658 WILL_LJMP(lua_error(L));
5659
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005660 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005661}
5662
5663/* This function replace full header, or just a value in
5664 * the request or in the response. It is a wrapper fir the
5665 * 4 following functions.
5666 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005667__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005668{
5669 size_t name_len;
5670 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5671 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5672 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005673 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005674 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005675
Dragan Dosen26743032019-04-30 15:54:36 +02005676 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005677 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5678
Christopher Fauleta2097962019-07-15 16:25:33 +02005679 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005680 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005681 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005682 return 0;
5683}
5684
5685__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5686{
5687 struct hlua_txn *htxn;
5688
5689 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5690 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5691
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005692 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005693 WILL_LJMP(lua_error(L));
5694
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005695 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005696}
5697
5698__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5699{
5700 struct hlua_txn *htxn;
5701
5702 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5703 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5704
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005705 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005706 WILL_LJMP(lua_error(L));
5707
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005708 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005709}
5710
5711__LJMP static int hlua_http_req_rep_val(lua_State *L)
5712{
5713 struct hlua_txn *htxn;
5714
5715 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5716 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5717
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005718 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005719 WILL_LJMP(lua_error(L));
5720
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005721 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005722}
5723
5724__LJMP static int hlua_http_res_rep_val(lua_State *L)
5725{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005726 struct hlua_txn *htxn;
5727
5728 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5729 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5730
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005731 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005732 WILL_LJMP(lua_error(L));
5733
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005734 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005735}
5736
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005737/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005738 * It is a wrapper for the 2 following functions.
5739 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005740__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005741{
5742 size_t len;
5743 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005744 struct htx *htx = htxbuf(&msg->chn->buf);
5745 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005746
Christopher Fauleta2097962019-07-15 16:25:33 +02005747 ctx.blk = NULL;
5748 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5749 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005750 return 0;
5751}
5752
5753__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5754{
5755 struct hlua_txn *htxn;
5756
5757 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5758 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5759
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005760 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005761 WILL_LJMP(lua_error(L));
5762
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005763 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005764}
5765
5766__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5767{
5768 struct hlua_txn *htxn;
5769
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005770 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005771 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5772
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005773 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005774 WILL_LJMP(lua_error(L));
5775
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005776 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005777}
5778
5779/* This function adds an header. It is a wrapper used by
5780 * the 2 following functions.
5781 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005782__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005783{
5784 size_t name_len;
5785 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5786 size_t value_len;
5787 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005788 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005789
Christopher Fauleta2097962019-07-15 16:25:33 +02005790 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5791 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005792 return 0;
5793}
5794
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005795__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5796{
5797 struct hlua_txn *htxn;
5798
5799 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5800 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5801
5802 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5803 WILL_LJMP(lua_error(L));
5804
5805 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5806}
5807
5808__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5809{
5810 struct hlua_txn *htxn;
5811
5812 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5813 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5814
5815 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5816 WILL_LJMP(lua_error(L));
5817
5818 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5819}
5820
5821static int hlua_http_req_set_hdr(lua_State *L)
5822{
5823 struct hlua_txn *htxn;
5824
5825 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5826 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5827
5828 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5829 WILL_LJMP(lua_error(L));
5830
5831 hlua_http_del_hdr(L, &htxn->s->txn->req);
5832 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5833}
5834
5835static int hlua_http_res_set_hdr(lua_State *L)
5836{
5837 struct hlua_txn *htxn;
5838
5839 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5840 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5841
5842 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5843 WILL_LJMP(lua_error(L));
5844
5845 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5846 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5847}
5848
5849/* This function set the method. */
5850static int hlua_http_req_set_meth(lua_State *L)
5851{
5852 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5853 size_t name_len;
5854 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5855
5856 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5857 WILL_LJMP(lua_error(L));
5858
5859 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5860 return 1;
5861}
5862
5863/* This function set the method. */
5864static int hlua_http_req_set_path(lua_State *L)
5865{
5866 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5867 size_t name_len;
5868 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5869
5870 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5871 WILL_LJMP(lua_error(L));
5872
5873 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5874 return 1;
5875}
5876
5877/* This function set the query-string. */
5878static int hlua_http_req_set_query(lua_State *L)
5879{
5880 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5881 size_t name_len;
5882 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5883
5884 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5885 WILL_LJMP(lua_error(L));
5886
5887 /* Check length. */
5888 if (name_len > trash.size - 1) {
5889 lua_pushboolean(L, 0);
5890 return 1;
5891 }
5892
5893 /* Add the mark question as prefix. */
5894 chunk_reset(&trash);
5895 trash.area[trash.data++] = '?';
5896 memcpy(trash.area + trash.data, name, name_len);
5897 trash.data += name_len;
5898
5899 lua_pushboolean(L,
5900 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5901 return 1;
5902}
5903
5904/* This function set the uri. */
5905static int hlua_http_req_set_uri(lua_State *L)
5906{
5907 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5908 size_t name_len;
5909 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5910
5911 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5912 WILL_LJMP(lua_error(L));
5913
5914 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5915 return 1;
5916}
5917
5918/* This function set the response code & optionally reason. */
5919static int hlua_http_res_set_status(lua_State *L)
5920{
5921 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5922 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5923 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5924 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5925
5926 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5927 WILL_LJMP(lua_error(L));
5928
5929 http_res_set_status(code, reason, htxn->s);
5930 return 0;
5931}
5932
5933/*
5934 *
5935 *
5936 * Class HTTPMessage
5937 *
5938 *
5939 */
5940
5941/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5942 * otherwise it throws an error.
5943 */
5944__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5945{
5946 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5947}
5948
5949/* Creates and pushes on the stack a HTTP object according with a current TXN.
5950 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005951static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005952{
5953 /* Check stack size. */
5954 if (!lua_checkstack(L, 3))
5955 return 0;
5956
5957 lua_newtable(L);
5958 lua_pushlightuserdata(L, msg);
5959 lua_rawseti(L, -2, 0);
5960
5961 /* Create the "channel" field that contains the request channel object. */
5962 lua_pushstring(L, "channel");
5963 if (!hlua_channel_new(L, msg->chn))
5964 return 0;
5965 lua_rawset(L, -3);
5966
5967 /* Pop a class stream metatable and affect it to the table. */
5968 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5969 lua_setmetatable(L, -2);
5970
5971 return 1;
5972}
5973
5974/* Helper function returning a filter attached to the HTTP message at the
5975 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05005976 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005977 * filled with output and input length respectively.
5978 */
5979static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5980{
5981 struct channel *chn = msg->chn;
5982 struct htx *htx = htxbuf(&chn->buf);
5983 struct filter *filter = NULL;
5984
5985 *offset = co_data(msg->chn);
5986 *len = htx->data - co_data(msg->chn);
5987
5988 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5989 filter = lua_touserdata (L, -1);
5990 if (msg->msg_state >= HTTP_MSG_DATA) {
5991 struct hlua_flt_ctx *flt_ctx = filter->ctx;
5992
5993 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
5994 *len = flt_ctx->cur_len[CHN_IDX(chn)];
5995 }
5996 }
5997
5998 lua_pop(L, 1);
5999 return filter;
6000}
6001
6002/* Returns true if the channel attached to the HTTP message is the response
6003 * channel.
6004 */
6005__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6006{
6007 struct http_msg *msg;
6008
6009 MAY_LJMP(check_args(L, 1, "is_resp"));
6010 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6011
6012 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6013 return 1;
6014}
6015
6016/* Returns an array containing the elements status-line of the HTTP message. It relies
6017 * on hlua_http_get_stline().
6018 */
6019__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6020{
6021 struct http_msg *msg;
6022 struct htx *htx;
6023 struct htx_sl *sl;
6024
6025 MAY_LJMP(check_args(L, 1, "get_stline"));
6026 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6027
6028 if (msg->msg_state > HTTP_MSG_BODY)
6029 WILL_LJMP(lua_error(L));
6030
6031 htx = htxbuf(&msg->chn->buf);
6032 sl = http_get_stline(htx);
6033 if (!sl)
6034 return 0;
6035 return hlua_http_get_stline(L, sl);
6036}
6037
6038/* Returns an array containing all headers of the HTTP message. it relies on
6039 * hlua_http_get_headers().
6040 */
6041__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6042{
6043 struct http_msg *msg;
6044
6045 MAY_LJMP(check_args(L, 1, "get_headers"));
6046 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6047
6048 if (msg->msg_state > HTTP_MSG_BODY)
6049 WILL_LJMP(lua_error(L));
6050
6051 return hlua_http_get_headers(L, msg);
6052}
6053
6054/* Deletes all occurrences of an header in the HTTP message matching on its
6055 * name. It relies on hlua_http_del_hdr().
6056 */
6057__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6058{
6059 struct http_msg *msg;
6060
6061 MAY_LJMP(check_args(L, 2, "del_header"));
6062 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6063
6064 if (msg->msg_state > HTTP_MSG_BODY)
6065 WILL_LJMP(lua_error(L));
6066
6067 return hlua_http_del_hdr(L, msg);
6068}
6069
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006070/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006071 * message given its name against a regex and replaces it if it matches. It
6072 * relies on hlua_http_rep_hdr().
6073 */
6074__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6075{
6076 struct http_msg *msg;
6077
6078 MAY_LJMP(check_args(L, 4, "rep_header"));
6079 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6080
6081 if (msg->msg_state > HTTP_MSG_BODY)
6082 WILL_LJMP(lua_error(L));
6083
6084 return hlua_http_rep_hdr(L, msg, 1);
6085}
6086
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006087/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006088 * message given its name against a regex and replaces it if it matches. It
6089 * relies on hlua_http_rep_hdr().
6090 */
6091__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6092{
6093 struct http_msg *msg;
6094
6095 MAY_LJMP(check_args(L, 4, "rep_value"));
6096 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6097
6098 if (msg->msg_state > HTTP_MSG_BODY)
6099 WILL_LJMP(lua_error(L));
6100
6101 return hlua_http_rep_hdr(L, msg, 0);
6102}
6103
6104/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6105__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6106{
6107 struct http_msg *msg;
6108
6109 MAY_LJMP(check_args(L, 3, "add_header"));
6110 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6111
6112 if (msg->msg_state > HTTP_MSG_BODY)
6113 WILL_LJMP(lua_error(L));
6114
6115 return hlua_http_add_hdr(L, msg);
6116}
6117
6118/* Add an header in the HTTP message removing existing headers with the same
6119 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6120 */
6121__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6122{
6123 struct http_msg *msg;
6124
6125 MAY_LJMP(check_args(L, 3, "set_header"));
6126 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6127
6128 if (msg->msg_state > HTTP_MSG_BODY)
6129 WILL_LJMP(lua_error(L));
6130
6131 hlua_http_del_hdr(L, msg);
6132 return hlua_http_add_hdr(L, msg);
6133}
6134
6135/* Rewrites the request method. It relies on http_req_replace_stline(). */
6136__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6137{
6138 struct stream *s;
6139 struct http_msg *msg;
6140 const char *name;
6141 size_t name_len;
6142
6143 MAY_LJMP(check_args(L, 2, "set_method"));
6144 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6145 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6146
6147 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6148 WILL_LJMP(lua_error(L));
6149
6150 s = chn_strm(msg->chn);
6151 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6152 return 1;
6153}
6154
6155/* Rewrites the request path. It relies on http_req_replace_stline(). */
6156__LJMP static int hlua_http_msg_set_path(lua_State *L)
6157{
6158 struct stream *s;
6159 struct http_msg *msg;
6160 const char *name;
6161 size_t name_len;
6162
6163 MAY_LJMP(check_args(L, 2, "set_path"));
6164 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6165 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6166
6167 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6168 WILL_LJMP(lua_error(L));
6169
6170 s = chn_strm(msg->chn);
6171 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6172 return 1;
6173}
6174
6175/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6176__LJMP static int hlua_http_msg_set_query(lua_State *L)
6177{
6178 struct stream *s;
6179 struct http_msg *msg;
6180 const char *name;
6181 size_t name_len;
6182
6183 MAY_LJMP(check_args(L, 2, "set_query"));
6184 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6185 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6186
6187 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6188 WILL_LJMP(lua_error(L));
6189
6190 /* Check length. */
6191 if (name_len > trash.size - 1) {
6192 lua_pushboolean(L, 0);
6193 return 1;
6194 }
6195
6196 /* Add the mark question as prefix. */
6197 chunk_reset(&trash);
6198 trash.area[trash.data++] = '?';
6199 memcpy(trash.area + trash.data, name, name_len);
6200 trash.data += name_len;
6201
6202 s = chn_strm(msg->chn);
6203 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6204 return 1;
6205}
6206
6207/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6208__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6209{
6210 struct stream *s;
6211 struct http_msg *msg;
6212 const char *name;
6213 size_t name_len;
6214
6215 MAY_LJMP(check_args(L, 2, "set_uri"));
6216 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6217 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6218
6219 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6220 WILL_LJMP(lua_error(L));
6221
6222 s = chn_strm(msg->chn);
6223 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6224 return 1;
6225}
6226
6227/* Rewrites the response status code. It relies on http_res_set_status(). */
6228__LJMP static int hlua_http_msg_set_status(lua_State *L)
6229{
6230 struct http_msg *msg;
6231 unsigned int code;
6232 const char *reason;
6233 size_t reason_len;
6234
6235 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6236 code = MAY_LJMP(luaL_checkinteger(L, 2));
6237 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6238
6239 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6240 WILL_LJMP(lua_error(L));
6241
6242 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6243 return 1;
6244}
6245
6246/* Returns true if the HTTP message is full. */
6247__LJMP static int hlua_http_msg_is_full(lua_State *L)
6248{
6249 struct http_msg *msg;
6250
6251 MAY_LJMP(check_args(L, 1, "is_full"));
6252 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6253 lua_pushboolean(L, channel_full(msg->chn, 0));
6254 return 1;
6255}
6256
6257/* Returns true if the HTTP message may still receive data. */
6258__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6259{
6260 struct http_msg *msg;
6261 struct htx *htx;
6262
6263 MAY_LJMP(check_args(L, 1, "may_recv"));
6264 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6265 htx = htxbuf(&msg->chn->buf);
6266 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6267 return 1;
6268}
6269
6270/* Returns true if the HTTP message EOM was received */
6271__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6272{
6273 struct http_msg *msg;
6274 struct htx *htx;
6275
6276 MAY_LJMP(check_args(L, 1, "may_recv"));
6277 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6278 htx = htxbuf(&msg->chn->buf);
6279 lua_pushboolean(L, !htx_expect_more(htx));
6280 return 1;
6281}
6282
6283/* Returns the number of bytes available in the input side of the HTTP
6284 * message. This function never fails.
6285 */
6286__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6287{
6288 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006289 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006290
6291 MAY_LJMP(check_args(L, 1, "input"));
6292 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006293 hlua_http_msg_filter(L, 1, msg, &output, &input);
6294 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006295 return 1;
6296}
6297
6298/* Returns the number of bytes available in the output side of the HTTP
6299 * message. This function never fails.
6300 */
6301__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6302{
6303 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006304 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006305
6306 MAY_LJMP(check_args(L, 1, "output"));
6307 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006308 hlua_http_msg_filter(L, 1, msg, &output, &input);
6309 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006310 return 1;
6311}
6312
6313/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6314 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006315 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006316 * block. This function is called during the payload filtering, so the headers
6317 * are already scheduled for output (from the filter point of view).
6318 */
6319static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6320{
6321 struct htx *htx = htxbuf(&msg->chn->buf);
6322 struct htx_blk *blk;
6323 struct htx_ret htxret;
6324 luaL_Buffer b;
6325 int ret = 0;
6326
6327 luaL_buffinit(L, &b);
6328 htxret = htx_find_offset(htx, offset);
6329 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6330 enum htx_blk_type type = htx_get_blk_type(blk);
6331 struct ist v;
6332
6333 switch (type) {
6334 case HTX_BLK_UNUSED:
6335 break;
6336
6337 case HTX_BLK_DATA:
6338 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006339 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006340 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006341
6342 luaL_addlstring(&b, v.ptr, v.len);
6343 ret += v.len;
6344 break;
6345
6346 default:
vishnu0af4bd72021-10-24 06:46:24 +05306347 if (!ret)
6348 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006349 goto end;
6350 }
6351 offset = 0;
6352 }
6353
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006354end:
vishnu0af4bd72021-10-24 06:46:24 +05306355 if (!ret && (htx->flags & HTX_FL_EOM))
6356 goto no_data;
6357 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006358 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306359
6360 no_data:
6361 /* Remove the empty string and push nil on the stack */
6362 lua_pop(L, 1);
6363 lua_pushnil(L);
6364 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006365}
6366
6367/* Copies the string <str> to the HTTP message <msg> at the offset
6368 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006369 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006370 * the filter context.
6371 */
6372static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6373{
6374 struct htx *htx = htx_from_buf(&msg->chn->buf);
6375 struct htx_ret htxret;
6376 int /*max, */ret = 0;
6377
6378 /* Nothing to do, just return */
6379 if (unlikely(istlen(str) == 0))
6380 goto end;
6381
6382 if (istlen(str) > htx_free_data_space(htx)) {
6383 ret = -1;
6384 goto end;
6385 }
6386
6387 htxret = htx_find_offset(htx, offset);
6388 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6389 if (!htx_add_last_data(htx, str))
6390 goto end;
6391 }
6392 else {
6393 struct ist v = htx_get_blk_value(htx, htxret.blk);
6394 v.ptr += htxret.ret;
6395 v.len = 0;
6396 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6397 goto end;
6398 }
6399 ret = str.len;
6400 if (ret) {
6401 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6402 flt_update_offsets(filter, msg->chn, ret);
6403 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6404 }
6405
6406 end:
6407 htx_to_buf(htx, &msg->chn->buf);
6408 return ret;
6409}
6410
6411/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6412 * position <offset>. It stops on the first non-DATA HTX block. This function is
6413 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006414 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006415 * update the filter context.
6416 */
6417static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6418{
6419 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6420 struct htx *htx = htx_from_buf(&msg->chn->buf);
6421 struct htx_blk *blk;
6422 struct htx_ret htxret;
6423 size_t ret = 0;
6424
6425 /* Be sure <len> is always the amount of DATA to remove */
6426 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6427 htx_truncate(htx, offset);
6428 ret = len;
6429 goto end;
6430 }
6431
6432 htxret = htx_find_offset(htx, offset);
6433 blk = htxret.blk;
6434 if (htxret.ret) {
6435 struct ist v;
6436
6437 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6438 goto end;
6439 v = htx_get_blk_value(htx, blk);
6440 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006441 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006442 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006443 len -= v.len;
6444 ret += v.len;
6445 }
6446
6447
6448 while (blk && len) {
6449 enum htx_blk_type type = htx_get_blk_type(blk);
6450 uint32_t sz = htx_get_blksz(blk);
6451
6452 switch (type) {
6453 case HTX_BLK_UNUSED:
6454 break;
6455
6456 case HTX_BLK_DATA:
6457 if (len < sz) {
6458 htx_cut_data_blk(htx, blk, len);
6459 ret += len;
6460 goto end;
6461 }
6462 break;
6463
6464 default:
6465 goto end;
6466 }
6467
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006468 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006469 len -= sz;
6470 ret += sz;
6471 blk = htx_remove_blk(htx, blk);
6472 }
6473
6474end:
6475 flt_update_offsets(filter, msg->chn, -ret);
6476 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6477 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6478 * to loose the EOM flag if the message is empty.
6479 */
6480}
6481
6482/* Copies input data found in an HTTP message. Unlike the channel function used
6483 * to duplicate raw data, this one can only be called inside a filter, from
6484 * http_payload callback. So it cannot yield. An exception is returned if it is
6485 * called from another callback. If nothing was copied, a nil value is pushed on
6486 * the stack.
6487 */
6488__LJMP static int hlua_http_msg_get_body(lua_State *L)
6489{
6490 struct http_msg *msg;
6491 struct filter *filter;
6492 size_t output, input;
6493 int offset, len;
6494
6495 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6496 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6497 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6498
6499 if (msg->msg_state < HTTP_MSG_DATA)
6500 WILL_LJMP(lua_error(L));
6501
6502 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6503 if (!filter || !hlua_filter_from_payload(filter))
6504 WILL_LJMP(lua_error(L));
6505
6506 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6507 lua_pushnil(L);
6508 return 1;
6509 }
6510
6511 offset = output;
6512 if (lua_gettop(L) > 1) {
6513 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6514 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006515 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006516 offset += output;
6517 if (offset < output || offset > input + output) {
6518 lua_pushfstring(L, "offset out of range.");
6519 WILL_LJMP(lua_error(L));
6520 }
6521 }
6522 len = output + input - offset;
6523 if (lua_gettop(L) == 3) {
6524 len = MAY_LJMP(luaL_checkinteger(L, 3));
6525 if (!len)
6526 goto dup;
6527 if (len == -1)
6528 len = global.tune.bufsize;
6529 if (len < 0) {
6530 lua_pushfstring(L, "length out of range.");
6531 WILL_LJMP(lua_error(L));
6532 }
6533 }
6534
6535 dup:
6536 _hlua_http_msg_dup(msg, L, offset, len);
6537 return 1;
6538}
6539
6540/* Appends a string to the HTTP message, after all existing DATA blocks but
6541 * before the trailers, if any. It returns the amount of data written or -1 if
6542 * nothing was copied. Unlike the channel function used to append data, this one
6543 * can only be called inside a filter, from http_payload callback. So it cannot
6544 * yield. An exception is returned if it is called from another callback.
6545 */
6546__LJMP static int hlua_http_msg_append(lua_State *L)
6547{
6548 struct http_msg *msg;
6549 struct filter *filter;
6550 const char *str;
6551 size_t offset, len, sz;
6552 int ret;
6553
6554 MAY_LJMP(check_args(L, 2, "append"));
6555 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6556
6557 if (msg->msg_state < HTTP_MSG_DATA)
6558 WILL_LJMP(lua_error(L));
6559
6560 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6561 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6562 if (!filter || !hlua_filter_from_payload(filter))
6563 WILL_LJMP(lua_error(L));
6564
6565 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6566 lua_pushinteger(L, ret);
6567 return 1;
6568}
6569
6570/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6571 * returns the amount of data written or -1 if nothing was copied. Unlike the
6572 * channel function used to prepend data, this one can only be called inside a
6573 * filter, from http_payload callback. So it cannot yield. An exception is
6574 * returned if it is called from another callback.
6575 */
6576__LJMP static int hlua_http_msg_prepend(lua_State *L)
6577{
6578 struct http_msg *msg;
6579 struct filter *filter;
6580 const char *str;
6581 size_t offset, len, sz;
6582 int ret;
6583
6584 MAY_LJMP(check_args(L, 2, "prepend"));
6585 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006586
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006587 if (msg->msg_state < HTTP_MSG_DATA)
6588 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006589
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006590 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6591 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6592 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006593 WILL_LJMP(lua_error(L));
6594
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006595 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6596 lua_pushinteger(L, ret);
6597 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006598}
6599
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006600/* Inserts a string to the HTTP message at a given offset. By default the string
6601 * is appended at the end of DATA blocks. It returns the amount of data written
6602 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6603 * this one can only be called inside a filter, from http_payload callback. So
6604 * it cannot yield. An exception is returned if it is called from another
6605 * callback.
6606 */
6607__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006608{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006609 struct http_msg *msg;
6610 struct filter *filter;
6611 const char *str;
6612 size_t input, output, sz;
6613 int offset;
6614 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006615
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006616 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6617 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6618 MAY_LJMP(check_args(L, 2, "insert"));
6619 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006620
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006621 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006622 WILL_LJMP(lua_error(L));
6623
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006624 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6625 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6626 if (!filter || !hlua_filter_from_payload(filter))
6627 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006628
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006629 offset = input + output;
6630 if (lua_gettop(L) > 2) {
6631 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6632 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006633 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006634 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006635 if (offset < output || offset > output + input) {
6636 lua_pushfstring(L, "offset out of range.");
6637 WILL_LJMP(lua_error(L));
6638 }
6639 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006640
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006641 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6642 lua_pushinteger(L, ret);
6643 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006644}
6645
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006646/* Removes a given amount of data from the HTTP message at a given offset. By
6647 * default all DATA blocks are removed. It returns the amount of data
6648 * removed. Unlike the channel function used to remove data, this one can only
6649 * be called inside a filter, from http_payload callback. So it cannot yield. An
6650 * exception is returned if it is called from another callback.
6651 */
6652__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006653{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006654 struct http_msg *msg;
6655 struct filter *filter;
6656 size_t input, output;
6657 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006658
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006659 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6660 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6661 MAY_LJMP(check_args(L, 2, "insert"));
6662 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006663
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006664 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006665 WILL_LJMP(lua_error(L));
6666
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006667 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6668 if (!filter || !hlua_filter_from_payload(filter))
6669 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006670
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006671 offset = input + output;
6672 if (lua_gettop(L) > 2) {
6673 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6674 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006675 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006676 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006677 if (offset < output || offset > output + input) {
6678 lua_pushfstring(L, "offset out of range.");
6679 WILL_LJMP(lua_error(L));
6680 }
6681 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006682
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006683 len = output + input - offset;
6684 if (lua_gettop(L) == 4) {
6685 len = MAY_LJMP(luaL_checkinteger(L, 4));
6686 if (!len)
6687 goto end;
6688 if (len == -1)
6689 len = output + input - offset;
6690 if (len < 0 || offset + len > output + input) {
6691 lua_pushfstring(L, "length out of range.");
6692 WILL_LJMP(lua_error(L));
6693 }
6694 }
6695
6696 _hlua_http_msg_delete(msg, filter, offset, len);
6697
6698 end:
6699 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006700 return 1;
6701}
6702
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006703/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006704 * all remaining data are removed, accordingly to the filter context. It returns
6705 * the amount of data written or -1 if nothing was copied. Unlike the channel
6706 * function used to replace data, this one can only be called inside a filter,
6707 * from http_payload callback. So it cannot yield. An exception is returned if
6708 * it is called from another callback.
6709 */
6710__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006711{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006712 struct http_msg *msg;
6713 struct filter *filter;
6714 struct htx *htx;
6715 const char *str;
6716 size_t input, output, sz;
6717 int offset, len;
6718 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006719
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006720 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6721 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6722 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6723
6724 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006725 WILL_LJMP(lua_error(L));
6726
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006727 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6728 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6729 if (!filter || !hlua_filter_from_payload(filter))
6730 WILL_LJMP(lua_error(L));
6731
6732 offset = output;
6733 if (lua_gettop(L) > 2) {
6734 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6735 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006736 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006737 offset += output;
6738 if (offset < output || offset > input + output) {
6739 lua_pushfstring(L, "offset out of range.");
6740 WILL_LJMP(lua_error(L));
6741 }
6742 }
6743
6744 len = output + input - offset;
6745 if (lua_gettop(L) == 4) {
6746 len = MAY_LJMP(luaL_checkinteger(L, 4));
6747 if (!len)
6748 goto set;
6749 if (len == -1)
6750 len = output + input - offset;
6751 if (len < 0 || offset + len > output + input) {
6752 lua_pushfstring(L, "length out of range.");
6753 WILL_LJMP(lua_error(L));
6754 }
6755 }
6756
6757 set:
6758 /* Be sure we can copied the string once input data will be removed. */
6759 htx = htx_from_buf(&msg->chn->buf);
6760 if (sz > htx_free_data_space(htx) + len)
6761 lua_pushinteger(L, -1);
6762 else {
6763 _hlua_http_msg_delete(msg, filter, offset, len);
6764 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6765 lua_pushinteger(L, ret);
6766 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006767 return 1;
6768}
6769
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006770/* Prepends data into an HTTP message and forward it, from the filter point of
6771 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6772 * the channel function used to send data, this one can only be called inside a
6773 * filter, from http_payload callback. So it cannot yield. An exception is
6774 * returned if it is called from another callback.
6775 */
6776__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006777{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006778 struct http_msg *msg;
6779 struct filter *filter;
6780 struct htx *htx;
6781 const char *str;
6782 size_t offset, len, sz;
6783 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006784
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006785 MAY_LJMP(check_args(L, 2, "send"));
6786 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6787
6788 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006789 WILL_LJMP(lua_error(L));
6790
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006791 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6792 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6793 if (!filter || !hlua_filter_from_payload(filter))
6794 WILL_LJMP(lua_error(L));
6795
6796 /* Return an error if the channel's output is closed */
6797 if (unlikely(channel_output_closed(msg->chn))) {
6798 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006799 return 1;
6800 }
6801
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006802 htx = htx_from_buf(&msg->chn->buf);
6803 if (sz > htx_free_data_space(htx)) {
6804 lua_pushinteger(L, -1);
6805 return 1;
6806 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006807
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006808 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6809 if (ret > 0) {
6810 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6811
6812 FLT_OFF(filter, msg->chn) += ret;
6813 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6814 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6815 }
6816
6817 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006818 return 1;
6819}
6820
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006821/* Forwards a given amount of bytes. It return -1 if the channel's output is
6822 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6823 * channel function used to forward data, this one can only be called inside a
6824 * filter, from http_payload callback. So it cannot yield. An exception is
6825 * returned if it is called from another callback. All other functions deal with
6826 * DATA block, this one not.
6827*/
6828__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006829{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006830 struct http_msg *msg;
6831 struct filter *filter;
6832 size_t offset, len;
6833 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006834
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006835 MAY_LJMP(check_args(L, 2, "forward"));
6836 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6837
6838 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006839 WILL_LJMP(lua_error(L));
6840
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006841 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6842 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6843 if (!filter || !hlua_filter_from_payload(filter))
6844 WILL_LJMP(lua_error(L));
6845
6846 /* Nothing to do, just return */
6847 if (!fwd)
6848 goto end;
6849
6850 /* Return an error if the channel's output is closed */
6851 if (unlikely(channel_output_closed(msg->chn))) {
6852 ret = -1;
6853 goto end;
6854 }
6855
6856 ret = fwd;
6857 if (ret > len)
6858 ret = len;
6859
6860 if (ret) {
6861 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6862
6863 FLT_OFF(filter, msg->chn) += ret;
6864 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6865 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6866 }
6867
6868 end:
6869 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006870 return 1;
6871}
6872
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006873/* Set EOM flag on the HTX message.
6874 *
6875 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6876 * really know how to do without this feature.
6877 */
6878__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006879{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006880 struct http_msg *msg;
6881 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006882
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006883 MAY_LJMP(check_args(L, 1, "set_eom"));
6884 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6885 htx = htxbuf(&msg->chn->buf);
6886 htx->flags |= HTX_FL_EOM;
6887 return 0;
6888}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006889
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006890/* Unset EOM flag on the HTX message.
6891 *
6892 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6893 * really know how to do without this feature.
6894 */
6895__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6896{
6897 struct http_msg *msg;
6898 struct htx *htx;
6899
6900 MAY_LJMP(check_args(L, 1, "set_eom"));
6901 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6902 htx = htxbuf(&msg->chn->buf);
6903 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006904 return 0;
6905}
6906
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006907/*
6908 *
6909 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006910 * Class HTTPClient
6911 *
6912 *
6913 */
6914__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6915{
6916 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6917}
6918
William Lallemandf77f1de2021-09-28 19:10:38 +02006919
6920/* stops the httpclient and ask it to kill itself */
6921__LJMP static int hlua_httpclient_gc(lua_State *L)
6922{
6923 struct hlua_httpclient *hlua_hc;
6924
6925 MAY_LJMP(check_args(L, 1, "__gc"));
6926
6927 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6928
6929 httpclient_stop_and_destroy(hlua_hc->hc);
6930
6931 hlua_hc->hc = NULL;
6932
6933
6934 return 0;
6935}
6936
6937
William Lallemand3956c4e2021-09-21 16:25:15 +02006938__LJMP static int hlua_httpclient_new(lua_State *L)
6939{
6940 struct hlua_httpclient *hlua_hc;
6941 struct hlua *hlua;
6942
6943 /* Get hlua struct, or NULL if we execute from main lua state */
6944 hlua = hlua_gethlua(L);
6945 if (!hlua)
6946 return 0;
6947
6948 /* Check stack size. */
6949 if (!lua_checkstack(L, 3)) {
6950 hlua_pusherror(L, "httpclient: full stack");
6951 goto err;
6952 }
6953 /* Create the object: obj[0] = userdata. */
6954 lua_newtable(L);
6955 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6956 lua_rawseti(L, -2, 0);
6957 memset(hlua_hc, 0, sizeof(*hlua_hc));
6958
6959 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6960 if (!hlua_hc->hc)
6961 goto err;
6962
6963 /* Pop a class stream metatable and affect it to the userdata. */
6964 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6965 lua_setmetatable(L, -2);
6966
6967 return 1;
6968
6969 err:
6970 WILL_LJMP(lua_error(L));
6971 return 0;
6972}
6973
6974
6975/*
6976 * Callback of the httpclient, this callback wakes the lua task up, once the
6977 * httpclient receives some data
6978 *
6979 */
6980
William Lallemandbd5739e2021-10-28 15:41:38 +02006981static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02006982{
6983 struct hlua *hlua = hc->caller;
6984
6985 if (!hlua || !hlua->task)
6986 return;
6987
6988 task_wakeup(hlua->task, TASK_WOKEN_MSG);
6989}
6990
6991/*
William Lallemandd7df73a2021-09-23 17:54:00 +02006992 * Fill the lua stack with headers from the httpclient response
6993 * This works the same way as the hlua_http_get_headers() function
6994 */
6995__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
6996{
6997 struct http_hdr *hdr;
6998
6999 lua_newtable(L);
7000
William Lallemandef574b22021-10-05 16:19:31 +02007001 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007002 struct ist n, v;
7003 int len;
7004
7005 n = hdr->n;
7006 v = hdr->v;
7007
7008 /* Check for existing entry:
7009 * assume that the table is on the top of the stack, and
7010 * push the key in the stack, the function lua_gettable()
7011 * perform the lookup.
7012 */
7013
7014 lua_pushlstring(L, n.ptr, n.len);
7015 lua_gettable(L, -2);
7016
7017 switch (lua_type(L, -1)) {
7018 case LUA_TNIL:
7019 /* Table not found, create it. */
7020 lua_pop(L, 1); /* remove the nil value. */
7021 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7022 lua_newtable(L); /* create and push empty table. */
7023 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7024 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7025 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7026 break;
7027
7028 case LUA_TTABLE:
7029 /* Entry found: push the value in the table. */
7030 len = lua_rawlen(L, -1);
7031 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7032 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7033 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7034 break;
7035
7036 default:
7037 /* Other cases are errors. */
7038 hlua_pusherror(L, "internal error during the parsing of headers.");
7039 WILL_LJMP(lua_error(L));
7040 }
7041 }
7042 return 1;
7043}
7044
7045/*
William Lallemand746e6f32021-10-06 10:57:44 +02007046 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7047 *
7048 * Caller must free the result
7049 */
7050struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7051{
7052 struct http_hdr hdrs[global.tune.max_http_hdr];
7053 struct http_hdr *result = NULL;
7054 uint32_t hdr_num = 0;
7055
7056 lua_pushnil(L);
7057 while (lua_next(L, -2) != 0) {
7058 struct ist name, value;
7059 const char *n, *v;
7060 size_t nlen, vlen;
7061
7062 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7063 /* Skip element if the key is not a string or if the value is not a table */
7064 goto next_hdr;
7065 }
7066
7067 n = lua_tolstring(L, -2, &nlen);
7068 name = ist2(n, nlen);
7069
7070 /* Loop on header's values */
7071 lua_pushnil(L);
7072 while (lua_next(L, -2)) {
7073 if (!lua_isstring(L, -1)) {
7074 /* Skip the value if it is not a string */
7075 goto next_value;
7076 }
7077
7078 v = lua_tolstring(L, -1, &vlen);
7079 value = ist2(v, vlen);
7080 name = ist2(n, nlen);
7081
7082 hdrs[hdr_num].n = istdup(name);
7083 hdrs[hdr_num].v = istdup(value);
7084
7085 hdr_num++;
7086
7087 next_value:
7088 lua_pop(L, 1);
7089 }
7090
7091 next_hdr:
7092 lua_pop(L, 1);
7093
7094 }
7095
7096 if (hdr_num) {
7097 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007098 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007099 if (!result)
7100 goto skip_headers;
7101 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7102
7103 result[hdr_num].n = IST_NULL;
7104 result[hdr_num].v = IST_NULL;
7105 }
7106
7107skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007108
7109 return result;
7110}
7111
7112
William Lallemandbd5739e2021-10-28 15:41:38 +02007113/*
7114 * For each yield, checks if there is some data in the httpclient and push them
7115 * in the lua buffer, once the httpclient finished its job, push the result on
7116 * the stack
7117 */
7118__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7119{
7120 struct buffer *tr;
7121 int res;
7122 struct hlua *hlua = hlua_gethlua(L);
7123 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7124
7125
7126 tr = get_trash_chunk();
7127
7128 res = httpclient_res_xfer(hlua_hc->hc, tr);
7129 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7130
7131 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7132
7133 luaL_pushresult(&hlua_hc->b);
7134 lua_settable(L, -3);
7135
7136 lua_pushstring(L, "status");
7137 lua_pushinteger(L, hlua_hc->hc->res.status);
7138 lua_settable(L, -3);
7139
7140
7141 lua_pushstring(L, "reason");
7142 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7143 lua_settable(L, -3);
7144
7145 lua_pushstring(L, "headers");
7146 hlua_httpclient_get_headers(L, hlua_hc);
7147 lua_settable(L, -3);
7148
7149 return 1;
7150 }
7151
7152 if (httpclient_data(hlua_hc->hc))
7153 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7154
7155 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7156
7157 return 0;
7158}
7159
7160/*
7161 * Call this when trying to stream a body during a request
7162 */
7163__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7164{
7165 struct hlua *hlua;
7166 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7167 const char *body_str = NULL;
7168 int ret;
7169 int end = 0;
7170 size_t buf_len;
7171 size_t to_send = 0;
7172
7173 hlua = hlua_gethlua(L);
7174
7175 if (!hlua || !hlua->task)
7176 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7177 "'frontend', 'backend' or 'task'"));
7178
7179 ret = lua_getfield(L, -1, "body");
7180 if (ret != LUA_TSTRING)
7181 goto rcv;
7182
7183 body_str = lua_tolstring(L, -1, &buf_len);
7184 lua_pop(L, 1);
7185
Christopher Fauletfc591292022-01-12 14:46:03 +01007186 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007187
7188 if ((hlua_hc->sent + to_send) >= buf_len)
7189 end = 1;
7190
7191 /* the end flag is always set since we are using the whole remaining size */
7192 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7193
7194 if (buf_len > hlua_hc->sent) {
7195 /* still need to process the buffer */
7196 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7197 } else {
7198 goto rcv;
7199 /* we sent the whole request buffer we can recv */
7200 }
7201 return 0;
7202
7203rcv:
7204
7205 /* we return a "res" object */
7206 lua_newtable(L);
7207
William Lallemandbd5739e2021-10-28 15:41:38 +02007208 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007209 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007210
William Lallemand933fe392021-11-04 09:45:58 +01007211 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007212 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7213
7214 return 1;
7215}
William Lallemand746e6f32021-10-06 10:57:44 +02007216
William Lallemand3956c4e2021-09-21 16:25:15 +02007217/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007218 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007219 */
7220
William Lallemanddc2cc902021-10-26 11:43:26 +02007221__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007222{
7223 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007224 struct http_hdr *hdrs = NULL;
7225 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007226 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007227 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007228 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007229 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007230 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007231
7232 hlua = hlua_gethlua(L);
7233
7234 if (!hlua || !hlua->task)
7235 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7236 "'frontend', 'backend' or 'task'"));
7237
William Lallemand746e6f32021-10-06 10:57:44 +02007238 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7239 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7240
William Lallemand4f4f2b72022-02-17 20:00:23 +01007241 hlua_hc = hlua_checkhttpclient(L, 1);
7242
William Lallemand7177a952022-03-03 15:33:12 +01007243 lua_pushnil(L); /* first key */
7244 while (lua_next(L, 2)) {
7245 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7246 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7247 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007248
William Lallemand7177a952022-03-03 15:33:12 +01007249 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7250 if (lua_type(L, -1) != LUA_TSTRING)
7251 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7252 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007253
William Lallemand7177a952022-03-03 15:33:12 +01007254 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7255 if (lua_type(L, -1) != LUA_TNUMBER)
7256 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7257 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007258
William Lallemand7177a952022-03-03 15:33:12 +01007259 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7260 if (lua_type(L, -1) != LUA_TTABLE)
7261 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7262 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007263
William Lallemand7177a952022-03-03 15:33:12 +01007264 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7265 if (lua_type(L, -1) != LUA_TSTRING)
7266 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7267 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007268
William Lallemand7177a952022-03-03 15:33:12 +01007269 } else {
7270 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7271 }
7272 /* removes 'value'; keeps 'key' for next iteration */
7273 lua_pop(L, 1);
7274 }
William Lallemanddec25c32021-10-25 19:48:37 +02007275
William Lallemand746e6f32021-10-06 10:57:44 +02007276 if (!url_str) {
7277 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7278 return 0;
7279 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007280
William Lallemand10a37362022-03-02 16:18:26 +01007281 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007282
7283 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007284 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007285
7286 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007287 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7288 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7289 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007290 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007291
William Lallemandbd5739e2021-10-28 15:41:38 +02007292 /* a body is available, it will use the request callback */
7293 if (body_str) {
7294 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7295 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007296
William Lallemandbd5739e2021-10-28 15:41:38 +02007297 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007298
William Lallemand746e6f32021-10-06 10:57:44 +02007299 /* free the temporary headers array */
7300 hdrs_i = hdrs;
7301 while (hdrs_i && isttest(hdrs_i->n)) {
7302 istfree(&hdrs_i->n);
7303 istfree(&hdrs_i->v);
7304 hdrs_i++;
7305 }
7306 ha_free(&hdrs);
7307
7308
William Lallemand6137a9e2021-10-26 15:01:53 +02007309 if (ret != ERR_NONE) {
7310 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7311 return 0;
7312 }
7313
William Lallemand6137a9e2021-10-26 15:01:53 +02007314 httpclient_start(hlua_hc->hc);
7315
William Lallemandbd5739e2021-10-28 15:41:38 +02007316 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007317
William Lallemand3956c4e2021-09-21 16:25:15 +02007318 return 0;
7319}
7320
7321/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007322 * Sends an HTTP HEAD request and wait for a response
7323 *
7324 * httpclient:head(url, headers, payload)
7325 */
7326__LJMP static int hlua_httpclient_head(lua_State *L)
7327{
7328 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7329}
7330
7331/*
7332 * Send an HTTP GET request and wait for a response
7333 *
7334 * httpclient:get(url, headers, payload)
7335 */
7336__LJMP static int hlua_httpclient_get(lua_State *L)
7337{
7338 return hlua_httpclient_send(L, HTTP_METH_GET);
7339
7340}
7341
7342/*
7343 * Sends an HTTP PUT request and wait for a response
7344 *
7345 * httpclient:put(url, headers, payload)
7346 */
7347__LJMP static int hlua_httpclient_put(lua_State *L)
7348{
7349 return hlua_httpclient_send(L, HTTP_METH_PUT);
7350}
7351
7352/*
7353 * Send an HTTP POST request and wait for a response
7354 *
7355 * httpclient:post(url, headers, payload)
7356 */
7357__LJMP static int hlua_httpclient_post(lua_State *L)
7358{
7359 return hlua_httpclient_send(L, HTTP_METH_POST);
7360}
7361
7362
7363/*
7364 * Sends an HTTP DELETE request and wait for a response
7365 *
7366 * httpclient:delete(url, headers, payload)
7367 */
7368__LJMP static int hlua_httpclient_delete(lua_State *L)
7369{
7370 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7371}
7372
7373/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007374 *
7375 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007376 * Class TXN
7377 *
7378 *
7379 */
7380
7381/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007382 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007383 */
7384__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7385{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007386 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007387}
7388
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007389__LJMP static int hlua_set_var(lua_State *L)
7390{
7391 struct hlua_txn *htxn;
7392 const char *name;
7393 size_t len;
7394 struct sample smp;
7395
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007396 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7397 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007398
7399 /* It is useles to retrieve the stream, but this function
7400 * runs only in a stream context.
7401 */
7402 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7403 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7404
7405 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007406 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007407 hlua_lua2smp(L, 3, &smp);
7408
7409 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007410 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007411
7412 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7413 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7414 else
7415 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7416
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007417 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007418}
7419
Christopher Faulet85d79c92016-11-09 16:54:56 +01007420__LJMP static int hlua_unset_var(lua_State *L)
7421{
7422 struct hlua_txn *htxn;
7423 const char *name;
7424 size_t len;
7425 struct sample smp;
7426
7427 MAY_LJMP(check_args(L, 2, "unset_var"));
7428
7429 /* It is useles to retrieve the stream, but this function
7430 * runs only in a stream context.
7431 */
7432 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7433 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7434
7435 /* Unset the variable. */
7436 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007437 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7438 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007439}
7440
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007441__LJMP static int hlua_get_var(lua_State *L)
7442{
7443 struct hlua_txn *htxn;
7444 const char *name;
7445 size_t len;
7446 struct sample smp;
7447
7448 MAY_LJMP(check_args(L, 2, "get_var"));
7449
7450 /* It is useles to retrieve the stream, but this function
7451 * runs only in a stream context.
7452 */
7453 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7454 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7455
Willy Tarreau7560dd42016-03-10 16:28:58 +01007456 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007457 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007458 lua_pushnil(L);
7459 return 1;
7460 }
7461
7462 return hlua_smp2lua(L, &smp);
7463}
7464
Willy Tarreau59551662015-03-10 14:23:13 +01007465__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007466{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007467 struct hlua *hlua;
7468
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007469 MAY_LJMP(check_args(L, 2, "set_priv"));
7470
Willy Tarreau87b09662015-04-03 00:22:06 +02007471 /* It is useles to retrieve the stream, but this function
7472 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007473 */
7474 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007475
7476 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007477 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007478 if (!hlua)
7479 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007480
7481 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007482 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007483
7484 /* Get and store new value. */
7485 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7486 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7487
7488 return 0;
7489}
7490
Willy Tarreau59551662015-03-10 14:23:13 +01007491__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007492{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007493 struct hlua *hlua;
7494
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007495 MAY_LJMP(check_args(L, 1, "get_priv"));
7496
Willy Tarreau87b09662015-04-03 00:22:06 +02007497 /* It is useles to retrieve the stream, but this function
7498 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007499 */
7500 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007501
7502 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007503 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007504 if (!hlua) {
7505 lua_pushnil(L);
7506 return 1;
7507 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007508
7509 /* Push configuration index in the stack. */
7510 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7511
7512 return 1;
7513}
7514
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007515/* Create stack entry containing a class TXN. This function
7516 * return 0 if the stack does not contains free slots,
7517 * otherwise it returns 1.
7518 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007519static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007520{
Willy Tarreaude491382015-04-06 11:04:28 +02007521 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007522
7523 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007524 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007525 return 0;
7526
7527 /* NOTE: The allocation never fails. The failure
7528 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007529 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007530 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007531 /* Create the object: obj[0] = userdata. */
7532 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007533 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007534 lua_rawseti(L, -2, 0);
7535
Willy Tarreaude491382015-04-06 11:04:28 +02007536 htxn->s = s;
7537 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007538 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007539 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007540
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007541 /* Create the "f" field that contains a list of fetches. */
7542 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007543 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007544 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007545 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007546
7547 /* Create the "sf" field that contains a list of stringsafe fetches. */
7548 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007549 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007550 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007551 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007552
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007553 /* Create the "c" field that contains a list of converters. */
7554 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007555 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007556 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007557 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007558
7559 /* Create the "sc" field that contains a list of stringsafe converters. */
7560 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007561 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007562 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007563 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007564
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007565 /* Create the "req" field that contains the request channel object. */
7566 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007567 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007568 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007569 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007570
7571 /* Create the "res" field that contains the response channel object. */
7572 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007573 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007574 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007575 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007576
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007577 /* Creates the HTTP object is the current proxy allows http. */
7578 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007579 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007580 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007581 return 0;
7582 }
7583 else
7584 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007585 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007586
Christopher Faulet78c35472020-02-26 17:14:08 +01007587 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7588 /* HTTPMessage object are created when a lua TXN is created from
7589 * a filter context only
7590 */
7591
7592 /* Creates the HTTP-Request object is the current proxy allows http. */
7593 lua_pushstring(L, "http_req");
7594 if (p->mode == PR_MODE_HTTP) {
7595 if (!hlua_http_msg_new(L, &s->txn->req))
7596 return 0;
7597 }
7598 else
7599 lua_pushnil(L);
7600 lua_rawset(L, -3);
7601
7602 /* Creates the HTTP-Response object is the current proxy allows http. */
7603 lua_pushstring(L, "http_res");
7604 if (p->mode == PR_MODE_HTTP) {
7605 if (!hlua_http_msg_new(L, &s->txn->rsp))
7606 return 0;
7607 }
7608 else
7609 lua_pushnil(L);
7610 lua_rawset(L, -3);
7611 }
7612
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007613 /* Pop a class sesison metatable and affect it to the userdata. */
7614 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7615 lua_setmetatable(L, -2);
7616
7617 return 1;
7618}
7619
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007620__LJMP static int hlua_txn_deflog(lua_State *L)
7621{
7622 const char *msg;
7623 struct hlua_txn *htxn;
7624
7625 MAY_LJMP(check_args(L, 2, "deflog"));
7626 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7627 msg = MAY_LJMP(luaL_checkstring(L, 2));
7628
7629 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7630 return 0;
7631}
7632
7633__LJMP static int hlua_txn_log(lua_State *L)
7634{
7635 int level;
7636 const char *msg;
7637 struct hlua_txn *htxn;
7638
7639 MAY_LJMP(check_args(L, 3, "log"));
7640 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7641 level = MAY_LJMP(luaL_checkinteger(L, 2));
7642 msg = MAY_LJMP(luaL_checkstring(L, 3));
7643
7644 if (level < 0 || level >= NB_LOG_LEVELS)
7645 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7646
7647 hlua_sendlog(htxn->s->be, level, msg);
7648 return 0;
7649}
7650
7651__LJMP static int hlua_txn_log_debug(lua_State *L)
7652{
7653 const char *msg;
7654 struct hlua_txn *htxn;
7655
7656 MAY_LJMP(check_args(L, 2, "Debug"));
7657 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7658 msg = MAY_LJMP(luaL_checkstring(L, 2));
7659 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7660 return 0;
7661}
7662
7663__LJMP static int hlua_txn_log_info(lua_State *L)
7664{
7665 const char *msg;
7666 struct hlua_txn *htxn;
7667
7668 MAY_LJMP(check_args(L, 2, "Info"));
7669 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7670 msg = MAY_LJMP(luaL_checkstring(L, 2));
7671 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7672 return 0;
7673}
7674
7675__LJMP static int hlua_txn_log_warning(lua_State *L)
7676{
7677 const char *msg;
7678 struct hlua_txn *htxn;
7679
7680 MAY_LJMP(check_args(L, 2, "Warning"));
7681 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7682 msg = MAY_LJMP(luaL_checkstring(L, 2));
7683 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7684 return 0;
7685}
7686
7687__LJMP static int hlua_txn_log_alert(lua_State *L)
7688{
7689 const char *msg;
7690 struct hlua_txn *htxn;
7691
7692 MAY_LJMP(check_args(L, 2, "Alert"));
7693 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7694 msg = MAY_LJMP(luaL_checkstring(L, 2));
7695 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7696 return 0;
7697}
7698
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007699__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7700{
7701 struct hlua_txn *htxn;
7702 int ll;
7703
7704 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7705 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7706 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7707
7708 if (ll < 0 || ll > 7)
7709 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7710
7711 htxn->s->logs.level = ll;
7712 return 0;
7713}
7714
7715__LJMP static int hlua_txn_set_tos(lua_State *L)
7716{
7717 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007718 int tos;
7719
7720 MAY_LJMP(check_args(L, 2, "set_tos"));
7721 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7722 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7723
Willy Tarreau1a18b542018-12-11 16:37:42 +01007724 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007725 return 0;
7726}
7727
7728__LJMP static int hlua_txn_set_mark(lua_State *L)
7729{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007730 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007731 int mark;
7732
7733 MAY_LJMP(check_args(L, 2, "set_mark"));
7734 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7735 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7736
Lukas Tribus579e3e32019-08-11 18:03:45 +02007737 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007738 return 0;
7739}
7740
Patrick Hemmer268a7072018-05-11 12:52:31 -04007741__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7742{
7743 struct hlua_txn *htxn;
7744
7745 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7746 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7747 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7748 return 0;
7749}
7750
7751__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7752{
7753 struct hlua_txn *htxn;
7754
7755 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7756 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7757 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7758 return 0;
7759}
7760
Christopher Faulet700d9e82020-01-31 12:21:52 +01007761/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007762 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007763 * message and terminate the transaction. It returns 1 on success and 0 on
7764 * error. The Reply must be on top of the stack.
7765 */
7766__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7767{
7768 struct htx *htx;
7769 struct htx_sl *sl;
7770 struct h1m h1m;
7771 const char *status, *reason, *body;
7772 size_t status_len, reason_len, body_len;
7773 int ret, code, flags;
7774
7775 code = 200;
7776 status = "200";
7777 status_len = 3;
7778 ret = lua_getfield(L, -1, "status");
7779 if (ret == LUA_TNUMBER) {
7780 code = lua_tointeger(L, -1);
7781 status = lua_tolstring(L, -1, &status_len);
7782 }
7783 lua_pop(L, 1);
7784
7785 reason = http_get_reason(code);
7786 reason_len = strlen(reason);
7787 ret = lua_getfield(L, -1, "reason");
7788 if (ret == LUA_TSTRING)
7789 reason = lua_tolstring(L, -1, &reason_len);
7790 lua_pop(L, 1);
7791
7792 body = NULL;
7793 body_len = 0;
7794 ret = lua_getfield(L, -1, "body");
7795 if (ret == LUA_TSTRING)
7796 body = lua_tolstring(L, -1, &body_len);
7797 lua_pop(L, 1);
7798
7799 /* Prepare the response before inserting the headers */
7800 h1m_init_res(&h1m);
7801 htx = htx_from_buf(&s->res.buf);
7802 channel_htx_truncate(&s->res, htx);
7803 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7804 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7805 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7806 ist2(status, status_len), ist2(reason, reason_len));
7807 }
7808 else {
7809 flags = HTX_SL_F_IS_RESP;
7810 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7811 ist2(status, status_len), ist2(reason, reason_len));
7812 }
7813 if (!sl)
7814 goto fail;
7815 sl->info.res.status = code;
7816
7817 /* Push in the stack the "headers" entry. */
7818 ret = lua_getfield(L, -1, "headers");
7819 if (ret != LUA_TTABLE)
7820 goto skip_headers;
7821
7822 lua_pushnil(L);
7823 while (lua_next(L, -2) != 0) {
7824 struct ist name, value;
7825 const char *n, *v;
7826 size_t nlen, vlen;
7827
7828 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7829 /* Skip element if the key is not a string or if the value is not a table */
7830 goto next_hdr;
7831 }
7832
7833 n = lua_tolstring(L, -2, &nlen);
7834 name = ist2(n, nlen);
7835 if (isteqi(name, ist("content-length"))) {
7836 /* Always skip content-length header. It will be added
7837 * later with the correct len
7838 */
7839 goto next_hdr;
7840 }
7841
7842 /* Loop on header's values */
7843 lua_pushnil(L);
7844 while (lua_next(L, -2)) {
7845 if (!lua_isstring(L, -1)) {
7846 /* Skip the value if it is not a string */
7847 goto next_value;
7848 }
7849
7850 v = lua_tolstring(L, -1, &vlen);
7851 value = ist2(v, vlen);
7852
7853 if (isteqi(name, ist("transfer-encoding")))
7854 h1_parse_xfer_enc_header(&h1m, value);
7855 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7856 goto fail;
7857
7858 next_value:
7859 lua_pop(L, 1);
7860 }
7861
7862 next_hdr:
7863 lua_pop(L, 1);
7864 }
7865 skip_headers:
7866 lua_pop(L, 1);
7867
7868 /* Update h1m flags: CLEN is set if CHNK is not present */
7869 if (!(h1m.flags & H1_MF_CHNK)) {
7870 const char *clen = ultoa(body_len);
7871
7872 h1m.flags |= H1_MF_CLEN;
7873 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7874 goto fail;
7875 }
7876 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7877 h1m.flags |= H1_MF_XFER_LEN;
7878
7879 /* Update HTX start-line flags */
7880 if (h1m.flags & H1_MF_XFER_ENC)
7881 flags |= HTX_SL_F_XFER_ENC;
7882 if (h1m.flags & H1_MF_XFER_LEN) {
7883 flags |= HTX_SL_F_XFER_LEN;
7884 if (h1m.flags & H1_MF_CHNK)
7885 flags |= HTX_SL_F_CHNK;
7886 else if (h1m.flags & H1_MF_CLEN)
7887 flags |= HTX_SL_F_CLEN;
7888 if (h1m.body_len == 0)
7889 flags |= HTX_SL_F_BODYLESS;
7890 }
7891 sl->flags |= flags;
7892
7893
7894 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007895 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007896 goto fail;
7897
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007898 htx->flags |= HTX_FL_EOM;
7899
Christopher Faulet700d9e82020-01-31 12:21:52 +01007900 /* Now, forward the response and terminate the transaction */
7901 s->txn->status = code;
7902 htx_to_buf(htx, &s->res.buf);
7903 if (!http_forward_proxy_resp(s, 1))
7904 goto fail;
7905
7906 return 1;
7907
7908 fail:
7909 channel_htx_truncate(&s->res, htx);
7910 return 0;
7911}
7912
7913/* Terminate a transaction if called from a lua action. For TCP streams,
7914 * processing is just aborted. Nothing is returned to the client and all
7915 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7916 * is forwarded to the client before terminating the transaction. On success,
7917 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7918 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7919 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007920 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007921__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007922{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007923 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007924 struct stream *s;
7925 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007926
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007927 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007928
Christopher Faulet700d9e82020-01-31 12:21:52 +01007929 /* If the flags NOTERM is set, we cannot terminate the session, so we
7930 * just end the execution of the current lua code. */
7931 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007932 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007933
Christopher Faulet700d9e82020-01-31 12:21:52 +01007934 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007935 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007936 struct channel *req = &s->req;
7937 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007938
Christopher Faulet700d9e82020-01-31 12:21:52 +01007939 channel_auto_read(req);
7940 channel_abort(req);
7941 channel_auto_close(req);
7942 channel_erase(req);
7943
7944 res->wex = tick_add_ifset(now_ms, res->wto);
7945 channel_auto_read(res);
7946 channel_auto_close(res);
7947 channel_shutr_now(res);
7948
7949 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7950 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007951 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007952
Christopher Faulet700d9e82020-01-31 12:21:52 +01007953 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7954 /* No reply or invalid reply */
7955 s->txn->status = 0;
7956 http_reply_and_close(s, 0, NULL);
7957 }
7958 else {
7959 /* Remove extra args to have the reply on top of the stack */
7960 if (lua_gettop(L) > 2)
7961 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007962
Christopher Faulet700d9e82020-01-31 12:21:52 +01007963 if (!hlua_txn_forward_reply(L, s)) {
7964 if (!(s->flags & SF_ERR_MASK))
7965 s->flags |= SF_ERR_PRXCOND;
7966 lua_pushinteger(L, ACT_RET_ERR);
7967 WILL_LJMP(hlua_done(L));
7968 return 0; /* Never reached */
7969 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007970 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007971
Christopher Faulet700d9e82020-01-31 12:21:52 +01007972 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7973 if (htxn->dir == SMP_OPT_DIR_REQ) {
7974 /* let's log the request time */
7975 s->logs.tv_request = now;
7976 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007977 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007978 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007979
Christopher Faulet700d9e82020-01-31 12:21:52 +01007980 done:
7981 if (!(s->flags & SF_ERR_MASK))
7982 s->flags |= SF_ERR_LOCAL;
7983 if (!(s->flags & SF_FINST_MASK))
7984 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007985
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007986 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7987 lua_pushinteger(L, -1);
7988 else
7989 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007990 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007991 return 0;
7992}
7993
Christopher Faulet700d9e82020-01-31 12:21:52 +01007994/*
7995 *
7996 *
7997 * Class REPLY
7998 *
7999 *
8000 */
8001
8002/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8003 * free slots, the function fails and returns 0;
8004 */
8005static int hlua_txn_reply_new(lua_State *L)
8006{
8007 struct hlua_txn *htxn;
8008 const char *reason, *body = NULL;
8009 int ret, status;
8010
8011 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008012 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008013 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8014 WILL_LJMP(lua_error(L));
8015 }
8016
8017 /* Default value */
8018 status = 200;
8019 reason = http_get_reason(status);
8020
8021 if (lua_istable(L, 2)) {
8022 /* load status and reason from the table argument at index 2 */
8023 ret = lua_getfield(L, 2, "status");
8024 if (ret == LUA_TNIL)
8025 goto reason;
8026 else if (ret != LUA_TNUMBER) {
8027 /* invalid status: ignore the reason */
8028 goto body;
8029 }
8030 status = lua_tointeger(L, -1);
8031
8032 reason:
8033 lua_pop(L, 1); /* restore the stack: remove status */
8034 ret = lua_getfield(L, 2, "reason");
8035 if (ret == LUA_TSTRING)
8036 reason = lua_tostring(L, -1);
8037
8038 body:
8039 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8040 ret = lua_getfield(L, 2, "body");
8041 if (ret == LUA_TSTRING)
8042 body = lua_tostring(L, -1);
8043 lua_pop(L, 1); /* restore the stack: remove body */
8044 }
8045
8046 /* Create the Reply table */
8047 lua_newtable(L);
8048
8049 /* Add status element */
8050 lua_pushstring(L, "status");
8051 lua_pushinteger(L, status);
8052 lua_settable(L, -3);
8053
8054 /* Add reason element */
8055 reason = http_get_reason(status);
8056 lua_pushstring(L, "reason");
8057 lua_pushstring(L, reason);
8058 lua_settable(L, -3);
8059
8060 /* Add body element, nil if undefined */
8061 lua_pushstring(L, "body");
8062 if (body)
8063 lua_pushstring(L, body);
8064 else
8065 lua_pushnil(L);
8066 lua_settable(L, -3);
8067
8068 /* Add headers element */
8069 lua_pushstring(L, "headers");
8070 lua_newtable(L);
8071
8072 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8073 if (lua_istable(L, 2)) {
8074 /* load headers from the table argument at index 2. If it is a table, copy it. */
8075 ret = lua_getfield(L, 2, "headers");
8076 if (ret == LUA_TTABLE) {
8077 /* stack: [ ... <headers:table>, <table> ] */
8078 lua_pushnil(L);
8079 while (lua_next(L, -2) != 0) {
8080 /* stack: [ ... <headers:table>, <table>, k, v] */
8081 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8082 /* invalid value type, skip it */
8083 lua_pop(L, 1);
8084 continue;
8085 }
8086
8087
8088 /* Duplicate the key and swap it with the value. */
8089 lua_pushvalue(L, -2);
8090 lua_insert(L, -2);
8091 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8092
8093 lua_newtable(L);
8094 lua_insert(L, -2);
8095 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8096
8097 if (lua_isstring(L, -1)) {
8098 /* push the value in the inner table */
8099 lua_rawseti(L, -2, 1);
8100 }
8101 else { /* table */
8102 lua_pushnil(L);
8103 while (lua_next(L, -2) != 0) {
8104 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8105 if (!lua_isstring(L, -1)) {
8106 /* invalid value type, skip it*/
8107 lua_pop(L, 1);
8108 continue;
8109 }
8110 /* push the value in the inner table */
8111 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8112 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8113 }
8114 lua_pop(L, 1);
8115 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8116 }
8117
8118 /* push (k,v) on the stack in the headers table:
8119 * stack: [ ... <headers:table>, <table>, k, k, v ]
8120 */
8121 lua_settable(L, -5);
8122 /* stack: [ ... <headers:table>, <table>, k ] */
8123 }
8124 }
8125 lua_pop(L, 1);
8126 }
8127 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8128 lua_settable(L, -3);
8129 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8130
8131 /* Pop a class sesison metatable and affect it to the userdata. */
8132 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8133 lua_setmetatable(L, -2);
8134 return 1;
8135}
8136
8137/* Set the reply status code, and optionally the reason. If no reason is
8138 * provided, the default one corresponding to the status code is used.
8139 */
8140__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8141{
8142 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8143 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8144
8145 /* First argument (self) must be a table */
8146 luaL_checktype(L, 1, LUA_TTABLE);
8147
8148 if (status < 100 || status > 599) {
8149 lua_pushboolean(L, 0);
8150 return 1;
8151 }
8152 if (!reason)
8153 reason = http_get_reason(status);
8154
8155 lua_pushinteger(L, status);
8156 lua_setfield(L, 1, "status");
8157
8158 lua_pushstring(L, reason);
8159 lua_setfield(L, 1, "reason");
8160
8161 lua_pushboolean(L, 1);
8162 return 1;
8163}
8164
8165/* Add a header into the reply object. Each header name is associated to an
8166 * array of values in the "headers" table. If the header name is not found, a
8167 * new entry is created.
8168 */
8169__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8170{
8171 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8172 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8173 int ret;
8174
8175 /* First argument (self) must be a table */
8176 luaL_checktype(L, 1, LUA_TTABLE);
8177
8178 /* Push in the stack the "headers" entry. */
8179 ret = lua_getfield(L, 1, "headers");
8180 if (ret != LUA_TTABLE) {
8181 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8182 WILL_LJMP(lua_error(L));
8183 }
8184
8185 /* check if the header is already registered. If not, register it. */
8186 ret = lua_getfield(L, -1, name);
8187 if (ret == LUA_TNIL) {
8188 /* Entry not found. */
8189 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8190
8191 /* Insert the new header name in the array in the top of the stack.
8192 * It left the new array in the top of the stack.
8193 */
8194 lua_newtable(L);
8195 lua_pushstring(L, name);
8196 lua_pushvalue(L, -2);
8197 lua_settable(L, -4);
8198 }
8199 else if (ret != LUA_TTABLE) {
8200 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8201 WILL_LJMP(lua_error(L));
8202 }
8203
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008204 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008205 * the header value as new entry.
8206 */
8207 lua_pushstring(L, value);
8208 ret = lua_rawlen(L, -2);
8209 lua_rawseti(L, -2, ret + 1);
8210
8211 lua_pushboolean(L, 1);
8212 return 1;
8213}
8214
8215/* Remove all occurrences of a given header name. */
8216__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8217{
8218 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8219 int ret;
8220
8221 /* First argument (self) must be a table */
8222 luaL_checktype(L, 1, LUA_TTABLE);
8223
8224 /* Push in the stack the "headers" entry. */
8225 ret = lua_getfield(L, 1, "headers");
8226 if (ret != LUA_TTABLE) {
8227 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8228 WILL_LJMP(lua_error(L));
8229 }
8230
8231 lua_pushstring(L, name);
8232 lua_pushnil(L);
8233 lua_settable(L, -3);
8234
8235 lua_pushboolean(L, 1);
8236 return 1;
8237}
8238
8239/* Set the reply's body. Overwrite any existing entry. */
8240__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8241{
8242 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8243
8244 /* First argument (self) must be a table */
8245 luaL_checktype(L, 1, LUA_TTABLE);
8246
8247 lua_pushstring(L, payload);
8248 lua_setfield(L, 1, "body");
8249
8250 lua_pushboolean(L, 1);
8251 return 1;
8252}
8253
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008254__LJMP static int hlua_log(lua_State *L)
8255{
8256 int level;
8257 const char *msg;
8258
8259 MAY_LJMP(check_args(L, 2, "log"));
8260 level = MAY_LJMP(luaL_checkinteger(L, 1));
8261 msg = MAY_LJMP(luaL_checkstring(L, 2));
8262
8263 if (level < 0 || level >= NB_LOG_LEVELS)
8264 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8265
8266 hlua_sendlog(NULL, level, msg);
8267 return 0;
8268}
8269
8270__LJMP static int hlua_log_debug(lua_State *L)
8271{
8272 const char *msg;
8273
8274 MAY_LJMP(check_args(L, 1, "debug"));
8275 msg = MAY_LJMP(luaL_checkstring(L, 1));
8276 hlua_sendlog(NULL, LOG_DEBUG, msg);
8277 return 0;
8278}
8279
8280__LJMP static int hlua_log_info(lua_State *L)
8281{
8282 const char *msg;
8283
8284 MAY_LJMP(check_args(L, 1, "info"));
8285 msg = MAY_LJMP(luaL_checkstring(L, 1));
8286 hlua_sendlog(NULL, LOG_INFO, msg);
8287 return 0;
8288}
8289
8290__LJMP static int hlua_log_warning(lua_State *L)
8291{
8292 const char *msg;
8293
8294 MAY_LJMP(check_args(L, 1, "warning"));
8295 msg = MAY_LJMP(luaL_checkstring(L, 1));
8296 hlua_sendlog(NULL, LOG_WARNING, msg);
8297 return 0;
8298}
8299
8300__LJMP static int hlua_log_alert(lua_State *L)
8301{
8302 const char *msg;
8303
8304 MAY_LJMP(check_args(L, 1, "alert"));
8305 msg = MAY_LJMP(luaL_checkstring(L, 1));
8306 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008307 return 0;
8308}
8309
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008310__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008311{
8312 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008313 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008314 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008315 return 0;
8316}
8317
8318__LJMP static int hlua_sleep(lua_State *L)
8319{
8320 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008321 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008322
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008323 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008324
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008325 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008326 wakeup_ms = tick_add(now_ms, delay);
8327 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008328
Willy Tarreau9635e032018-10-16 17:52:55 +02008329 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008330 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008331}
8332
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008333__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008334{
8335 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008336 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008337
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008338 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008339
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008340 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008341 wakeup_ms = tick_add(now_ms, delay);
8342 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008343
Willy Tarreau9635e032018-10-16 17:52:55 +02008344 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008345 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008346}
8347
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008348/* This functionis an LUA binding. it permits to give back
8349 * the hand at the HAProxy scheduler. It is used when the
8350 * LUA processing consumes a lot of time.
8351 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008352__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008353{
8354 return 0;
8355}
8356
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008357__LJMP static int hlua_yield(lua_State *L)
8358{
Willy Tarreau9635e032018-10-16 17:52:55 +02008359 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008360 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008361}
8362
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008363/* This function change the nice of the currently executed
8364 * task. It is used set low or high priority at the current
8365 * task.
8366 */
Willy Tarreau59551662015-03-10 14:23:13 +01008367__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008368{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008369 struct hlua *hlua;
8370 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008371
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008372 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008373 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008374
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008375 /* Get hlua struct, or NULL if we execute from main lua state */
8376 hlua = hlua_gethlua(L);
8377
8378 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008379 if (!hlua || !hlua->task)
8380 return 0;
8381
8382 if (nice < -1024)
8383 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008384 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008385 nice = 1024;
8386
8387 hlua->task->nice = nice;
8388 return 0;
8389}
8390
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008391/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008392 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8393 * return an E_AGAIN signal, the emmiter of this signal must set a
8394 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008395 *
8396 * Task wrapper are longjmp safe because the only one Lua code
8397 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008398 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008399struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008400{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008401 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008402 enum hlua_exec status;
8403
Christopher Faulet5bc99722018-04-25 10:34:45 +02008404 if (task->thread_mask == MAX_THREADS_MASK)
8405 task_set_affinity(task, tid_bit);
8406
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008407 /* If it is the first call to the task, we must initialize the
8408 * execution timeouts.
8409 */
8410 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008411 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008412
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008413 /* Execute the Lua code. */
8414 status = hlua_ctx_resume(hlua, 1);
8415
8416 switch (status) {
8417 /* finished or yield */
8418 case HLUA_E_OK:
8419 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008420 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008421 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008422 break;
8423
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008424 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008425 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008426 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008427 break;
8428
8429 /* finished with error. */
8430 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008431 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008432 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008433 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008434 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008435 break;
8436
8437 case HLUA_E_ERR:
8438 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008439 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008440 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008441 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008442 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008443 break;
8444 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008445 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008446}
8447
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008448/* This function is an LUA binding that register LUA function to be
8449 * executed after the HAProxy configuration parsing and before the
8450 * HAProxy scheduler starts. This function expect only one LUA
8451 * argument that is a function. This function returns nothing, but
8452 * throws if an error is encountered.
8453 */
8454__LJMP static int hlua_register_init(lua_State *L)
8455{
8456 struct hlua_init_function *init;
8457 int ref;
8458
8459 MAY_LJMP(check_args(L, 1, "register_init"));
8460
8461 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8462
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008463 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008464 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008465 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008466
8467 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008468 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008469 return 0;
8470}
8471
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008472/* This functio is an LUA binding. It permits to register a task
8473 * executed in parallel of the main HAroxy activity. The task is
8474 * created and it is set in the HAProxy scheduler. It can be called
8475 * from the "init" section, "post init" or during the runtime.
8476 *
8477 * Lua prototype:
8478 *
8479 * <none> core.register_task(<function>)
8480 */
8481static int hlua_register_task(lua_State *L)
8482{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008483 struct hlua *hlua = NULL;
8484 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008485 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008486 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008487
8488 MAY_LJMP(check_args(L, 1, "register_task"));
8489
8490 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8491
Thierry Fournier75fc0292020-11-28 13:18:56 +01008492 /* Get the reference state. If the reference is NULL, L is the master
8493 * state, otherwise hlua->T is.
8494 */
8495 hlua = hlua_gethlua(L);
8496 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008497 /* we are in runtime processing */
8498 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008499 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008500 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008501 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008502
Willy Tarreaubafbe012017-11-24 17:34:44 +01008503 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008504 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008505 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008506 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008507
Thierry Fournier59f11be2020-11-29 00:37:41 +01008508 /* We are in the common lua state, execute the task anywhere,
8509 * otherwise, inherit the current thread identifier
8510 */
8511 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008512 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008513 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008514 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008515 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008516 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008517
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008518 task->context = hlua;
8519 task->process = hlua_process_task;
8520
Thierry Fournier021d9862020-11-28 23:42:03 +01008521 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008522 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008523
8524 /* Restore the function in the stack. */
8525 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8526 hlua->nargs = 0;
8527
8528 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008529 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008530
8531 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008532
8533 alloc_error:
8534 task_destroy(task);
8535 hlua_ctx_destroy(hlua);
8536 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8537 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008538}
8539
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008540/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8541 * doesn't allow "yield" functions because the HAProxy engine cannot
8542 * resume converters.
8543 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008544static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008545{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008546 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008547 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008548 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008549
Willy Tarreaube508f12016-03-10 11:47:01 +01008550 if (!stream)
8551 return 0;
8552
Willy Tarreau87b09662015-04-03 00:22:06 +02008553 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008554 * Lua context can be not initialized. This behavior
8555 * permits to save performances because a systematic
8556 * Lua initialization cause 5% performances loss.
8557 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008558 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008559 struct hlua *hlua;
8560
8561 hlua = pool_alloc(pool_head_hlua);
8562 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008563 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8564 return 0;
8565 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008566 HLUA_INIT(hlua);
8567 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008568 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008569 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8570 return 0;
8571 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008572 }
8573
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008574 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008575 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008576
8577 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008578 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008579 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8580 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008581 else
8582 error = "critical error";
8583 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008584 return 0;
8585 }
8586
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008587 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008588 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008589 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008590 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008591 return 0;
8592 }
8593
8594 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008595 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008596
8597 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008598 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008599 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008600 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008601 return 0;
8602 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008603 hlua_smp2lua(stream->hlua->T, smp);
8604 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008605
8606 /* push keywords in the stack. */
8607 if (arg_p) {
8608 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008609 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008610 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008611 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008612 return 0;
8613 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008614 hlua_arg2lua(stream->hlua->T, arg_p);
8615 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008616 }
8617 }
8618
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008619 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008620 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008621
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008622 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008623 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008624 }
8625
8626 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008627 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008628 /* finished. */
8629 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008630 /* If the stack is empty, the function fails. */
8631 if (lua_gettop(stream->hlua->T) <= 0)
8632 return 0;
8633
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008634 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008635 hlua_lua2smp(stream->hlua->T, -1, smp);
8636 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008637 return 1;
8638
8639 /* yield. */
8640 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008641 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008642 return 0;
8643
8644 /* finished with error. */
8645 case HLUA_E_ERRMSG:
8646 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008647 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008648 fcn->name, lua_tostring(stream->hlua->T, -1));
8649 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008650 return 0;
8651
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008652 case HLUA_E_ETMOUT:
8653 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8654 return 0;
8655
8656 case HLUA_E_NOMEM:
8657 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8658 return 0;
8659
8660 case HLUA_E_YIELD:
8661 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8662 return 0;
8663
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008664 case HLUA_E_ERR:
8665 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008666 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008667 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008668
8669 default:
8670 return 0;
8671 }
8672}
8673
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008674/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8675 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008676 * resume sample-fetches. This function will be called by the sample
8677 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008678 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008679static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8680 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008681{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008682 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008683 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008684 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008685 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008686
Willy Tarreaube508f12016-03-10 11:47:01 +01008687 if (!stream)
8688 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008689
Willy Tarreau87b09662015-04-03 00:22:06 +02008690 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008691 * Lua context can be not initialized. This behavior
8692 * permits to save performances because a systematic
8693 * Lua initialization cause 5% performances loss.
8694 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008695 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008696 struct hlua *hlua;
8697
8698 hlua = pool_alloc(pool_head_hlua);
8699 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008700 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8701 return 0;
8702 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008703 hlua->T = NULL;
8704 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008705 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008706 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8707 return 0;
8708 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008709 }
8710
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008711 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008712 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008713
8714 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008715 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008716 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8717 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008718 else
8719 error = "critical error";
8720 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008721 return 0;
8722 }
8723
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008724 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008725 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008726 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008727 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008728 return 0;
8729 }
8730
8731 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008732 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008733
8734 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008735 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008736 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008737 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008738 return 0;
8739 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008740 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008741
8742 /* push keywords in the stack. */
8743 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8744 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008745 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008746 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008747 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008748 return 0;
8749 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008750 hlua_arg2lua(stream->hlua->T, arg_p);
8751 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008752 }
8753
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008754 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008755 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008756
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008757 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008758 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008759 }
8760
8761 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008762 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008763 /* finished. */
8764 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008765 /* If the stack is empty, the function fails. */
8766 if (lua_gettop(stream->hlua->T) <= 0)
8767 return 0;
8768
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008769 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008770 hlua_lua2smp(stream->hlua->T, -1, smp);
8771 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008772
8773 /* Set the end of execution flag. */
8774 smp->flags &= ~SMP_F_MAY_CHANGE;
8775 return 1;
8776
8777 /* yield. */
8778 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008779 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008780 return 0;
8781
8782 /* finished with error. */
8783 case HLUA_E_ERRMSG:
8784 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008785 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008786 fcn->name, lua_tostring(stream->hlua->T, -1));
8787 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008788 return 0;
8789
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008790 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008791 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8792 return 0;
8793
8794 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008795 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8796 return 0;
8797
8798 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008799 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8800 return 0;
8801
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008802 case HLUA_E_ERR:
8803 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008804 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008805 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008806
8807 default:
8808 return 0;
8809 }
8810}
8811
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008812/* This function is an LUA binding used for registering
8813 * "sample-conv" functions. It expects a converter name used
8814 * in the haproxy configuration file, and an LUA function.
8815 */
8816__LJMP static int hlua_register_converters(lua_State *L)
8817{
8818 struct sample_conv_kw_list *sck;
8819 const char *name;
8820 int ref;
8821 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008822 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008823 struct sample_conv *sc;
8824 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008825
8826 MAY_LJMP(check_args(L, 2, "register_converters"));
8827
8828 /* First argument : converter name. */
8829 name = MAY_LJMP(luaL_checkstring(L, 1));
8830
8831 /* Second argument : lua function. */
8832 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8833
Thierry Fournierf67442e2020-11-28 20:41:07 +01008834 /* Check if the converter is already registered */
8835 trash = get_trash_chunk();
8836 chunk_printf(trash, "lua.%s", name);
8837 sc = find_sample_conv(trash->area, trash->data);
8838 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008839 fcn = sc->private;
8840 if (fcn->function_ref[hlua_state_id] != -1) {
8841 ha_warning("Trying to register converter 'lua.%s' more than once. "
8842 "This will become a hard error in version 2.5.\n", name);
8843 }
8844 fcn->function_ref[hlua_state_id] = ref;
8845 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008846 }
8847
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008848 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008849 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008850 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008851 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008852 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008853 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008854 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008855
8856 /* Fill fcn. */
8857 fcn->name = strdup(name);
8858 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008859 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008860 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008861
8862 /* List head */
8863 sck->list.n = sck->list.p = NULL;
8864
8865 /* converter keyword. */
8866 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008867 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008868 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008869 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008870
8871 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8872 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008873 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 +01008874 sck->kw[0].val_args = NULL;
8875 sck->kw[0].in_type = SMP_T_STR;
8876 sck->kw[0].out_type = SMP_T_STR;
8877 sck->kw[0].private = fcn;
8878
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008879 /* Register this new converter */
8880 sample_register_convs(sck);
8881
8882 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008883
8884 alloc_error:
8885 release_hlua_function(fcn);
8886 ha_free(&sck);
8887 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8888 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008889}
8890
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008891/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008892 * "sample-fetch" functions. It expects a converter name used
8893 * in the haproxy configuration file, and an LUA function.
8894 */
8895__LJMP static int hlua_register_fetches(lua_State *L)
8896{
8897 const char *name;
8898 int ref;
8899 int len;
8900 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008901 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008902 struct sample_fetch *sf;
8903 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008904
8905 MAY_LJMP(check_args(L, 2, "register_fetches"));
8906
8907 /* First argument : sample-fetch name. */
8908 name = MAY_LJMP(luaL_checkstring(L, 1));
8909
8910 /* Second argument : lua function. */
8911 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8912
Thierry Fournierf67442e2020-11-28 20:41:07 +01008913 /* Check if the sample-fetch is already registered */
8914 trash = get_trash_chunk();
8915 chunk_printf(trash, "lua.%s", name);
8916 sf = find_sample_fetch(trash->area, trash->data);
8917 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008918 fcn = sf->private;
8919 if (fcn->function_ref[hlua_state_id] != -1) {
8920 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8921 "This will become a hard error in version 2.5.\n", name);
8922 }
8923 fcn->function_ref[hlua_state_id] = ref;
8924 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008925 }
8926
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008927 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008928 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008929 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008930 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008931 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008932 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008933 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008934
8935 /* Fill fcn. */
8936 fcn->name = strdup(name);
8937 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008938 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008939 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008940
8941 /* List head */
8942 sfk->list.n = sfk->list.p = NULL;
8943
8944 /* sample-fetch keyword. */
8945 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008946 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008947 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008948 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008949
8950 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8951 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008952 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 +01008953 sfk->kw[0].val_args = NULL;
8954 sfk->kw[0].out_type = SMP_T_STR;
8955 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8956 sfk->kw[0].val = 0;
8957 sfk->kw[0].private = fcn;
8958
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008959 /* Register this new fetch. */
8960 sample_register_fetches(sfk);
8961
8962 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008963
8964 alloc_error:
8965 release_hlua_function(fcn);
8966 ha_free(&sfk);
8967 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8968 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008969}
8970
Christopher Faulet501465d2020-02-26 14:54:16 +01008971/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008972 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008973__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008974{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008975 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008976 unsigned int delay;
8977 unsigned int wakeup_ms;
8978
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008979 /* Get hlua struct, or NULL if we execute from main lua state */
8980 hlua = hlua_gethlua(L);
8981 if (!hlua) {
8982 return 0;
8983 }
8984
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008985 MAY_LJMP(check_args(L, 1, "wake_time"));
8986
8987 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8988 wakeup_ms = tick_add(now_ms, delay);
8989 hlua->wake_time = wakeup_ms;
8990 return 0;
8991}
8992
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008993/* This function is a wrapper to execute each LUA function declared as an action
8994 * wrapper during the initialisation period. This function may return any
8995 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8996 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8997 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008998 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008999static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009000 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009001{
9002 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009003 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009004 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009005 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009006
9007 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009008 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9009 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9010 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9011 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009012 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009013 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009014 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009015 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009016
Willy Tarreau87b09662015-04-03 00:22:06 +02009017 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009018 * Lua context can be not initialized. This behavior
9019 * permits to save performances because a systematic
9020 * Lua initialization cause 5% performances loss.
9021 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009022 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009023 struct hlua *hlua;
9024
9025 hlua = pool_alloc(pool_head_hlua);
9026 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009027 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009028 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009029 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009030 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009031 HLUA_INIT(hlua);
9032 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009033 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 +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 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009038 }
9039
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009040 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009041 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009042
9043 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009044 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009045 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9046 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009047 else
9048 error = "critical error";
9049 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009050 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009051 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009052 }
9053
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009054 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009055 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009056 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009057 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009058 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009059 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009060 }
9061
9062 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009063 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 +01009064
Willy Tarreau87b09662015-04-03 00:22:06 +02009065 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009066 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009067 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009068 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009069 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009070 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009071 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009072 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009073
9074 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009075 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009076 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009077 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009078 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009079 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009080 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009081 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009082 lua_pushstring(s->hlua->T, *arg);
9083 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009084 }
9085
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009086 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009087 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009088
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009089 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009090 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009091 }
9092
9093 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009094 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009095 /* finished. */
9096 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009097 /* Catch the return value */
9098 if (lua_gettop(s->hlua->T) > 0)
9099 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009100
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009101 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009102 if (act_ret == ACT_RET_YIELD) {
9103 if (flags & ACT_OPT_FINAL)
9104 goto err_yield;
9105
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009106 if (dir == SMP_OPT_DIR_REQ)
9107 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9108 s->hlua->wake_time);
9109 else
9110 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9111 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009112 }
9113 goto end;
9114
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009115 /* yield. */
9116 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009117 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009118 if (dir == SMP_OPT_DIR_REQ)
9119 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9120 s->hlua->wake_time);
9121 else
9122 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9123 s->hlua->wake_time);
9124
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009125 /* Some actions can be wake up when a "write" event
9126 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009127 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009128 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009129 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009130 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009131 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009132 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009133 act_ret = ACT_RET_YIELD;
9134 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009135
9136 /* finished with error. */
9137 case HLUA_E_ERRMSG:
9138 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009139 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009140 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009141 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009142 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009143
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009144 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009145 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009146 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009147
9148 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009149 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009150 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009151
9152 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009153 err_yield:
9154 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009155 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009156 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009157 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009158
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009159 case HLUA_E_ERR:
9160 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009161 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009162 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009163
9164 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009165 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009166 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009167
9168 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009169 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009170 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009171 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009172}
9173
Willy Tarreau144f84a2021-03-02 16:09:26 +01009174struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009175{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009176 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009177
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009178 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009179 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009180 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009181}
9182
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009183static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009184{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009185 struct stream_interface *si = cs_si(ctx->owner);
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009186 struct stream *strm = si_strm(si);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009187 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009188 struct task *task;
9189 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009190 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009191
Willy Tarreaubafbe012017-11-24 17:34:44 +01009192 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009193 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009194 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009195 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009196 return 0;
9197 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009198 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009199 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009200 ctx->ctx.hlua_apptcp.flags = 0;
9201
9202 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009203 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009204 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009205 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009206 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009207 return 0;
9208 }
9209 task->nice = 0;
9210 task->context = ctx;
9211 task->process = hlua_applet_wakeup;
9212 ctx->ctx.hlua_apptcp.task = task;
9213
9214 /* In the execution wrappers linked with a stream, the
9215 * Lua context can be not initialized. This behavior
9216 * permits to save performances because a systematic
9217 * Lua initialization cause 5% performances loss.
9218 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009219 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009220 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009221 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009222 return 0;
9223 }
9224
9225 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009226 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009227
9228 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009229 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009230 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9231 error = lua_tostring(hlua->T, -1);
9232 else
9233 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009234 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009235 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009236 return 0;
9237 }
9238
9239 /* Check stack available size. */
9240 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009241 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009242 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009243 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009244 return 0;
9245 }
9246
9247 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009248 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009249
9250 /* Create and and push object stream in the stack. */
9251 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009252 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009253 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009254 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009255 return 0;
9256 }
9257 hlua->nargs = 1;
9258
9259 /* push keywords in the stack. */
9260 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9261 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009262 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009263 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009264 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009265 return 0;
9266 }
9267 lua_pushstring(hlua->T, *arg);
9268 hlua->nargs++;
9269 }
9270
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009271 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009272
9273 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009274 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01009275 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009276
9277 return 1;
9278}
9279
Willy Tarreau60409db2019-08-21 14:14:50 +02009280void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009281{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009282 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009283 struct stream *strm = si_strm(si);
9284 struct channel *res = si_ic(si);
9285 struct act_rule *rule = ctx->rule;
9286 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009287 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009288
9289 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02009290 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
9291 /* eat the whole request */
9292 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009293 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009294 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009295
9296 /* If the stream is disconnect or closed, ldo nothing. */
9297 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9298 return;
9299
9300 /* Execute the function. */
9301 switch (hlua_ctx_resume(hlua, 1)) {
9302 /* finished. */
9303 case HLUA_E_OK:
9304 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9305
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009306 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02009307 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009308 res->flags |= CF_READ_NULL;
9309 si_shutr(si);
9310 return;
9311
9312 /* yield. */
9313 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009314 if (hlua->wake_time != TICK_ETERNITY)
9315 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009316 return;
9317
9318 /* finished with error. */
9319 case HLUA_E_ERRMSG:
9320 /* Display log. */
9321 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009322 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009323 lua_pop(hlua->T, 1);
9324 goto error;
9325
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009326 case HLUA_E_ETMOUT:
9327 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009328 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009329 goto error;
9330
9331 case HLUA_E_NOMEM:
9332 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009333 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009334 goto error;
9335
9336 case HLUA_E_YIELD: /* unexpected */
9337 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009338 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009339 goto error;
9340
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009341 case HLUA_E_ERR:
9342 /* Display log. */
9343 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009344 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009345 goto error;
9346
9347 default:
9348 goto error;
9349 }
9350
9351error:
9352
9353 /* For all other cases, just close the stream. */
9354 si_shutw(si);
9355 si_shutr(si);
9356 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9357}
9358
9359static void hlua_applet_tcp_release(struct appctx *ctx)
9360{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009361 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009362 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009363 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009364 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009365}
9366
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009367/* The function returns 1 if the initialisation is complete, 0 if
9368 * an errors occurs and -1 if more data are required for initializing
9369 * the applet.
9370 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009371static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009372{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009373 struct stream_interface *si = cs_si(ctx->owner);
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009374 struct stream *strm = si_strm(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009375 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009376 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009377 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009378 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009379 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009380
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009381 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009382 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009383 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009384 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009385 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009386 return 0;
9387 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009388 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009389 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009390 ctx->ctx.hlua_apphttp.left_bytes = -1;
9391 ctx->ctx.hlua_apphttp.flags = 0;
9392
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009393 if (txn->req.flags & HTTP_MSGF_VER_11)
9394 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
9395
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009396 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009397 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009398 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009399 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009400 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009401 return 0;
9402 }
9403 task->nice = 0;
9404 task->context = ctx;
9405 task->process = hlua_applet_wakeup;
9406 ctx->ctx.hlua_apphttp.task = task;
9407
9408 /* In the execution wrappers linked with a stream, the
9409 * Lua context can be not initialized. This behavior
9410 * permits to save performances because a systematic
9411 * Lua initialization cause 5% performances loss.
9412 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009413 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009414 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009415 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009416 return 0;
9417 }
9418
9419 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009420 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009421
9422 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009423 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009424 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9425 error = lua_tostring(hlua->T, -1);
9426 else
9427 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009428 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009429 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009430 return 0;
9431 }
9432
9433 /* Check stack available size. */
9434 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009435 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009436 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009437 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009438 return 0;
9439 }
9440
9441 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009442 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009443
9444 /* Create and and push object stream in the stack. */
9445 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009446 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009447 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009448 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009449 return 0;
9450 }
9451 hlua->nargs = 1;
9452
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009453 /* push keywords in the stack. */
9454 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9455 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009456 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009457 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009458 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009459 return 0;
9460 }
9461 lua_pushstring(hlua->T, *arg);
9462 hlua->nargs++;
9463 }
9464
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009465 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009466
9467 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009468 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009469
9470 return 1;
9471}
9472
Willy Tarreau60409db2019-08-21 14:14:50 +02009473void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009474{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009475 struct stream_interface *si = cs_si(ctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009476 struct stream *strm = si_strm(si);
9477 struct channel *req = si_oc(si);
9478 struct channel *res = si_ic(si);
9479 struct act_rule *rule = ctx->rule;
9480 struct proxy *px = strm->be;
9481 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
9482 struct htx *req_htx, *res_htx;
9483
9484 res_htx = htx_from_buf(&res->buf);
9485
9486 /* If the stream is disconnect or closed, ldo nothing. */
9487 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9488 goto out;
9489
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009490 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009491 if (!b_size(&res->buf)) {
9492 si_rx_room_blk(si);
9493 goto out;
9494 }
9495 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009496 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009497 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9498
9499 /* Set the currently running flag. */
9500 if (!HLUA_IS_RUNNING(hlua) &&
9501 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009502 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009503 si_cant_get(si);
9504 goto out;
9505 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009506 }
9507
9508 /* Executes The applet if it is not done. */
9509 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9510
9511 /* Execute the function. */
9512 switch (hlua_ctx_resume(hlua, 1)) {
9513 /* finished. */
9514 case HLUA_E_OK:
9515 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9516 break;
9517
9518 /* yield. */
9519 case HLUA_E_AGAIN:
9520 if (hlua->wake_time != TICK_ETERNITY)
9521 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009522 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009523
9524 /* finished with error. */
9525 case HLUA_E_ERRMSG:
9526 /* Display log. */
9527 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009528 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009529 lua_pop(hlua->T, 1);
9530 goto error;
9531
9532 case HLUA_E_ETMOUT:
9533 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009534 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009535 goto error;
9536
9537 case HLUA_E_NOMEM:
9538 SEND_ERR(px, "Lua applet http '%s': out of memory error.\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_YIELD: /* unexpected */
9543 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\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_ERR:
9548 /* Display log. */
9549 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009550 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009551 goto error;
9552
9553 default:
9554 goto error;
9555 }
9556 }
9557
9558 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009559 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9560 goto done;
9561
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009562 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9563 goto error;
9564
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009565 /* no more data are expected. If the response buffer is empty
9566 * for a chunked message, be sure to add something (EOT block in
9567 * this case) to have something to send. It is important to be
9568 * sure the EOM flags will be handled by the endpoint.
9569 */
9570 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9571 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
9572 si_rx_room_blk(si);
9573 goto out;
9574 }
9575 channel_add_input(res, 1);
9576 }
9577
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009578 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009579 si->cs->flags |= CS_FL_EOI;
9580 res->flags |= CF_EOI;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009581 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9582 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009583 }
9584
9585 done:
9586 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009587 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009588 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009589 si_shutr(si);
9590 }
9591
9592 /* eat the whole request */
9593 if (co_data(req)) {
9594 req_htx = htx_from_buf(&req->buf);
9595 co_htx_skip(req, req_htx, co_data(req));
9596 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009597 }
9598 }
9599
9600 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009601 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009602 return;
9603
9604 error:
9605
9606 /* If we are in HTTP mode, and we are not send any
9607 * data, return a 500 server error in best effort:
9608 * if there is no room available in the buffer,
9609 * just close the connection.
9610 */
9611 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009612 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009613
9614 channel_erase(res);
9615 res->buf.data = b_data(err);
9616 memcpy(res->buf.area, b_head(err), b_data(err));
9617 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009618 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009619 }
9620 if (!(strm->flags & SF_ERR_MASK))
9621 strm->flags |= SF_ERR_RESOURCE;
9622 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9623 goto done;
9624}
9625
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009626static void hlua_applet_http_release(struct appctx *ctx)
9627{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009628 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009629 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009630 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009631 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009632}
9633
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009634/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009635 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009636 *
9637 * This function can fail with an abort() due to an Lua critical error.
9638 * We are in the configuration parsing process of HAProxy, this abort() is
9639 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009640 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009641static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9642 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009643{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009644 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009645 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009646
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009647 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009648 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009649 if (!rule->arg.hlua_rule) {
9650 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009651 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009652 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009653
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009654 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009655 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9656 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009657 if (!rule->arg.hlua_rule->args) {
9658 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009659 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009660 }
9661
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009662 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009663 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009664
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009665 /* Expect some arguments */
9666 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009667 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009668 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009669 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009670 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009671 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009672 if (!rule->arg.hlua_rule->args[i]) {
9673 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009674 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009675 }
9676 (*cur_arg)++;
9677 }
9678 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009679
Thierry FOURNIER42148732015-09-02 17:17:33 +02009680 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009681 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009682 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009683
9684 error:
9685 if (rule->arg.hlua_rule) {
9686 if (rule->arg.hlua_rule->args) {
9687 for (i = 0; i < fcn->nargs; i++)
9688 ha_free(&rule->arg.hlua_rule->args[i]);
9689 ha_free(&rule->arg.hlua_rule->args);
9690 }
9691 ha_free(&rule->arg.hlua_rule);
9692 }
9693 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009694}
9695
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009696static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9697 struct act_rule *rule, char **err)
9698{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009699 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009700
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009701 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009702 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009703 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009704 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009705 * the call of this analyzer.
9706 */
9707 if (rule->from != ACT_F_HTTP_REQ) {
9708 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9709 return ACT_RET_PRS_ERR;
9710 }
9711
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009712 /* Memory for the rule. */
9713 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9714 if (!rule->arg.hlua_rule) {
9715 memprintf(err, "out of memory error");
9716 return ACT_RET_PRS_ERR;
9717 }
9718
9719 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009720 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009721
9722 /* TODO: later accept arguments. */
9723 rule->arg.hlua_rule->args = NULL;
9724
9725 /* Add applet pointer in the rule. */
9726 rule->applet.obj_type = OBJ_TYPE_APPLET;
9727 rule->applet.name = fcn->name;
9728 rule->applet.init = hlua_applet_http_init;
9729 rule->applet.fct = hlua_applet_http_fct;
9730 rule->applet.release = hlua_applet_http_release;
9731 rule->applet.timeout = hlua_timeout_applet;
9732
9733 return ACT_RET_PRS_OK;
9734}
9735
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009736/* This function is an LUA binding used for registering
9737 * "sample-conv" functions. It expects a converter name used
9738 * in the haproxy configuration file, and an LUA function.
9739 */
9740__LJMP static int hlua_register_action(lua_State *L)
9741{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009742 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009743 const char *name;
9744 int ref;
9745 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009746 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009747 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009748 struct buffer *trash;
9749 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009750
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009751 /* Initialise the number of expected arguments at 0. */
9752 nargs = 0;
9753
9754 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9755 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009756
9757 /* First argument : converter name. */
9758 name = MAY_LJMP(luaL_checkstring(L, 1));
9759
9760 /* Second argument : environment. */
9761 if (lua_type(L, 2) != LUA_TTABLE)
9762 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9763
9764 /* Third argument : lua function. */
9765 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9766
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009767 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009768 if (lua_gettop(L) >= 4)
9769 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9770
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009771 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009772 lua_pushnil(L);
9773 while (lua_next(L, 2) != 0) {
9774 if (lua_type(L, -1) != LUA_TSTRING)
9775 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9776
Thierry Fournierf67442e2020-11-28 20:41:07 +01009777 /* Check if action exists */
9778 trash = get_trash_chunk();
9779 chunk_printf(trash, "lua.%s", name);
9780 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9781 akw = tcp_req_cont_action(trash->area);
9782 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9783 akw = tcp_res_cont_action(trash->area);
9784 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9785 akw = action_http_req_custom(trash->area);
9786 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9787 akw = action_http_res_custom(trash->area);
9788 } else {
9789 akw = NULL;
9790 }
9791 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009792 fcn = akw->private;
9793 if (fcn->function_ref[hlua_state_id] != -1) {
9794 ha_warning("Trying to register action 'lua.%s' more than once. "
9795 "This will become a hard error in version 2.5.\n", name);
9796 }
9797 fcn->function_ref[hlua_state_id] = ref;
9798
9799 /* pop the environment string. */
9800 lua_pop(L, 1);
9801 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009802 }
9803
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009804 /* Check required environment. Only accepted "http" or "tcp". */
9805 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009806 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009807 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009808 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009809 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009810 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009811 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009812
9813 /* Fill fcn. */
9814 fcn->name = strdup(name);
9815 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009816 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009817 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009818
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009819 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009820 fcn->nargs = nargs;
9821
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009822 /* List head */
9823 akl->list.n = akl->list.p = NULL;
9824
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009825 /* action keyword. */
9826 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009827 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009828 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009829 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009830
9831 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9832
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009833 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009834 akl->kw[0].private = fcn;
9835 akl->kw[0].parse = action_register_lua;
9836
9837 /* select the action registering point. */
9838 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9839 tcp_req_cont_keywords_register(akl);
9840 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9841 tcp_res_cont_keywords_register(akl);
9842 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9843 http_req_keywords_register(akl);
9844 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9845 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009846 else {
9847 release_hlua_function(fcn);
9848 if (akl)
9849 ha_free((char **)&(akl->kw[0].kw));
9850 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009851 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009852 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9853 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009854 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009855
9856 /* pop the environment string. */
9857 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009858
9859 /* reset for next loop */
9860 akl = NULL;
9861 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009862 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009863 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009864
9865 alloc_error:
9866 release_hlua_function(fcn);
9867 ha_free(&akl);
9868 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9869 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009870}
9871
9872static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9873 struct act_rule *rule, char **err)
9874{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009875 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009876
Christopher Faulet280f85b2019-07-15 15:02:04 +02009877 if (px->mode == PR_MODE_HTTP) {
9878 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009879 return ACT_RET_PRS_ERR;
9880 }
9881
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009882 /* Memory for the rule. */
9883 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9884 if (!rule->arg.hlua_rule) {
9885 memprintf(err, "out of memory error");
9886 return ACT_RET_PRS_ERR;
9887 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009888
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009889 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009890 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009891
9892 /* TODO: later accept arguments. */
9893 rule->arg.hlua_rule->args = NULL;
9894
9895 /* Add applet pointer in the rule. */
9896 rule->applet.obj_type = OBJ_TYPE_APPLET;
9897 rule->applet.name = fcn->name;
9898 rule->applet.init = hlua_applet_tcp_init;
9899 rule->applet.fct = hlua_applet_tcp_fct;
9900 rule->applet.release = hlua_applet_tcp_release;
9901 rule->applet.timeout = hlua_timeout_applet;
9902
9903 return 0;
9904}
9905
9906/* This function is an LUA binding used for registering
9907 * "sample-conv" functions. It expects a converter name used
9908 * in the haproxy configuration file, and an LUA function.
9909 */
9910__LJMP static int hlua_register_service(lua_State *L)
9911{
9912 struct action_kw_list *akl;
9913 const char *name;
9914 const char *env;
9915 int ref;
9916 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009917 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009918 struct buffer *trash;
9919 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009920
9921 MAY_LJMP(check_args(L, 3, "register_service"));
9922
9923 /* First argument : converter name. */
9924 name = MAY_LJMP(luaL_checkstring(L, 1));
9925
9926 /* Second argument : environment. */
9927 env = MAY_LJMP(luaL_checkstring(L, 2));
9928
9929 /* Third argument : lua function. */
9930 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9931
Thierry Fournierf67442e2020-11-28 20:41:07 +01009932 /* Check for service already registered */
9933 trash = get_trash_chunk();
9934 chunk_printf(trash, "lua.%s", name);
9935 akw = service_find(trash->area);
9936 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009937 fcn = akw->private;
9938 if (fcn->function_ref[hlua_state_id] != -1) {
9939 ha_warning("Trying to register service 'lua.%s' more than once. "
9940 "This will become a hard error in version 2.5.\n", name);
9941 }
9942 fcn->function_ref[hlua_state_id] = ref;
9943 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009944 }
9945
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009946 /* Allocate and fill the sample fetch keyword struct. */
9947 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9948 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009949 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009950 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009951 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009952 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009953
9954 /* Fill fcn. */
9955 len = strlen("<lua.>") + strlen(name) + 1;
9956 fcn->name = calloc(1, len);
9957 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009958 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009959 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009960 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009961
9962 /* List head */
9963 akl->list.n = akl->list.p = NULL;
9964
9965 /* converter keyword. */
9966 len = strlen("lua.") + strlen(name) + 1;
9967 akl->kw[0].kw = calloc(1, len);
9968 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009969 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009970
9971 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9972
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009973 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009974 if (strcmp(env, "tcp") == 0)
9975 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009976 else if (strcmp(env, "http") == 0)
9977 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009978 else {
9979 release_hlua_function(fcn);
9980 if (akl)
9981 ha_free((char **)&(akl->kw[0].kw));
9982 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009983 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009984 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009985 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009986
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009987 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009988 akl->kw[0].private = fcn;
9989
9990 /* End of array. */
9991 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9992
9993 /* Register this new converter */
9994 service_keywords_register(akl);
9995
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009996 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009997
9998 alloc_error:
9999 release_hlua_function(fcn);
10000 ha_free(&akl);
10001 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10002 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010003}
10004
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010005/* This function initialises Lua cli handler. It copies the
10006 * arguments in the Lua stack and create channel IO objects.
10007 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010008static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010009{
10010 struct hlua *hlua;
10011 struct hlua_function *fcn;
10012 int i;
10013 const char *error;
10014
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010015 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010016 appctx->ctx.hlua_cli.fcn = private;
10017
Willy Tarreaubafbe012017-11-24 17:34:44 +010010018 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010019 if (!hlua) {
10020 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010021 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010022 }
10023 HLUA_INIT(hlua);
10024 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010025
10026 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010027 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010028 * applet_http. It is absolutely compatible.
10029 */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010030 appctx->ctx.hlua_cli.task = task_new_here();
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010031 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010032 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010033 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010034 }
10035 appctx->ctx.hlua_cli.task->nice = 0;
10036 appctx->ctx.hlua_cli.task->context = appctx;
10037 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
10038
10039 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +010010040 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 +010010041 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010042 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010043 }
10044
10045 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010046 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010047 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10048 error = lua_tostring(hlua->T, -1);
10049 else
10050 error = "critical error";
10051 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10052 goto error;
10053 }
10054
10055 /* Check stack available size. */
10056 if (!lua_checkstack(hlua->T, 2)) {
10057 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10058 goto error;
10059 }
10060
10061 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010062 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010063
10064 /* Once the arguments parsed, the CLI is like an AppletTCP,
10065 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010066 */
10067 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10068 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10069 goto error;
10070 }
10071 hlua->nargs = 1;
10072
10073 /* push keywords in the stack. */
10074 for (i = 0; *args[i]; i++) {
10075 /* Check stack available size. */
10076 if (!lua_checkstack(hlua->T, 1)) {
10077 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10078 goto error;
10079 }
10080 lua_pushstring(hlua->T, args[i]);
10081 hlua->nargs++;
10082 }
10083
10084 /* We must initialize the execution timeouts. */
10085 hlua->max_time = hlua_timeout_session;
10086
10087 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010088 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010089
10090 /* It's ok */
10091 return 0;
10092
10093 /* It's not ok. */
10094error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010095 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010096 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010097 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010098 return 1;
10099}
10100
10101static int hlua_cli_io_handler_fct(struct appctx *appctx)
10102{
10103 struct hlua *hlua;
10104 struct stream_interface *si;
10105 struct hlua_function *fcn;
10106
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010107 hlua = appctx->ctx.hlua_cli.hlua;
Christopher Faulet86e1c332021-12-20 17:09:39 +010010108 si = cs_si(appctx->owner);
Willy Tarreau8ae4f752016-12-14 15:41:45 +010010109 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010110
10111 /* If the stream is disconnect or closed, ldo nothing. */
10112 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
10113 return 1;
10114
10115 /* Execute the function. */
10116 switch (hlua_ctx_resume(hlua, 1)) {
10117
10118 /* finished. */
10119 case HLUA_E_OK:
10120 return 1;
10121
10122 /* yield. */
10123 case HLUA_E_AGAIN:
10124 /* We want write. */
10125 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +010010126 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010127 /* Set the timeout. */
10128 if (hlua->wake_time != TICK_ETERNITY)
10129 task_schedule(hlua->task, hlua->wake_time);
10130 return 0;
10131
10132 /* finished with error. */
10133 case HLUA_E_ERRMSG:
10134 /* Display log. */
10135 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10136 fcn->name, lua_tostring(hlua->T, -1));
10137 lua_pop(hlua->T, 1);
10138 return 1;
10139
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010140 case HLUA_E_ETMOUT:
10141 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10142 fcn->name);
10143 return 1;
10144
10145 case HLUA_E_NOMEM:
10146 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10147 fcn->name);
10148 return 1;
10149
10150 case HLUA_E_YIELD: /* unexpected */
10151 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10152 fcn->name);
10153 return 1;
10154
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010155 case HLUA_E_ERR:
10156 /* Display log. */
10157 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10158 fcn->name);
10159 return 1;
10160
10161 default:
10162 return 1;
10163 }
10164
10165 return 1;
10166}
10167
10168static void hlua_cli_io_release_fct(struct appctx *appctx)
10169{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010170 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010171 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010172}
10173
10174/* This function is an LUA binding used for registering
10175 * new keywords in the cli. It expects a list of keywords
10176 * which are the "path". It is limited to 5 keywords. A
10177 * description of the command, a function to be executed
10178 * for the parsing and a function for io handlers.
10179 */
10180__LJMP static int hlua_register_cli(lua_State *L)
10181{
10182 struct cli_kw_list *cli_kws;
10183 const char *message;
10184 int ref_io;
10185 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010186 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010187 int index;
10188 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010189 struct buffer *trash;
10190 const char *kw[5];
10191 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010192 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010193
10194 MAY_LJMP(check_args(L, 3, "register_cli"));
10195
10196 /* First argument : an array of maximum 5 keywords. */
10197 if (!lua_istable(L, 1))
10198 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10199
10200 /* Second argument : string with contextual message. */
10201 message = MAY_LJMP(luaL_checkstring(L, 2));
10202
10203 /* Third and fourth argument : lua function. */
10204 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10205
Thierry Fournierf67442e2020-11-28 20:41:07 +010010206 /* Check for CLI service already registered */
10207 trash = get_trash_chunk();
10208 index = 0;
10209 lua_pushnil(L);
10210 memset(kw, 0, sizeof(kw));
10211 while (lua_next(L, 1) != 0) {
10212 if (index >= CLI_PREFIX_KW_NB)
10213 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10214 if (lua_type(L, -1) != LUA_TSTRING)
10215 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10216 kw[index] = lua_tostring(L, -1);
10217 if (index == 0)
10218 chunk_printf(trash, "%s", kw[index]);
10219 else
10220 chunk_appendf(trash, " %s", kw[index]);
10221 index++;
10222 lua_pop(L, 1);
10223 }
10224 cli_kw = cli_find_kw_exact((char **)kw);
10225 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010226 fcn = cli_kw->private;
10227 if (fcn->function_ref[hlua_state_id] != -1) {
10228 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10229 "This will become a hard error in version 2.5.\n", trash->area);
10230 }
10231 fcn->function_ref[hlua_state_id] = ref_io;
10232 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010233 }
10234
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010235 /* Allocate and fill the sample fetch keyword struct. */
10236 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010237 if (!cli_kws) {
10238 errmsg = "Lua out of memory error.";
10239 goto error;
10240 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010241 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010242 if (!fcn) {
10243 errmsg = "Lua out of memory error.";
10244 goto error;
10245 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010246
10247 /* Fill path. */
10248 index = 0;
10249 lua_pushnil(L);
10250 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010251 if (index >= 5) {
10252 errmsg = "1st argument must be a table with a maximum of 5 entries";
10253 goto error;
10254 }
10255 if (lua_type(L, -1) != LUA_TSTRING) {
10256 errmsg = "1st argument must be a table filled with strings";
10257 goto error;
10258 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010259 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010260 if (!cli_kws->kw[0].str_kw[index]) {
10261 errmsg = "Lua out of memory error.";
10262 goto error;
10263 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010264 index++;
10265 lua_pop(L, 1);
10266 }
10267
10268 /* Copy help message. */
10269 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010270 if (!cli_kws->kw[0].usage) {
10271 errmsg = "Lua out of memory error.";
10272 goto error;
10273 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010274
10275 /* Fill fcn io handler. */
10276 len = strlen("<lua.cli>") + 1;
10277 for (i = 0; i < index; i++)
10278 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10279 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010280 if (!fcn->name) {
10281 errmsg = "Lua out of memory error.";
10282 goto error;
10283 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010284 strncat((char *)fcn->name, "<lua.cli", len);
10285 for (i = 0; i < index; i++) {
10286 strncat((char *)fcn->name, ".", len);
10287 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10288 }
10289 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010290 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010291
10292 /* Fill last entries. */
10293 cli_kws->kw[0].private = fcn;
10294 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10295 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10296 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10297
10298 /* Register this new converter */
10299 cli_register_kw(cli_kws);
10300
10301 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010302
10303 error:
10304 release_hlua_function(fcn);
10305 if (cli_kws) {
10306 for (i = 0; i < index; i++)
10307 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10308 ha_free((char **)&(cli_kws->kw[0].usage));
10309 }
10310 ha_free(&cli_kws);
10311 WILL_LJMP(luaL_error(L, errmsg));
10312 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010313}
10314
Christopher Faulet69c581a2021-05-31 08:54:04 +020010315static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10316{
10317 struct hlua_flt_config *conf = fconf->conf;
10318 lua_State *L;
10319 int error, pos, state_id, flt_ref;
10320
10321 state_id = reg_flt_to_stack_id(conf->reg);
10322 L = hlua_states[state_id];
10323 pos = lua_gettop(L);
10324
10325 /* The filter parsing function */
10326 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10327
10328 /* Push the filter class on the stack and resolve all callbacks */
10329 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10330
10331 /* Duplicate the filter class so each filter will have its own copy */
10332 lua_newtable(L);
10333 lua_pushnil(L);
10334
10335 while (lua_next(L, pos+2)) {
10336 lua_pushvalue(L, -2);
10337 lua_insert(L, -2);
10338 lua_settable(L, -4);
10339 }
10340 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10341
10342 /* Remove the original lua filter class from the stack */
10343 lua_pop(L, 1);
10344
10345 /* Push the copy on the stack */
10346 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10347
10348 /* extra args are pushed in a table */
10349 lua_newtable(L);
10350 for (pos = 0; conf->args[pos]; pos++) {
10351 /* Check stack available size. */
10352 if (!lua_checkstack(L, 1)) {
10353 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10354 goto error;
10355 }
10356 lua_pushstring(L, conf->args[pos]);
10357 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10358 }
10359
10360 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10361 switch (error) {
10362 case LUA_OK:
10363 /* replace the filter ref */
10364 conf->ref[state_id] = flt_ref;
10365 break;
10366 case LUA_ERRRUN:
10367 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10368 goto error;
10369 case LUA_ERRMEM:
10370 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10371 goto error;
10372 case LUA_ERRERR:
10373 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10374 goto error;
10375#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10376 case LUA_ERRGCMM:
10377 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10378 goto error;
10379#endif
10380 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010381 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010382 goto error;
10383 }
10384
10385 lua_settop(L, 0);
10386 return 0;
10387
10388 error:
10389 lua_settop(L, 0);
10390 return -1;
10391}
10392
10393static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10394{
10395 struct hlua_flt_config *conf = fconf->conf;
10396 lua_State *L;
10397 int state_id;
10398
10399 if (!conf)
10400 return;
10401
10402 state_id = reg_flt_to_stack_id(conf->reg);
10403 L = hlua_states[state_id];
10404 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10405}
10406
10407static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10408{
10409 struct hlua_flt_config *conf = fconf->conf;
10410 int state_id = reg_flt_to_stack_id(conf->reg);
10411
10412 /* Rely on per-thread init for global scripts */
10413 if (!state_id)
10414 return hlua_filter_init_per_thread(px, fconf);
10415 return 0;
10416}
10417
10418static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10419{
10420
10421 if (fconf->conf) {
10422 struct hlua_flt_config *conf = fconf->conf;
10423 int state_id = reg_flt_to_stack_id(conf->reg);
10424 int pos;
10425
10426 /* Rely on per-thread deinit for global scripts */
10427 if (!state_id)
10428 hlua_filter_deinit_per_thread(px, fconf);
10429
10430 for (pos = 0; conf->args[pos]; pos++)
10431 free(conf->args[pos]);
10432 free(conf->args);
10433 }
10434 ha_free(&fconf->conf);
10435 ha_free((char **)&fconf->id);
10436 ha_free(&fconf->ops);
10437}
10438
10439static int hlua_filter_new(struct stream *s, struct filter *filter)
10440{
10441 struct hlua_flt_config *conf = FLT_CONF(filter);
10442 struct hlua_flt_ctx *flt_ctx = NULL;
10443 int ret = 1;
10444
10445 /* In the execution wrappers linked with a stream, the
10446 * Lua context can be not initialized. This behavior
10447 * permits to save performances because a systematic
10448 * Lua initialization cause 5% performances loss.
10449 */
10450 if (!s->hlua) {
10451 struct hlua *hlua;
10452
10453 hlua = pool_alloc(pool_head_hlua);
10454 if (!hlua) {
10455 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10456 conf->reg->name);
10457 ret = 0;
10458 goto end;
10459 }
10460 HLUA_INIT(hlua);
10461 s->hlua = hlua;
10462 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10463 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10464 conf->reg->name);
10465 ret = 0;
10466 goto end;
10467 }
10468 }
10469
10470 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10471 if (!flt_ctx) {
10472 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10473 conf->reg->name);
10474 ret = 0;
10475 goto end;
10476 }
10477 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10478 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10479 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10480 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10481 conf->reg->name);
10482 ret = 0;
10483 goto end;
10484 }
10485 HLUA_INIT(flt_ctx->hlua[0]);
10486 HLUA_INIT(flt_ctx->hlua[1]);
10487 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10488 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10489 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10490 conf->reg->name);
10491 ret = 0;
10492 goto end;
10493 }
10494
10495 if (!HLUA_IS_RUNNING(s->hlua)) {
10496 /* The following Lua calls can fail. */
10497 if (!SET_SAFE_LJMP(s->hlua)) {
10498 const char *error;
10499
10500 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10501 error = lua_tostring(s->hlua->T, -1);
10502 else
10503 error = "critical error";
10504 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10505 ret = 0;
10506 goto end;
10507 }
10508
10509 /* Check stack size. */
10510 if (!lua_checkstack(s->hlua->T, 1)) {
10511 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010512 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010513 ret = 0;
10514 goto end;
10515 }
10516
10517 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10518 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10519 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10520 conf->reg->name);
10521 RESET_SAFE_LJMP(s->hlua);
10522 ret = 0;
10523 goto end;
10524 }
10525 lua_insert(s->hlua->T, -2);
10526
10527 /* Push the copy on the stack */
10528 s->hlua->nargs = 1;
10529
10530 /* We must initialize the execution timeouts. */
10531 s->hlua->max_time = hlua_timeout_session;
10532
10533 /* At this point the execution is safe. */
10534 RESET_SAFE_LJMP(s->hlua);
10535 }
10536
10537 switch (hlua_ctx_resume(s->hlua, 0)) {
10538 case HLUA_E_OK:
10539 /* Nothing returned or not a table, ignore the filter for current stream */
10540 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10541 ret = 0;
10542 goto end;
10543 }
10544
10545 /* Attached the filter pointer to the ctx */
10546 lua_pushstring(s->hlua->T, "__filter");
10547 lua_pushlightuserdata(s->hlua->T, filter);
10548 lua_settable(s->hlua->T, -3);
10549
10550 /* Save a ref on the filter ctx */
10551 lua_pushvalue(s->hlua->T, 1);
10552 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10553 filter->ctx = flt_ctx;
10554 break;
10555 case HLUA_E_ERRMSG:
10556 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10557 ret = -1;
10558 goto end;
10559 case HLUA_E_ETMOUT:
10560 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10561 ret = 0;
10562 goto end;
10563 case HLUA_E_NOMEM:
10564 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10565 ret = 0;
10566 goto end;
10567 case HLUA_E_AGAIN:
10568 case HLUA_E_YIELD:
10569 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10570 " are not allowed from 'new' function.\n", conf->reg->name);
10571 ret = 0;
10572 goto end;
10573 case HLUA_E_ERR:
10574 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10575 ret = 0;
10576 goto end;
10577 default:
10578 ret = 0;
10579 goto end;
10580 }
10581
10582 end:
10583 if (s->hlua)
10584 lua_settop(s->hlua->T, 0);
10585 if (ret <= 0) {
10586 if (flt_ctx) {
10587 hlua_ctx_destroy(flt_ctx->hlua[0]);
10588 hlua_ctx_destroy(flt_ctx->hlua[1]);
10589 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10590 }
10591 }
10592 return ret;
10593}
10594
10595static void hlua_filter_delete(struct stream *s, struct filter *filter)
10596{
10597 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10598
10599 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10600 hlua_ctx_destroy(flt_ctx->hlua[0]);
10601 hlua_ctx_destroy(flt_ctx->hlua[1]);
10602 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10603 filter->ctx = NULL;
10604}
10605
Christopher Faulet9f55a502020-02-25 15:21:02 +010010606static int hlua_filter_from_payload(struct filter *filter)
10607{
10608 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10609
10610 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10611}
10612
Christopher Fauletc404f112020-02-26 15:03:09 +010010613static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10614 int dir, unsigned int flags)
10615{
10616 struct hlua *flt_hlua;
10617 struct hlua_flt_config *conf = FLT_CONF(filter);
10618 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10619 unsigned int hflags = HLUA_TXN_FLT_CTX;
10620 int ret = 1;
10621
10622 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10623 if (!flt_hlua)
10624 goto end;
10625
10626 if (!HLUA_IS_RUNNING(flt_hlua)) {
10627 int extra_idx = lua_gettop(flt_hlua->T);
10628
10629 /* The following Lua calls can fail. */
10630 if (!SET_SAFE_LJMP(flt_hlua)) {
10631 const char *error;
10632
10633 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10634 error = lua_tostring(flt_hlua->T, -1);
10635 else
10636 error = "critical error";
10637 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10638 goto end;
10639 }
10640
10641 /* Check stack size. */
10642 if (!lua_checkstack(flt_hlua->T, 3)) {
10643 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10644 RESET_SAFE_LJMP(flt_hlua);
10645 goto end;
10646 }
10647
10648 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10649 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10650 RESET_SAFE_LJMP(flt_hlua);
10651 goto end;
10652 }
10653 lua_insert(flt_hlua->T, -2);
10654
10655 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10656 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10657 RESET_SAFE_LJMP(flt_hlua);
10658 goto end;
10659 }
10660 flt_hlua->nargs = 2;
10661
10662 if (flags & HLUA_FLT_CB_ARG_CHN) {
10663 if (dir == SMP_OPT_DIR_REQ)
10664 lua_getfield(flt_hlua->T, -1, "req");
10665 else
10666 lua_getfield(flt_hlua->T, -1, "res");
10667 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10668 lua_pushstring(flt_hlua->T, "__filter");
10669 lua_pushlightuserdata(flt_hlua->T, filter);
10670 lua_settable(flt_hlua->T, -3);
10671 }
10672 flt_hlua->nargs++;
10673 }
10674 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010675 if (dir == SMP_OPT_DIR_REQ)
10676 lua_getfield(flt_hlua->T, -1, "http_req");
10677 else
10678 lua_getfield(flt_hlua->T, -1, "http_res");
10679 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10680 lua_pushstring(flt_hlua->T, "__filter");
10681 lua_pushlightuserdata(flt_hlua->T, filter);
10682 lua_settable(flt_hlua->T, -3);
10683 }
10684 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010685 }
10686
10687 /* Check stack size. */
10688 if (!lua_checkstack(flt_hlua->T, 1)) {
10689 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10690 RESET_SAFE_LJMP(flt_hlua);
10691 goto end;
10692 }
10693
10694 while (extra_idx--) {
10695 lua_pushvalue(flt_hlua->T, 1);
10696 lua_remove(flt_hlua->T, 1);
10697 flt_hlua->nargs++;
10698 }
10699
10700 /* We must initialize the execution timeouts. */
10701 flt_hlua->max_time = hlua_timeout_session;
10702
10703 /* At this point the execution is safe. */
10704 RESET_SAFE_LJMP(flt_hlua);
10705 }
10706
10707 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10708 case HLUA_E_OK:
10709 /* Catch the return value if it required */
10710 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10711 ret = lua_tointeger(flt_hlua->T, -1);
10712 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10713 }
10714
10715 /* Set timeout in the required channel. */
10716 if (flt_hlua->wake_time != TICK_ETERNITY) {
10717 if (dir == SMP_OPT_DIR_REQ)
10718 s->req.analyse_exp = flt_hlua->wake_time;
10719 else
10720 s->res.analyse_exp = flt_hlua->wake_time;
10721 }
10722 break;
10723 case HLUA_E_AGAIN:
10724 /* Set timeout in the required channel. */
10725 if (flt_hlua->wake_time != TICK_ETERNITY) {
10726 if (dir == SMP_OPT_DIR_REQ)
10727 s->req.analyse_exp = flt_hlua->wake_time;
10728 else
10729 s->res.analyse_exp = flt_hlua->wake_time;
10730 }
10731 /* Some actions can be wake up when a "write" event
10732 * is detected on a response channel. This is useful
10733 * only for actions targeted on the requests.
10734 */
10735 if (HLUA_IS_WAKERESWR(flt_hlua))
10736 s->res.flags |= CF_WAKE_WRITE;
10737 if (HLUA_IS_WAKEREQWR(flt_hlua))
10738 s->req.flags |= CF_WAKE_WRITE;
10739 ret = 0;
10740 goto end;
10741 case HLUA_E_ERRMSG:
10742 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10743 ret = -1;
10744 goto end;
10745 case HLUA_E_ETMOUT:
10746 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10747 goto end;
10748 case HLUA_E_NOMEM:
10749 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10750 goto end;
10751 case HLUA_E_YIELD:
10752 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10753 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10754 goto end;
10755 case HLUA_E_ERR:
10756 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10757 goto end;
10758 default:
10759 goto end;
10760 }
10761
10762
10763 end:
10764 return ret;
10765}
10766
10767static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10768{
10769 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10770
10771 flt_ctx->flags = 0;
10772 return hlua_filter_callback(s, filter, "start_analyze",
10773 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10774 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10775}
10776
10777static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10778{
10779 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10780
10781 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10782 return hlua_filter_callback(s, filter, "end_analyze",
10783 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10784 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10785}
10786
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010787static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10788{
10789 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10790
10791 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10792 return hlua_filter_callback(s, filter, "http_headers",
10793 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10794 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10795}
10796
10797static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10798 unsigned int offset, unsigned int len)
10799{
10800 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10801 struct hlua *flt_hlua;
10802 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10803 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10804 int ret;
10805
10806 flt_hlua = flt_ctx->hlua[idx];
10807 flt_ctx->cur_off[idx] = offset;
10808 flt_ctx->cur_len[idx] = len;
10809 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10810 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10811 if (ret != -1) {
10812 ret = flt_ctx->cur_len[idx];
10813 if (lua_gettop(flt_hlua->T) > 0) {
10814 ret = lua_tointeger(flt_hlua->T, -1);
10815 if (ret > flt_ctx->cur_len[idx])
10816 ret = flt_ctx->cur_len[idx];
10817 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10818 }
10819 }
10820 return ret;
10821}
10822
10823static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10824{
10825 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10826
10827 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10828 return hlua_filter_callback(s, filter, "http_end",
10829 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10830 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10831}
10832
Christopher Fauletc404f112020-02-26 15:03:09 +010010833static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10834 unsigned int offset, unsigned int len)
10835{
10836 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10837 struct hlua *flt_hlua;
10838 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10839 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10840 int ret;
10841
10842 flt_hlua = flt_ctx->hlua[idx];
10843 flt_ctx->cur_off[idx] = offset;
10844 flt_ctx->cur_len[idx] = len;
10845 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10846 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10847 if (ret != -1) {
10848 ret = flt_ctx->cur_len[idx];
10849 if (lua_gettop(flt_hlua->T) > 0) {
10850 ret = lua_tointeger(flt_hlua->T, -1);
10851 if (ret > flt_ctx->cur_len[idx])
10852 ret = flt_ctx->cur_len[idx];
10853 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10854 }
10855 }
10856 return ret;
10857}
10858
Christopher Faulet69c581a2021-05-31 08:54:04 +020010859static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10860 struct flt_conf *fconf, char **err, void *private)
10861{
10862 struct hlua_reg_filter *reg_flt = private;
10863 lua_State *L;
10864 struct hlua_flt_config *conf = NULL;
10865 const char *flt_id = NULL;
10866 int state_id, pos, flt_flags = 0;
10867 struct flt_ops *hlua_flt_ops = NULL;
10868
10869 state_id = reg_flt_to_stack_id(reg_flt);
10870 L = hlua_states[state_id];
10871
10872 /* Initialize the filter ops with default callbacks */
10873 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010874 if (!hlua_flt_ops)
10875 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010876 hlua_flt_ops->init = hlua_filter_init;
10877 hlua_flt_ops->deinit = hlua_filter_deinit;
10878 if (state_id) {
10879 /* Set per-thread callback if script is loaded per-thread */
10880 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10881 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10882 }
10883 hlua_flt_ops->attach = hlua_filter_new;
10884 hlua_flt_ops->detach = hlua_filter_delete;
10885
10886 /* Push the filter class on the stack and resolve all callbacks */
10887 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10888
Christopher Fauletc404f112020-02-26 15:03:09 +010010889 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10890 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10891 lua_pop(L, 1);
10892 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10893 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10894 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010895 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10896 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10897 lua_pop(L, 1);
10898 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10899 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10900 lua_pop(L, 1);
10901 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10902 hlua_flt_ops->http_end = hlua_filter_http_end;
10903 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010904 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10905 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10906 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010907
10908 /* Get id and flags of the filter class */
10909 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10910 flt_id = lua_tostring(L, -1);
10911 lua_pop(L, 1);
10912 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10913 flt_flags = lua_tointeger(L, -1);
10914 lua_pop(L, 1);
10915
10916 /* Create the filter config */
10917 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010918 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010919 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010920 conf->reg = reg_flt;
10921
10922 /* duplicate args */
10923 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10924 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010925 if (!conf->args)
10926 goto error;
10927 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010928 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010929 if (!conf->args[pos])
10930 goto error;
10931 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010932 conf->args[pos] = NULL;
10933 *cur_arg += pos + 1;
10934
Christopher Fauletc86bb872021-08-13 08:33:57 +020010935 if (flt_id) {
10936 fconf->id = strdup(flt_id);
10937 if (!fconf->id)
10938 goto error;
10939 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010940 fconf->flags = flt_flags;
10941 fconf->conf = conf;
10942 fconf->ops = hlua_flt_ops;
10943
10944 lua_settop(L, 0);
10945 return 0;
10946
10947 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010948 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010949 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010950 if (conf && conf->args) {
10951 for (pos = 0; conf->args[pos]; pos++)
10952 free(conf->args[pos]);
10953 free(conf->args);
10954 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010955 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010956 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010957 lua_settop(L, 0);
10958 return -1;
10959}
10960
Christopher Fauletc404f112020-02-26 15:03:09 +010010961__LJMP static int hlua_register_data_filter(lua_State *L)
10962{
10963 struct filter *filter;
10964 struct channel *chn;
10965
10966 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10967 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10968 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10969
10970 lua_getfield(L, 1, "__filter");
10971 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10972 filter = lua_touserdata (L, -1);
10973 lua_pop(L, 1);
10974
10975 register_data_filter(chn_strm(chn), chn, filter);
10976 return 1;
10977}
10978
10979__LJMP static int hlua_unregister_data_filter(lua_State *L)
10980{
10981 struct filter *filter;
10982 struct channel *chn;
10983
10984 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10985 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10986 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10987
10988 lua_getfield(L, 1, "__filter");
10989 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10990 filter = lua_touserdata (L, -1);
10991 lua_pop(L, 1);
10992
10993 unregister_data_filter(chn_strm(chn), chn, filter);
10994 return 1;
10995}
10996
Christopher Faulet69c581a2021-05-31 08:54:04 +020010997/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010998 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020010999 * parse configuration arguments.
11000 */
11001__LJMP static int hlua_register_filter(lua_State *L)
11002{
11003 struct buffer *trash;
11004 struct flt_kw_list *fkl;
11005 struct flt_kw *fkw;
11006 const char *name;
11007 struct hlua_reg_filter *reg_flt= NULL;
11008 int flt_ref, fun_ref;
11009 int len;
11010
11011 MAY_LJMP(check_args(L, 3, "register_filter"));
11012
11013 /* First argument : filter name. */
11014 name = MAY_LJMP(luaL_checkstring(L, 1));
11015
11016 /* Second argument : The filter class */
11017 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11018
11019 /* Third argument : lua function. */
11020 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11021
11022 trash = get_trash_chunk();
11023 chunk_printf(trash, "lua.%s", name);
11024 fkw = flt_find_kw(trash->area);
11025 if (fkw != NULL) {
11026 reg_flt = fkw->private;
11027 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11028 ha_warning("Trying to register filter 'lua.%s' more than once. "
11029 "This will become a hard error in version 2.5.\n", name);
11030 }
11031 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11032 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11033 return 0;
11034 }
11035
11036 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11037 if (!fkl)
11038 goto alloc_error;
11039 fkl->scope = "HLUA";
11040
11041 reg_flt = new_hlua_reg_filter(name);
11042 if (!reg_flt)
11043 goto alloc_error;
11044
11045 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11046 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11047
11048 /* The filter keyword */
11049 len = strlen("lua.") + strlen(name) + 1;
11050 fkl->kw[0].kw = calloc(1, len);
11051 if (!fkl->kw[0].kw)
11052 goto alloc_error;
11053
11054 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11055
11056 fkl->kw[0].parse = hlua_filter_parse_fct;
11057 fkl->kw[0].private = reg_flt;
11058 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11059
11060 /* Register this new filter */
11061 flt_register_keywords(fkl);
11062
11063 return 0;
11064
11065 alloc_error:
11066 release_hlua_reg_filter(reg_flt);
11067 ha_free(&fkl);
11068 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11069 return 0; /* Never reached */
11070}
11071
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011072static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011073 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011074 char **err, unsigned int *timeout)
11075{
11076 const char *error;
11077
11078 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011079 if (error == PARSE_TIME_OVER) {
11080 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11081 args[1], args[0]);
11082 return -1;
11083 }
11084 else if (error == PARSE_TIME_UNDER) {
11085 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11086 args[1], args[0]);
11087 return -1;
11088 }
11089 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011090 memprintf(err, "%s: invalid timeout", args[0]);
11091 return -1;
11092 }
11093 return 0;
11094}
11095
11096static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011097 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011098 char **err)
11099{
11100 return hlua_read_timeout(args, section_type, curpx, defpx,
11101 file, line, err, &hlua_timeout_session);
11102}
11103
11104static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011105 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011106 char **err)
11107{
11108 return hlua_read_timeout(args, section_type, curpx, defpx,
11109 file, line, err, &hlua_timeout_task);
11110}
11111
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011112static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011113 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011114 char **err)
11115{
11116 return hlua_read_timeout(args, section_type, curpx, defpx,
11117 file, line, err, &hlua_timeout_applet);
11118}
11119
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011120static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011121 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011122 char **err)
11123{
11124 char *error;
11125
11126 hlua_nb_instruction = strtoll(args[1], &error, 10);
11127 if (*error != '\0') {
11128 memprintf(err, "%s: invalid number", args[0]);
11129 return -1;
11130 }
11131 return 0;
11132}
11133
Willy Tarreau32f61e22015-03-18 17:54:59 +010011134static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011135 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011136 char **err)
11137{
11138 char *error;
11139
11140 if (*(args[1]) == 0) {
11141 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11142 return -1;
11143 }
11144 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11145 if (*error != '\0') {
11146 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11147 return -1;
11148 }
11149 return 0;
11150}
11151
11152
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011153/* This function is called by the main configuration key "lua-load". It loads and
11154 * execute an lua file during the parsing of the HAProxy configuration file. It is
11155 * the main lua entry point.
11156 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011157 * This function runs with the HAProxy keywords API. It returns -1 if an error
11158 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011159 *
11160 * In some error case, LUA set an error message in top of the stack. This function
11161 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011162 *
11163 * This function can fail with an abort() due to an Lua critical error.
11164 * We are in the configuration parsing process of HAProxy, this abort() is
11165 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011166 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011167static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011168{
11169 int error;
11170
11171 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011172 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011173 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011174 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11175 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011176 return -1;
11177 }
11178
11179 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011180 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011181 switch (error) {
11182 case LUA_OK:
11183 break;
11184 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011185 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11186 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011187 return -1;
11188 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011189 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011190 return -1;
11191 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011192 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11193 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011194 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011195#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011196 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011197 memprintf(err, "Lua garbage collector 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#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011201 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011202 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11203 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011204 return -1;
11205 }
11206
11207 return 0;
11208}
11209
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011210static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011211 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011212 char **err)
11213{
11214 if (*(args[1]) == 0) {
11215 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11216 return -1;
11217 }
11218
Thierry Fournier59f11be2020-11-29 00:37:41 +010011219 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011220 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011221 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011222 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011223}
11224
Thierry Fournier59f11be2020-11-29 00:37:41 +010011225static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011226 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011227 char **err)
11228{
11229 int len;
11230
11231 if (*(args[1]) == 0) {
11232 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11233 return -1;
11234 }
11235
11236 if (per_thread_load == NULL) {
11237 /* allocate the first entry large enough to store the final NULL */
11238 per_thread_load = calloc(1, sizeof(*per_thread_load));
11239 if (per_thread_load == NULL) {
11240 memprintf(err, "out of memory error");
11241 return -1;
11242 }
11243 }
11244
11245 /* count used entries */
11246 for (len = 0; per_thread_load[len] != NULL; len++)
11247 ;
11248
11249 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11250 if (per_thread_load == NULL) {
11251 memprintf(err, "out of memory error");
11252 return -1;
11253 }
11254
11255 per_thread_load[len] = strdup(args[1]);
11256 per_thread_load[len + 1] = NULL;
11257
11258 if (per_thread_load[len] == NULL) {
11259 memprintf(err, "out of memory error");
11260 return -1;
11261 }
11262
11263 /* loading for thread 1 only */
11264 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011265 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011266 return hlua_load_state(args[1], hlua_states[1], err);
11267}
11268
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011269/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11270 * in the given <ctx>.
11271 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011272static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011273{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011274 lua_getglobal(L, "package"); /* push package variable */
11275 lua_pushstring(L, path); /* push given path */
11276 lua_pushstring(L, ";"); /* push semicolon */
11277 lua_getfield(L, -3, type); /* push old path */
11278 lua_concat(L, 3); /* concatenate to new path */
11279 lua_setfield(L, -2, type); /* store new path */
11280 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011281
11282 return 0;
11283}
11284
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011285static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011286 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011287 char **err)
11288{
11289 char *path;
11290 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011291 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011292 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011293
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011294 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011295 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011296 }
11297
11298 if (!(*args[1])) {
11299 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011300 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011301 }
11302 path = args[1];
11303
11304 if (*args[2]) {
11305 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11306 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011307 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011308 }
11309 type = args[2];
11310 }
11311
Thierry Fournier59f11be2020-11-29 00:37:41 +010011312 p = calloc(1, sizeof(*p));
11313 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011314 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011315 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011316 }
11317 p->path = strdup(path);
11318 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011319 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011320 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011321 }
11322 p->type = strdup(type);
11323 if (p->type == 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 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011327 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011328
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011329 /* Handle the global state and the per-thread state for the first
11330 * thread. The remaining threads will be initialized based on
11331 * prepend_path_list.
11332 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011333 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011334 lua_State *L = hlua_states[i];
11335 const char *error;
11336
11337 if (setjmp(safe_ljmp_env) != 0) {
11338 lua_atpanic(L, hlua_panic_safe);
11339 if (lua_type(L, -1) == LUA_TSTRING)
11340 error = lua_tostring(L, -1);
11341 else
11342 error = "critical error";
11343 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11344 exit(1);
11345 } else {
11346 lua_atpanic(L, hlua_panic_ljmp);
11347 }
11348
11349 hlua_prepend_path(L, type, path);
11350
11351 lua_atpanic(L, hlua_panic_safe);
11352 }
11353
Thierry Fournier59f11be2020-11-29 00:37:41 +010011354 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011355
11356err2:
11357 free(p->type);
11358 free(p->path);
11359err:
11360 free(p);
11361 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011362}
11363
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011364/* configuration keywords declaration */
11365static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011366 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011367 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011368 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011369 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11370 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011371 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011372 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011373 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011374 { 0, NULL, NULL },
11375}};
11376
Willy Tarreau0108d902018-11-25 19:14:37 +010011377INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11378
William Lallemand52139182022-03-30 15:05:42 +020011379#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011380
William Lallemand30fcca12022-03-30 12:03:12 +020011381/*
11382 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11383 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11384 * difference is that the yield in lua and for the CLI is not handled the same
11385 * way.
11386 */
11387__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11388{
11389 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11390 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11391 struct ckch_inst *ckchi = *lua_ckchi;
11392 struct ckch_store *old_ckchs = lua_ckchs[0];
11393 struct ckch_store *new_ckchs = lua_ckchs[1];
11394 struct hlua *hlua;
11395 char *err = NULL;
11396 int y = 1;
11397
11398 hlua = hlua_gethlua(L);
11399
11400 /* get the first ckchi to copy */
11401 if (ckchi == NULL)
11402 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11403
11404 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11405 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11406 struct ckch_inst *new_inst;
11407
11408 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11409 if (y % 10 == 0) {
11410
11411 *lua_ckchi = ckchi;
11412
11413 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11414 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11415 }
11416
11417 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11418 goto error;
11419
11420 /* link the new ckch_inst to the duplicate */
11421 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11422 y++;
11423 }
11424
11425 /* The generation is finished, we can insert everything */
11426 ckch_store_replace(old_ckchs, new_ckchs);
11427
11428 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11429
11430 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11431
11432 return 0;
11433
11434error:
11435 ckch_store_free(new_ckchs);
11436 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11437 WILL_LJMP(luaL_error(L, "%s", err));
11438 free(err);
11439
11440 return 0;
11441}
11442
11443/*
11444 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11445 * from the table in parameter.
11446 *
11447 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11448 * means it does not need to have a transaction since everything is done in the
11449 * same function.
11450 *
11451 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11452 *
11453 */
11454__LJMP static int hlua_ckch_set(lua_State *L)
11455{
11456 struct hlua *hlua;
11457 struct ckch_inst **lua_ckchi;
11458 struct ckch_store **lua_ckchs;
11459 struct ckch_store *old_ckchs = NULL;
11460 struct ckch_store *new_ckchs = NULL;
11461 int errcode = 0;
11462 char *err = NULL;
11463 struct cert_exts *cert_ext = NULL;
11464 char *filename;
11465 struct cert_key_and_chain *ckch;
11466 int ret;
11467
11468 if (lua_type(L, -1) != LUA_TTABLE)
11469 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11470
11471 hlua = hlua_gethlua(L);
11472
11473 /* FIXME: this should not return an error but should come back later */
11474 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11475 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11476
11477 ret = lua_getfield(L, -1, "filename");
11478 if (ret != LUA_TSTRING) {
11479 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11480 errcode |= ERR_ALERT | ERR_FATAL;
11481 goto end;
11482 }
11483 filename = (char *)lua_tostring(L, -1);
11484
11485
11486 /* look for the filename in the tree */
11487 old_ckchs = ckchs_lookup(filename);
11488 if (!old_ckchs) {
11489 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11490 errcode |= ERR_ALERT | ERR_FATAL;
11491 goto end;
11492 }
11493 /* TODO: handle extra_files_noext */
11494
11495 new_ckchs = ckchs_dup(old_ckchs);
11496 if (!new_ckchs) {
11497 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11498 errcode |= ERR_ALERT | ERR_FATAL;
11499 goto end;
11500 }
11501
11502 ckch = new_ckchs->ckch;
11503
11504 /* loop on the field in the table, which have the same name as the
11505 * possible extensions of files */
11506 lua_pushnil(L);
11507 while (lua_next(L, 1)) {
11508 int i;
11509 const char *field = lua_tostring(L, -2);
11510 char *payload = (char *)lua_tostring(L, -1);
11511
11512 if (!field || strcmp(field, "filename") == 0) {
11513 lua_pop(L, 1);
11514 continue;
11515 }
11516
11517 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11518 if (strcmp(field, cert_exts[i].ext) == 0) {
11519 cert_ext = &cert_exts[i];
11520 break;
11521 }
11522 }
11523
11524 /* this is the default type, the field is not supported */
11525 if (cert_ext == NULL) {
11526 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11527 errcode |= ERR_ALERT | ERR_FATAL;
11528 goto end;
11529 }
11530
11531 /* appply the change on the duplicate */
11532 if (cert_exts->load(filename, payload, ckch, &err) != 0) {
11533 memprintf(&err, "%sCan't load the payload\n", err ? err : "");
11534 errcode |= ERR_ALERT | ERR_FATAL;
11535 goto end;
11536 }
11537 lua_pop(L, 1);
11538 }
11539
11540 /* store the pointers on the lua stack */
11541 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11542 lua_ckchs[0] = old_ckchs;
11543 lua_ckchs[1] = new_ckchs;
11544 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11545 *lua_ckchi = NULL;
11546
11547 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11548 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11549
11550end:
11551 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11552
11553 if (errcode & ERR_CODE) {
11554 ckch_store_free(new_ckchs);
11555 WILL_LJMP(luaL_error(L, "%s", err));
11556 }
11557 free(err);
11558
11559 return 0;
11560}
11561
William Lallemand52139182022-03-30 15:05:42 +020011562#else
11563
11564__LJMP static int hlua_ckch_set(lua_State *L)
11565{
11566 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11567
11568 return 0;
11569}
11570#endif /* ! USE_OPENSSL */
11571
11572
11573
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011574/* This function can fail with an abort() due to an Lua critical error.
11575 * We are in the initialisation process of HAProxy, this abort() is
11576 * tolerated.
11577 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011578int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011579{
11580 struct hlua_init_function *init;
11581 const char *msg;
11582 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011583 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011584 const char *kind;
11585 const char *trace;
11586 int return_status = 1;
11587#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11588 int nres;
11589#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011590
Willy Tarreaucdb53462020-12-02 12:12:00 +010011591 /* disable memory limit checks if limit is not set */
11592 if (!hlua_global_allocator.limit)
11593 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11594
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011595 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011596 if (setjmp(safe_ljmp_env) != 0) {
11597 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011598 if (lua_type(L, -1) == LUA_TSTRING)
11599 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011600 else
11601 error = "critical error";
11602 fprintf(stderr, "Lua post-init: %s.\n", error);
11603 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011604 } else {
11605 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011606 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011607
Thierry Fournierb8cef172020-11-28 15:37:17 +010011608 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011609
Thierry Fournierc7492592020-11-28 23:57:24 +010011610 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011611 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011612
11613#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011614 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011615#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011616 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011617#endif
11618 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011619 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011620
11621 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011622 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011623 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011624
11625 case LUA_ERRERR:
11626 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011627 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011628 case LUA_ERRRUN:
11629 if (!kind)
11630 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011631 msg = lua_tostring(L, -1);
11632 lua_settop(L, 0); /* Empty the stack. */
11633 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011634 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011635 if (msg)
11636 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11637 else
11638 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11639 return_status = 0;
11640 break;
11641
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011642 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011643 /* Unknown error */
11644 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011645 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011646 case LUA_YIELD:
11647 /* yield is not configured at this step, this state doesn't happen */
11648 if (!kind)
11649 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011650 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011651 case LUA_ERRMEM:
11652 if (!kind)
11653 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011654 lua_settop(L, 0);
11655 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011656 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011657 ha_alert("Lua init: %s: %s\n", kind, trace);
11658 return_status = 0;
11659 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011660 }
Thierry Fournier670db242020-11-28 10:49:59 +010011661 if (!return_status)
11662 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011663 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011664
11665 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011666 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011667}
11668
Thierry Fournierb8cef172020-11-28 15:37:17 +010011669int hlua_post_init()
11670{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011671 int ret;
11672 int i;
11673 int errors;
11674 char *err = NULL;
11675 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011676 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011677
Willy Tarreaub1310492021-08-30 09:35:18 +020011678#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011679 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011680 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011681 int saved_used_backed = global.ssl_used_backend;
11682 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011683 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011684 global.ssl_used_backend = saved_used_backed;
11685 }
11686#endif
11687
Thierry Fournierc7492592020-11-28 23:57:24 +010011688 /* Perform post init of common thread */
11689 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011690 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011691 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11692 if (ret == 0)
11693 return 0;
11694
11695 /* init remaining lua states and load files */
11696 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11697
11698 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011699 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011700
11701 /* Init lua state */
11702 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11703
11704 /* Load lua files */
11705 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11706 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11707 if (ret != 0) {
11708 ha_alert("Lua init: %s\n", err);
11709 return 0;
11710 }
11711 }
11712 }
11713
11714 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011715 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011716
11717 /* Execute post init for all states */
11718 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11719
11720 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011721 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011722
11723 /* run post init */
11724 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11725 if (ret == 0)
11726 return 0;
11727 }
11728
11729 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011730 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011731
11732 /* control functions registering. Each function must have:
11733 * - only the function_ref[0] set positive and all other to -1
11734 * - only the function_ref[0] set to -1 and all other positive
11735 * This ensure a same reference is not used both in shared
11736 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011737 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011738 * complicated to found for the end user.
11739 */
11740 errors = 0;
11741 list_for_each_entry(fcn, &referenced_functions, l) {
11742 ret = 0;
11743 for (i = 1; i < global.nbthread + 1; i++) {
11744 if (fcn->function_ref[i] == -1)
11745 ret--;
11746 else
11747 ret++;
11748 }
11749 if (abs(ret) != global.nbthread) {
11750 ha_alert("Lua function '%s' is not referenced in all thread. "
11751 "Expect function in all thread or in none thread.\n", fcn->name);
11752 errors++;
11753 continue;
11754 }
11755
11756 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011757 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11758 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011759 "exclusive.\n", fcn->name);
11760 errors++;
11761 }
11762 }
11763
Christopher Faulet69c581a2021-05-31 08:54:04 +020011764 /* Do the same with registered filters */
11765 list_for_each_entry(reg_flt, &referenced_filters, l) {
11766 ret = 0;
11767 for (i = 1; i < global.nbthread + 1; i++) {
11768 if (reg_flt->flt_ref[i] == -1)
11769 ret--;
11770 else
11771 ret++;
11772 }
11773 if (abs(ret) != global.nbthread) {
11774 ha_alert("Lua filter '%s' is not referenced in all thread. "
11775 "Expect function in all thread or in none thread.\n", reg_flt->name);
11776 errors++;
11777 continue;
11778 }
11779
11780 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11781 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11782 "and per-thread Lua context (through lua-load-per-thread). these two context "
11783 "exclusive.\n", fcn->name);
11784 errors++;
11785 }
11786 }
11787
11788
Thierry Fournier59f11be2020-11-29 00:37:41 +010011789 if (errors > 0)
11790 return 0;
11791
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011792 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011793 * -1 in order to have probably a segfault if someone use it
11794 */
11795 hlua_state_id = -1;
11796
11797 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011798}
11799
Willy Tarreau32f61e22015-03-18 17:54:59 +010011800/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11801 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11802 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011803 * allocation. <nsize> is the requested new size. A new allocation is
11804 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011805 * zero. This one verifies that the limits are respected but is optimized
11806 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011807 *
11808 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11809 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11810 * that and will simply allocate zero as if it were the result of malloc(0),
11811 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11812 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011813 */
11814static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11815{
11816 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011817 size_t limit, old, new;
11818
11819 /* a limit of ~0 means unlimited and boot complete, so there's no need
11820 * for accounting anymore.
11821 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011822 if (likely(~zone->limit == 0)) {
11823 if (!nsize)
11824 ha_free(&ptr);
11825 else
11826 ptr = realloc(ptr, nsize);
11827 return ptr;
11828 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011829
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011830 if (!ptr)
11831 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011832
Willy Tarreaucdb53462020-12-02 12:12:00 +010011833 /* enforce strict limits across all threads */
11834 limit = zone->limit;
11835 old = _HA_ATOMIC_LOAD(&zone->allocated);
11836 do {
11837 new = old + nsize - osize;
11838 if (unlikely(nsize && limit && new > limit))
11839 return NULL;
11840 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011841
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011842 if (!nsize)
11843 ha_free(&ptr);
11844 else
11845 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011846
11847 if (unlikely(!ptr && nsize)) // failed
11848 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11849
11850 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011851 return ptr;
11852}
11853
Thierry Fournierecb83c22020-11-28 15:49:44 +010011854/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011855 * We are in the initialisation process of HAProxy, this abort() is
11856 * tolerated.
11857 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011858lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011859{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011860 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011861 int idx;
11862 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011863 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011864 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011865 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011866 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011867 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011868 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011869
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011870 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011871 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011872
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011873 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011874 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011875 *context = NULL;
11876
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011877 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011878 * the Lua function can fail with an abort. We are in the initialisation
11879 * process of HAProxy, this abort() is tolerated.
11880 */
11881
Thierry Fournier3c539322020-11-28 16:05:05 +010011882 /* Call post initialisation function in safe environment. */
11883 if (setjmp(safe_ljmp_env) != 0) {
11884 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011885 if (lua_type(L, -1) == LUA_TSTRING)
11886 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011887 else
11888 error_msg = "critical error";
11889 fprintf(stderr, "Lua init: %s.\n", error_msg);
11890 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011891 } else {
11892 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011893 }
11894
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011895 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011896 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011897#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11898#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11899#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011900 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011901#endif
11902#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011903 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011904#endif
11905#undef HLUA_PREPEND_PATH_TOSTRING
11906#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011907
Thierry Fournier59f11be2020-11-29 00:37:41 +010011908 /* Apply configured prepend path */
11909 list_for_each_entry(pp, &prepend_path_list, l)
11910 hlua_prepend_path(L, pp->type, pp->path);
11911
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011912 /*
11913 *
11914 * Create "core" object.
11915 *
11916 */
11917
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011918 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011919 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011920
Thierry Fournierecb83c22020-11-28 15:49:44 +010011921 /* set the thread id */
11922 hlua_class_const_int(L, "thread", thread_num);
11923
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011924 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011925 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011926 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011927
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011928 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011929 hlua_class_function(L, "register_init", hlua_register_init);
11930 hlua_class_function(L, "register_task", hlua_register_task);
11931 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11932 hlua_class_function(L, "register_converters", hlua_register_converters);
11933 hlua_class_function(L, "register_action", hlua_register_action);
11934 hlua_class_function(L, "register_service", hlua_register_service);
11935 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011936 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011937 hlua_class_function(L, "yield", hlua_yield);
11938 hlua_class_function(L, "set_nice", hlua_set_nice);
11939 hlua_class_function(L, "sleep", hlua_sleep);
11940 hlua_class_function(L, "msleep", hlua_msleep);
11941 hlua_class_function(L, "add_acl", hlua_add_acl);
11942 hlua_class_function(L, "del_acl", hlua_del_acl);
11943 hlua_class_function(L, "set_map", hlua_set_map);
11944 hlua_class_function(L, "del_map", hlua_del_map);
11945 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011946 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011947 hlua_class_function(L, "log", hlua_log);
11948 hlua_class_function(L, "Debug", hlua_log_debug);
11949 hlua_class_function(L, "Info", hlua_log_info);
11950 hlua_class_function(L, "Warning", hlua_log_warning);
11951 hlua_class_function(L, "Alert", hlua_log_alert);
11952 hlua_class_function(L, "done", hlua_done);
11953 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011954
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011955 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011956
11957 /*
11958 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011959 * Create "act" object.
11960 *
11961 */
11962
11963 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011964 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011965
11966 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011967 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11968 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11969 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11970 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11971 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11972 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11973 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11974 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011975
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011976 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011977
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011978 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011979
11980 /*
11981 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011982 * Create "Filter" object.
11983 *
11984 */
11985
11986 /* This table entry is the object "filter" base. */
11987 lua_newtable(L);
11988
11989 /* push flags and constants */
11990 hlua_class_const_int(L, "CONTINUE", 1);
11991 hlua_class_const_int(L, "WAIT", 0);
11992 hlua_class_const_int(L, "ERROR", -1);
11993
11994 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
11995
Christopher Fauletc404f112020-02-26 15:03:09 +010011996 hlua_class_function(L, "wake_time", hlua_set_wake_time);
11997 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
11998 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
11999
Christopher Faulet69c581a2021-05-31 08:54:04 +020012000 lua_setglobal(L, "filter");
12001
12002 /*
12003 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012004 * Register class Map
12005 *
12006 */
12007
12008 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012009 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012010
12011 /* register pattern types. */
12012 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012013 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012014 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012015 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012016 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012017 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012018
12019 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012020 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012021
12022 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012023 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012024
Ilya Shipitsind4259502020-04-08 01:07:56 +050012025 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012026 lua_pushstring(L, "__index");
12027 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012028
12029 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012030 hlua_class_function(L, "lookup", hlua_map_lookup);
12031 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012032
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012033 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012034
Thierry Fournier45e78d72016-02-19 18:34:46 +010012035 /* Register previous table in the registry with reference and named entry.
12036 * The function hlua_register_metatable() pops the stack, so we
12037 * previously create a copy of the table.
12038 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012039 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12040 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012041
12042 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012043 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012044
12045 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012046 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012047
12048 /*
12049 *
William Lallemand30fcca12022-03-30 12:03:12 +020012050 * Register "CertCache" class
12051 *
12052 */
12053
12054 /* Create and fill the metatable. */
12055 lua_newtable(L);
12056 /* Register */
12057 hlua_class_function(L, "set", hlua_ckch_set);
12058 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12059
12060 /*
12061 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012062 * Register class Channel
12063 *
12064 */
12065
12066 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012067 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012068
Ilya Shipitsind4259502020-04-08 01:07:56 +050012069 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012070 lua_pushstring(L, "__index");
12071 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012072
12073 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012074 hlua_class_function(L, "data", hlua_channel_get_data);
12075 hlua_class_function(L, "line", hlua_channel_get_line);
12076 hlua_class_function(L, "set", hlua_channel_set_data);
12077 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012078 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012079 hlua_class_function(L, "prepend", hlua_channel_prepend);
12080 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012081 hlua_class_function(L, "send", hlua_channel_send);
12082 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012083 hlua_class_function(L, "input", hlua_channel_get_in_len);
12084 hlua_class_function(L, "output", hlua_channel_get_out_len);
12085 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012086 hlua_class_function(L, "is_full", hlua_channel_is_full);
12087 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012088
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012089 /* Deprecated API */
12090 hlua_class_function(L, "get", hlua_channel_get);
12091 hlua_class_function(L, "dup", hlua_channel_dup);
12092 hlua_class_function(L, "getline", hlua_channel_getline);
12093 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12094 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12095
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012096 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012097
12098 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012099 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012100
12101 /*
12102 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012103 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012104 *
12105 */
12106
12107 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012108 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012109
Ilya Shipitsind4259502020-04-08 01:07:56 +050012110 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012111 lua_pushstring(L, "__index");
12112 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012113
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012114 /* Browse existing fetches and create the associated
12115 * object method.
12116 */
12117 sf = NULL;
12118 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012119 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12120 * by an underscore.
12121 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012122 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012123 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012124 if (*p == '.' || *p == '-' || *p == '+')
12125 *p = '_';
12126
12127 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012128 lua_pushstring(L, trash.area);
12129 lua_pushlightuserdata(L, sf);
12130 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12131 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012132 }
12133
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012134 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012135
12136 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012137 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012138
12139 /*
12140 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012141 * Register class Converters
12142 *
12143 */
12144
12145 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012146 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012147
12148 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012149 lua_pushstring(L, "__index");
12150 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012151
12152 /* Browse existing converters and create the associated
12153 * object method.
12154 */
12155 sc = NULL;
12156 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012157 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12158 * by an underscore.
12159 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012160 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012161 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012162 if (*p == '.' || *p == '-' || *p == '+')
12163 *p = '_';
12164
12165 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012166 lua_pushstring(L, trash.area);
12167 lua_pushlightuserdata(L, sc);
12168 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12169 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012170 }
12171
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012172 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012173
12174 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012175 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012176
12177 /*
12178 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012179 * Register class HTTP
12180 *
12181 */
12182
12183 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012184 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012185
Ilya Shipitsind4259502020-04-08 01:07:56 +050012186 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012187 lua_pushstring(L, "__index");
12188 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012189
12190 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012191 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12192 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12193 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12194 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12195 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12196 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12197 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12198 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12199 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12200 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012201
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012202 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12203 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12204 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12205 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12206 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12207 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12208 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012209
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012210 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012211
12212 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012213 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012214
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012215 /*
12216 *
12217 * Register class HTTPMessage
12218 *
12219 */
12220
12221 /* Create and fill the metatable. */
12222 lua_newtable(L);
12223
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012224 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012225 lua_pushstring(L, "__index");
12226 lua_newtable(L);
12227
12228 /* Register Lua functions. */
12229 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12230 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12231 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12232 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12233 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12234 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12235 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12236 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12237 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12238 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12239 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12240 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12241 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12242 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12243 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12244 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12245 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12246 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12247
12248 hlua_class_function(L, "body", hlua_http_msg_get_body);
12249 hlua_class_function(L, "set", hlua_http_msg_set_data);
12250 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12251 hlua_class_function(L, "append", hlua_http_msg_append);
12252 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12253 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12254 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12255 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12256
12257 hlua_class_function(L, "send", hlua_http_msg_send);
12258 hlua_class_function(L, "forward", hlua_http_msg_forward);
12259
12260 lua_rawset(L, -3);
12261
12262 /* Register previous table in the registry with reference and named entry. */
12263 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012264
12265 /*
12266 *
12267 * Register class HTTPClient
12268 *
12269 */
12270
12271 /* Create and fill the metatable. */
12272 lua_newtable(L);
12273 lua_pushstring(L, "__index");
12274 lua_newtable(L);
12275 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012276 hlua_class_function(L, "head", hlua_httpclient_head);
12277 hlua_class_function(L, "put", hlua_httpclient_put);
12278 hlua_class_function(L, "post", hlua_httpclient_post);
12279 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012280 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012281 /* Register the garbage collector entry. */
12282 lua_pushstring(L, "__gc");
12283 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12284 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12285
William Lallemand3956c4e2021-09-21 16:25:15 +020012286
12287
12288 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012289 /*
12290 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012291 * Register class AppletTCP
12292 *
12293 */
12294
12295 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012296 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012297
Ilya Shipitsind4259502020-04-08 01:07:56 +050012298 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012299 lua_pushstring(L, "__index");
12300 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012301
12302 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012303 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12304 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12305 hlua_class_function(L, "send", hlua_applet_tcp_send);
12306 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12307 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12308 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12309 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12310 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012311
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012312 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012313
12314 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012315 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012316
12317 /*
12318 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012319 * Register class AppletHTTP
12320 *
12321 */
12322
12323 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012324 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012325
Ilya Shipitsind4259502020-04-08 01:07:56 +050012326 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012327 lua_pushstring(L, "__index");
12328 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012329
12330 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012331 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12332 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12333 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12334 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12335 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12336 hlua_class_function(L, "getline", hlua_applet_http_getline);
12337 hlua_class_function(L, "receive", hlua_applet_http_recv);
12338 hlua_class_function(L, "send", hlua_applet_http_send);
12339 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12340 hlua_class_function(L, "set_status", hlua_applet_http_status);
12341 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012342
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012343 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012344
12345 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012346 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012347
12348 /*
12349 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012350 * Register class TXN
12351 *
12352 */
12353
12354 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012355 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012356
Ilya Shipitsind4259502020-04-08 01:07:56 +050012357 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012358 lua_pushstring(L, "__index");
12359 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012360
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012361 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012362 hlua_class_function(L, "set_priv", hlua_set_priv);
12363 hlua_class_function(L, "get_priv", hlua_get_priv);
12364 hlua_class_function(L, "set_var", hlua_set_var);
12365 hlua_class_function(L, "unset_var", hlua_unset_var);
12366 hlua_class_function(L, "get_var", hlua_get_var);
12367 hlua_class_function(L, "done", hlua_txn_done);
12368 hlua_class_function(L, "reply", hlua_txn_reply_new);
12369 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12370 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12371 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12372 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12373 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12374 hlua_class_function(L, "deflog", hlua_txn_deflog);
12375 hlua_class_function(L, "log", hlua_txn_log);
12376 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12377 hlua_class_function(L, "Info", hlua_txn_log_info);
12378 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12379 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012380
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012381 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012382
12383 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012384 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012385
12386 /*
12387 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012388 * Register class reply
12389 *
12390 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012391 lua_newtable(L);
12392 lua_pushstring(L, "__index");
12393 lua_newtable(L);
12394 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12395 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12396 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12397 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12398 lua_settable(L, -3); /* Sets the __index entry. */
12399 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012400
12401
12402 /*
12403 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012404 * Register class Socket
12405 *
12406 */
12407
12408 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012409 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012410
Ilya Shipitsind4259502020-04-08 01:07:56 +050012411 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012412 lua_pushstring(L, "__index");
12413 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012414
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012415#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012416 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012417#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012418 hlua_class_function(L, "connect", hlua_socket_connect);
12419 hlua_class_function(L, "send", hlua_socket_send);
12420 hlua_class_function(L, "receive", hlua_socket_receive);
12421 hlua_class_function(L, "close", hlua_socket_close);
12422 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12423 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12424 hlua_class_function(L, "setoption", hlua_socket_setoption);
12425 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012426
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012427 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012428
12429 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012430 lua_pushstring(L, "__gc");
12431 lua_pushcclosure(L, hlua_socket_gc, 0);
12432 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 previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012435 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012436
Thierry Fournieraafc7772020-12-04 11:47:47 +010012437 lua_atpanic(L, hlua_panic_safe);
12438
12439 return L;
12440}
12441
12442void hlua_init(void) {
12443 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012444 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012445#ifdef USE_OPENSSL
12446 struct srv_kw *kw;
12447 int tmp_error;
12448 char *error;
12449 char *args[] = { /* SSL client configuration. */
12450 "ssl",
12451 "verify",
12452 "none",
12453 NULL
12454 };
12455#endif
12456
12457 /* Init post init function list head */
12458 for (i = 0; i < MAX_THREADS + 1; i++)
12459 LIST_INIT(&hlua_init_functions[i]);
12460
12461 /* Init state for common/shared lua parts */
12462 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012463 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012464 hlua_states[0] = hlua_init_state(0);
12465
12466 /* Init state 1 for thread 0. We have at least one thread. */
12467 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012468 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012469 hlua_states[1] = hlua_init_state(1);
12470
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012471 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012472 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012473 if (!socket_proxy) {
12474 fprintf(stderr, "Lua init: %s\n", errmsg);
12475 exit(1);
12476 }
12477 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012478
12479 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012480 socket_tcp = new_server(socket_proxy);
12481 if (!socket_tcp) {
12482 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12483 exit(1);
12484 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012485
12486#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012487 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012488 socket_ssl = new_server(socket_proxy);
12489 if (!socket_ssl) {
12490 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12491 exit(1);
12492 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012493
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012494 socket_ssl->use_ssl = 1;
12495 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012496
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012497 for (i = 0; args[i] != NULL; i++) {
12498 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012499 /*
12500 *
12501 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012502 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012503 * features like client certificates and ssl_verify.
12504 *
12505 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012506 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012507 if (tmp_error != 0) {
12508 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12509 abort(); /* This must be never arrives because the command line
12510 not editable by the user. */
12511 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012512 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012513 }
12514 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012515#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012516
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012517}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012518
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012519static void hlua_deinit()
12520{
Willy Tarreau186f3762020-12-04 11:48:12 +010012521 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012522 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12523
12524 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12525 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012526
12527 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12528 if (hlua_states[thr])
12529 lua_close(hlua_states[thr]);
12530 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012531
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012532 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012533
Willy Tarreau0f143af2021-03-05 10:41:48 +010012534#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012535 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012536#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012537
12538 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012539}
12540
12541REGISTER_POST_DEINIT(hlua_deinit);
12542
Willy Tarreau80713382018-11-26 10:19:54 +010012543static void hlua_register_build_options(void)
12544{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012545 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012546
Willy Tarreaubb57d942016-12-21 19:04:56 +010012547 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12548 hap_register_build_opts(ptr, 1);
12549}
Willy Tarreau80713382018-11-26 10:19:54 +010012550
12551INITCALL0(STG_REGISTER, hlua_register_build_options);