blob: 705c15c19a2b5edaa29d7a56f84270a457e5b2c9 [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 Fauleta9e8b392022-03-23 11:01:09 +01002921 struct cs_endpoint *endp;
Christopher Faulet13a35e52021-12-20 15:34:16 +01002922 struct conn_stream *cs;
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002923 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002924
2925 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002926 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002927 hlua_pusherror(L, "socket: full stack");
2928 goto out_fail_conf;
2929 }
2930
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002931 /* Create the object: obj[0] = userdata. */
2932 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002934 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002935 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002936 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002937
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002938 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002939 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002940 hlua_pusherror(L, "socket: uninitialized pools.");
2941 goto out_fail_conf;
2942 }
2943
Willy Tarreau87b09662015-04-03 00:22:06 +02002944 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002945 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2946 lua_setmetatable(L, -2);
2947
Willy Tarreaud420a972015-04-06 00:39:18 +02002948 /* Create the applet context */
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002949 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002950 if (!appctx) {
2951 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002952 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002953 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002954
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002955 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002956 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002957 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2958 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002959
Willy Tarreaud420a972015-04-06 00:39:18 +02002960 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002961 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002962 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002963 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet13a35e52021-12-20 15:34:16 +01002964 goto out_fail_appctx;
2965 }
2966
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002967 endp = cs_endpoint_new();
2968 if (!endp)
2969 goto out_fail_sess;
2970 endp->target = appctx;
2971 endp->ctx = appctx;
2972 endp->flags |= CS_EP_T_APPLET;
2973
2974 cs = cs_new_from_applet(endp, sess, &BUF_NULL);
2975 if (!cs) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002976 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002977 cs_endpoint_free(endp);
Christopher Faulet2479e5f2022-01-19 14:50:11 +01002978 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002979 }
2980
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002981 s = DISGUISE(cs_strm(cs));
Christopher Faulet2479e5f2022-01-19 14:50:11 +01002982
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002983 /* Initialise cross reference between stream and Lua socket object. */
2984 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002985
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002986 /* Configure "right" stream interface. this "si" is used to connect
2987 * and retrieve data from the server. The connection is initialized
2988 * with the "struct server".
2989 */
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002990 si_set_state(cs_si(s->csb), SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002991
2992 /* Force destination server. */
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002993 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
2994 s->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002995
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002996 return 1;
2997
Willy Tarreaud420a972015-04-06 00:39:18 +02002998 out_fail_sess:
Christopher Faulet13a35e52021-12-20 15:34:16 +01002999 session_free(sess);
3000 out_fail_appctx:
Willy Tarreaud420a972015-04-06 00:39:18 +02003001 appctx_free(appctx);
3002 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003003 WILL_LJMP(lua_error(L));
3004 return 0;
3005}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003006
3007/*
3008 *
3009 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003010 * Class Channel
3011 *
3012 *
3013 */
3014
3015/* Returns the struct hlua_channel join to the class channel in the
3016 * stack entry "ud" or throws an argument error.
3017 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003018__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003019{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003020 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003021}
3022
Willy Tarreau47860ed2015-03-10 14:07:50 +01003023/* Pushes the channel onto the top of the stack. If the stask does not have a
3024 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003025 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003026static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003027{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003028 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003029 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003030 return 0;
3031
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003032 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003033 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003034 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003035
3036 /* Pop a class sesison metatable and affect it to the userdata. */
3037 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3038 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003039 return 1;
3040}
3041
Christopher Faulet9f55a502020-02-25 15:21:02 +01003042/* Helper function returning a filter attached to a channel at the position <ud>
3043 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003044 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003045 * initialized.
3046 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003047static 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 +01003048{
3049 struct filter *filter = NULL;
3050
3051 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3052 struct hlua_flt_ctx *flt_ctx;
3053
3054 filter = lua_touserdata (L, -1);
3055 flt_ctx = filter->ctx;
3056 if (hlua_filter_from_payload(filter)) {
3057 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3058 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3059 }
3060 }
3061
3062 lua_pop(L, 1);
3063 return filter;
3064}
3065
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003066/* Copies <len> bytes of data present in the channel's buffer, starting at the
3067* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003068* responsibility to ensure <len> and <offset> are valid. It always return the
3069* length of the built string. <len> may be 0, in this case, an empty string is
3070* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003071*/
3072static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003073{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003074 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003075 luaL_Buffer b;
3076
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003077 block1 = len;
3078 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3079 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3080 block2 = len - block1;
3081
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003082 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003083 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3084 if (block2)
3085 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003086 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003087 return len;
3088}
3089
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003090/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3091 * function returns -1 if data cannot be copied. Otherwise, it returns the
3092 * number of bytes copied.
3093 */
3094static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3095{
3096 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003097
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003098 /* Nothing to do, just return */
3099 if (unlikely(istlen(str) == 0))
3100 goto end;
3101
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003102 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003103 ret = -1;
3104 goto end;
3105 }
3106 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3107
3108 end:
3109 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003110}
3111
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003112/* Removes <len> bytes of data at the absolute position <offset>.
3113 */
3114static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3115{
3116 size_t end = offset + len;
3117
3118 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3119 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3120 b_data(&chn->buf) - end, -len);
3121 b_sub(&chn->buf, len);
3122}
3123
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003124/* Copies input data in the channel's buffer. It is possible to set a specific
3125 * offset (0 by default) and a length (all remaining input data starting for the
3126 * offset by default). If there is not enough input data and more data can be
3127 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003128 *
3129 * From an action, All input data are considered. For a filter, the offset and
3130 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003131 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003132__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003133{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003134 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003135 struct filter *filter;
3136 size_t input, output;
3137 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003138
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003139 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003140
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003141 output = co_data(chn);
3142 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003143
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003144 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3145 if (filter && !hlua_filter_from_payload(filter))
3146 WILL_LJMP(lua_error(L));
3147
3148 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003149 if (lua_gettop(L) > 1) {
3150 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3151 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003152 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003153 offset += output;
3154 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003155 lua_pushfstring(L, "offset out of range.");
3156 WILL_LJMP(lua_error(L));
3157 }
3158 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003159 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003160 if (lua_gettop(L) == 3) {
3161 len = MAY_LJMP(luaL_checkinteger(L, 3));
3162 if (!len)
3163 goto dup;
3164 if (len == -1)
3165 len = global.tune.bufsize;
3166 if (len < 0) {
3167 lua_pushfstring(L, "length out of range.");
3168 WILL_LJMP(lua_error(L));
3169 }
3170 }
3171
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003172 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003173 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3174 /* Yield waiting for more data, as requested */
3175 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3176 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003177 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003178 }
3179
3180 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003181 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003182 return 1;
3183}
3184
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003185/* Copies the first line (including the trailing LF) of input data in the
3186 * channel's buffer. It is possible to set a specific offset (0 by default) and
3187 * a length (all remaining input data starting for the offset by default). If
3188 * there is not enough input data and more data can be received, the function
3189 * yields. If a length is explicitly specified, no more data are
3190 * copied. Otherwise, if no LF is found and more data can be received, this
3191 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003192 *
3193 * From an action, All input data are considered. For a filter, the offset and
3194 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003195 */
3196__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003197{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003198 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003199 struct filter *filter;
3200 size_t l, input, output;
3201 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003202
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003203 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003204 output = co_data(chn);
3205 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003206
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003207 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3208 if (filter && !hlua_filter_from_payload(filter))
3209 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003211 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003212 if (lua_gettop(L) > 1) {
3213 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3214 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003215 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003216 offset += output;
3217 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003218 lua_pushfstring(L, "offset out of range.");
3219 WILL_LJMP(lua_error(L));
3220 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003221 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003222
3223 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003224 if (lua_gettop(L) == 3) {
3225 len = MAY_LJMP(luaL_checkinteger(L, 3));
3226 if (!len)
3227 goto dup;
3228 if (len == -1)
3229 len = global.tune.bufsize;
3230 if (len < 0) {
3231 lua_pushfstring(L, "length out of range.");
3232 WILL_LJMP(lua_error(L));
3233 }
3234 }
3235
3236 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003237 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003238 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003239 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003240 len = l+1;
3241 goto dup;
3242 }
3243 }
3244
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003245 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003246 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3247 /* Yield waiting for more data */
3248 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3249 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003250 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003251 }
3252
3253 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003254 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003255 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003256}
3257
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003258/* [ DEPRECATED ]
3259 *
3260 * Duplicate all input data foud in the channel's buffer. The data are not
3261 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003262 *
3263 * From an action, All input data are considered. For a filter, the offset and
3264 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003265 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003266__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003267{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003268 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003269 struct filter *filter;
3270 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003271
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003272 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003273 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003274 if (IS_HTX_STRM(chn_strm(chn))) {
3275 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3276 WILL_LJMP(lua_error(L));
3277 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003278
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003279 offset = co_data(chn);
3280 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003281
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003282 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3283 if (filter && !hlua_filter_from_payload(filter))
3284 WILL_LJMP(lua_error(L));
3285
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003286 if (!ci_data(chn) && channel_input_closed(chn)) {
3287 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003288 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003289 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003290
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003291 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003292 return 1;
3293}
3294
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003295/* [ DEPRECATED ]
3296 *
3297 * Get all input data foud in the channel's buffer. The data are removed from
3298 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3299 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003300 *
3301 * From an action, All input data are considered. For a filter, the offset and
3302 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003303 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003304__LJMP static int hlua_channel_get(lua_State *L)
3305{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003306 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003307 struct filter *filter;
3308 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003309 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003310
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003311 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003312 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3313 if (IS_HTX_STRM(chn_strm(chn))) {
3314 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3315 WILL_LJMP(lua_error(L));
3316 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003317
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003318 offset = co_data(chn);
3319 len = ci_data(chn);
3320
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003321 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3322 if (filter && !hlua_filter_from_payload(filter))
3323 WILL_LJMP(lua_error(L));
3324
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003325 if (!ci_data(chn) && channel_input_closed(chn)) {
3326 lua_pushnil(L);
3327 return 1;
3328 }
3329
3330 ret = _hlua_channel_dup(chn, L, offset, len);
3331 _hlua_channel_delete(chn, offset, ret);
3332 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003333}
3334
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003335/* This functions consumes and returns one line. If the channel is closed,
3336 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003337 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003338 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003339 *
3340 * From an action, All input data are considered. For a filter, the offset and
3341 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003342 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003343__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003344{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003345 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003346 struct filter *filter;
3347 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003348 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003349
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003350 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003351
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003352 offset = co_data(chn);
3353 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003354
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003355 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3356 if (filter && !hlua_filter_from_payload(filter))
3357 WILL_LJMP(lua_error(L));
3358
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003359 if (!ci_data(chn) && channel_input_closed(chn)) {
3360 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003361 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003362 }
3363
3364 for (l = 0; l < len; l++) {
3365 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3366 len = l+1;
3367 goto dup;
3368 }
3369 }
3370
3371 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3372 /* Yield waiting for more data */
3373 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3374 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003375
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003376 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003377 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003378 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003379 return 1;
3380}
3381
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003382/* [ DEPRECATED ]
3383 *
3384 * Check arguments for the function "hlua_channel_getline_yield".
3385 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003386__LJMP static int hlua_channel_getline(lua_State *L)
3387{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003388 struct channel *chn;
3389
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003390 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003391 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3392 if (IS_HTX_STRM(chn_strm(chn))) {
3393 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3394 WILL_LJMP(lua_error(L));
3395 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003396 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3397}
3398
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003399/* Retrieves a given amount of input data at the given offset. By default all
3400 * available input data are returned. The offset may be negactive to start from
3401 * the end of input data. The length may be -1 to set it to the maximum buffer
3402 * size.
3403 */
3404__LJMP static int hlua_channel_get_data(lua_State *L)
3405{
3406 struct channel *chn;
3407
3408 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3409 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3410 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3411 if (IS_HTX_STRM(chn_strm(chn))) {
3412 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3413 WILL_LJMP(lua_error(L));
3414 }
3415 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3416}
3417
3418/* Retrieves a given amount of input data at the given offset. By default all
3419 * available input data are returned. The offset may be negactive to start from
3420 * the end of input data. The length may be -1 to set it to the maximum buffer
3421 * size.
3422 */
3423__LJMP static int hlua_channel_get_line(lua_State *L)
3424{
3425 struct channel *chn;
3426
3427 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3428 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3429 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3430 if (IS_HTX_STRM(chn_strm(chn))) {
3431 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3432 WILL_LJMP(lua_error(L));
3433 }
3434 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3435}
3436
3437/* Appends a string into the input side of channel. It returns the length of the
3438 * written string, or -1 if the channel is closed or if the buffer size is too
3439 * little for the data. 0 may be returned if nothing is copied. This function
3440 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003441 *
3442 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003443 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003444__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003445{
Christopher Faulet23976d92021-08-06 09:59:49 +02003446 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003447 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003448 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003449 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003450 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003451
3452 MAY_LJMP(check_args(L, 2, "append"));
3453 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003454 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003455 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003456 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003457 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003458 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003459
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003460 offset = co_data(chn);
3461 len = ci_data(chn);
3462
3463 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3464 if (filter && !hlua_filter_from_payload(filter))
3465 WILL_LJMP(lua_error(L));
3466
3467 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3468 if (ret > 0 && filter) {
3469 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3470
3471 flt_update_offsets(filter, chn, ret);
3472 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3473 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003474 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003475 return 1;
3476}
3477
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003478/* Prepends a string into the input side of channel. It returns the length of the
3479 * written string, or -1 if the channel is closed or if the buffer size is too
3480 * little for the data. 0 may be returned if nothing is copied. This function
3481 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003482 *
3483 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003484 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003485__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003486{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003487 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003488 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003489 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003490 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003491 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003492
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003493 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003494 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003495 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3496 if (IS_HTX_STRM(chn_strm(chn))) {
3497 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3498 WILL_LJMP(lua_error(L));
3499 }
3500
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003501 offset = co_data(chn);
3502 len = ci_data(chn);
3503
3504 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3505 if (filter && !hlua_filter_from_payload(filter))
3506 WILL_LJMP(lua_error(L));
3507
3508 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3509 if (ret > 0 && filter) {
3510 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3511
3512 flt_update_offsets(filter, chn, ret);
3513 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3514 }
3515
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003516 lua_pushinteger(L, ret);
3517 return 1;
3518}
3519
3520/* Inserts a given amount of input data at the given offset by a string
3521 * content. By default the string is appended at the end of input data. It
3522 * returns the length of the written string, or -1 if the channel is closed or
3523 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003524 *
3525 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003526 */
3527__LJMP static int hlua_channel_insert_data(lua_State *L)
3528{
3529 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003530 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003531 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003532 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003533 int ret, offset;
3534
3535 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3536 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3537 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3538 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003539
3540 output = co_data(chn);
3541 input = ci_data(chn);
3542
3543 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3544 if (filter && !hlua_filter_from_payload(filter))
3545 WILL_LJMP(lua_error(L));
3546
3547 offset = input + output;
3548 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003549 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003550 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003551 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003552 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003553 if (offset < output || offset > output + input) {
3554 lua_pushfstring(L, "offset out of range.");
3555 WILL_LJMP(lua_error(L));
3556 }
3557 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003558 if (IS_HTX_STRM(chn_strm(chn))) {
3559 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3560 WILL_LJMP(lua_error(L));
3561 }
3562
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003563 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3564 if (ret > 0 && filter) {
3565 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003567 flt_update_offsets(filter, chn, ret);
3568 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003569 }
3570
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003571 lua_pushinteger(L, ret);
3572 return 1;
3573}
3574/* Replaces a given amount of input data at the given offset by a string
3575 * content. By default all remaining data are removed (offset = 0 and len =
3576 * -1). It returns the length of the written string, or -1 if the channel is
3577 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003578 *
3579 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003580 */
3581__LJMP static int hlua_channel_set_data(lua_State *L)
3582{
3583 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003584 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003585 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003586 size_t sz, input, output;
3587 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003588
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003589 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3590 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3591 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3592 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003593
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003594 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003595 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003596 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003597 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003598
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003599 output = co_data(chn);
3600 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003601
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003602 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3603 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003604 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003605
3606 offset = output;
3607 if (lua_gettop(L) > 2) {
3608 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3609 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003610 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003611 offset += output;
3612 if (offset < output || offset > input + output) {
3613 lua_pushfstring(L, "offset out of range.");
3614 WILL_LJMP(lua_error(L));
3615 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003616 }
3617
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003618 len = output + input - offset;
3619 if (lua_gettop(L) == 4) {
3620 len = MAY_LJMP(luaL_checkinteger(L, 4));
3621 if (!len)
3622 goto set;
3623 if (len == -1)
3624 len = output + input - offset;
3625 if (len < 0 || offset + len > output + input) {
3626 lua_pushfstring(L, "length out of range.");
3627 WILL_LJMP(lua_error(L));
3628 }
3629 }
3630
3631 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003632 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003633 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003634 lua_pushinteger(L, -1);
3635 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003636 _hlua_channel_delete(chn, offset, len);
3637 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3638 if (filter) {
3639 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3640
3641 len -= (ret > 0 ? ret : 0);
3642 flt_update_offsets(filter, chn, -len);
3643 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3644 }
3645
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003646 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003647 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003648 return 1;
3649}
3650
3651/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003652 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003653 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003654 *
3655 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003656 */
3657__LJMP static int hlua_channel_del_data(lua_State *L)
3658{
3659 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003660 struct filter *filter;
3661 size_t input, output;
3662 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003663
3664 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3665 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3666 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003667
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003668 if (IS_HTX_STRM(chn_strm(chn))) {
3669 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3670 WILL_LJMP(lua_error(L));
3671 }
3672
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003673 output = co_data(chn);
3674 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003675
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003676 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3677 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003678 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003679
3680 offset = output;
3681 if (lua_gettop(L) > 2) {
3682 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3683 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003684 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003685 offset += output;
3686 if (offset < output || offset > input + output) {
3687 lua_pushfstring(L, "offset out of range.");
3688 WILL_LJMP(lua_error(L));
3689 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003690 }
3691
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003692 len = output + input - offset;
3693 if (lua_gettop(L) == 4) {
3694 len = MAY_LJMP(luaL_checkinteger(L, 4));
3695 if (!len)
3696 goto end;
3697 if (len == -1)
3698 len = output + input - offset;
3699 if (len < 0 || offset + len > output + input) {
3700 lua_pushfstring(L, "length out of range.");
3701 WILL_LJMP(lua_error(L));
3702 }
3703 }
3704
3705 _hlua_channel_delete(chn, offset, len);
3706 if (filter) {
3707 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3708
3709 flt_update_offsets(filter, chn, -len);
3710 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3711 }
3712
3713 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003714 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003715 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003716}
3717
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003718/* Append data in the output side of the buffer. This data is immediately
3719 * sent. The function returns the amount of data written. If the buffer
3720 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003721 * if the channel is closed.
3722 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003723__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003724{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003725 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003726 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003727 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003728 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003729 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003730 struct hlua *hlua;
3731
3732 /* Get hlua struct, or NULL if we execute from main lua state */
3733 hlua = hlua_gethlua(L);
3734 if (!hlua) {
3735 lua_pushnil(L);
3736 return 1;
3737 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003738
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003739 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3740 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3741 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003742
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003743 offset = co_data(chn);
3744 len = ci_data(chn);
3745
3746 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3747 if (filter && !hlua_filter_from_payload(filter))
3748 WILL_LJMP(lua_error(L));
3749
3750
Willy Tarreau47860ed2015-03-10 14:07:50 +01003751 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003752 lua_pushinteger(L, -1);
3753 return 1;
3754 }
3755
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003756 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003757 if (len > sz -l) {
3758 if (filter) {
3759 lua_pushinteger(L, -1);
3760 return 1;
3761 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003762 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003763 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003764
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003765 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003766 if (ret == -1) {
3767 lua_pop(L, 1);
3768 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003769 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003770 }
3771 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003772 if (filter) {
3773 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3774
3775
3776 flt_update_offsets(filter, chn, ret);
3777 FLT_OFF(filter, chn) += ret;
3778 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3779 }
3780 else
3781 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003782
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003783 l += ret;
3784 lua_pop(L, 1);
3785 lua_pushinteger(L, l);
3786 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003787
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003788 if (l < sz) {
3789 /* Yield only if the channel's output is not empty.
3790 * Otherwise it means we cannot add more data. */
3791 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003792 return 1;
3793
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003794 /* If we are waiting for space in the response buffer, we
3795 * must set the flag WAKERESWR. This flag required the task
3796 * wake up if any activity is detected on the response buffer.
3797 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003798 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003799 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003800 else
3801 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003802 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003803 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003804
3805 return 1;
3806}
3807
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003808/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003809 * yield the LUA process, and resume it without checking the
3810 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003811 *
3812 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003813 */
3814__LJMP static int hlua_channel_send(lua_State *L)
3815{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003816 struct channel *chn;
3817
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003818 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003819 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3820 if (IS_HTX_STRM(chn_strm(chn))) {
3821 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3822 WILL_LJMP(lua_error(L));
3823 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003824 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003825 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003826}
3827
3828/* This function forward and amount of butes. The data pass from
3829 * the input side of the buffer to the output side, and can be
3830 * forwarded. This function never fails.
3831 *
3832 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003833 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003834 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003835__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003836{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003837 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003838 struct filter *filter;
3839 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003840 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003841 struct hlua *hlua;
3842
3843 /* Get hlua struct, or NULL if we execute from main lua state */
3844 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003845 if (!hlua) {
3846 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003847 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003848 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003849
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003850 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003851 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003852 l = MAY_LJMP(luaL_checkinteger(L, -1));
3853
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003854 offset = co_data(chn);
3855 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003856
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003857 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3858 if (filter && !hlua_filter_from_payload(filter))
3859 WILL_LJMP(lua_error(L));
3860
3861 max = fwd - l;
3862 if (max > len)
3863 max = len;
3864
3865 if (filter) {
3866 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3867
3868 FLT_OFF(filter, chn) += max;
3869 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3870 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3871 }
3872 else
3873 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003874
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003875 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003876 lua_pop(L, 1);
3877 lua_pushinteger(L, l);
3878
3879 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003880 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003881 /* The the input channel or the output channel are closed, we
3882 * must return the amount of data forwarded.
3883 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003884 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003885 return 1;
3886
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003887 /* If we are waiting for space data in the response buffer, we
3888 * must set the flag WAKERESWR. This flag required the task
3889 * wake up if any activity is detected on the response buffer.
3890 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003891 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003892 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003893 else
3894 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003895
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003896 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003897 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003898 }
3899
3900 return 1;
3901}
3902
3903/* Just check the input and prepare the stack for the previous
3904 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003905 *
3906 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003907 */
3908__LJMP static int hlua_channel_forward(lua_State *L)
3909{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003910 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003911
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003912 MAY_LJMP(check_args(L, 2, "forward"));
3913 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3914 if (IS_HTX_STRM(chn_strm(chn))) {
3915 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3916 WILL_LJMP(lua_error(L));
3917 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003918 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003919 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003920}
3921
3922/* Just returns the number of bytes available in the input
3923 * side of the buffer. This function never fails.
3924 */
3925__LJMP static int hlua_channel_get_in_len(lua_State *L)
3926{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003927 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003928 struct filter *filter;
3929 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003930
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003931 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003932 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003933
3934 output = co_data(chn);
3935 input = ci_data(chn);
3936 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3937 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3938 lua_pushinteger(L, input);
3939 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003940 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003941
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003942 lua_pushinteger(L, htx->data - co_data(chn));
3943 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003944 return 1;
3945}
3946
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003947/* Returns true if the channel is full. */
3948__LJMP static int hlua_channel_is_full(lua_State *L)
3949{
3950 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003951
3952 MAY_LJMP(check_args(L, 1, "is_full"));
3953 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003954 /* ignore the reserve, we are not on a producer side (ie in an
3955 * applet).
3956 */
3957 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003958 return 1;
3959}
3960
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003961/* Returns true if the channel may still receive data. */
3962__LJMP static int hlua_channel_may_recv(lua_State *L)
3963{
3964 struct channel *chn;
3965
3966 MAY_LJMP(check_args(L, 1, "may_recv"));
3967 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3968 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3969 return 1;
3970}
3971
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003972/* Returns true if the channel is the response channel. */
3973__LJMP static int hlua_channel_is_resp(lua_State *L)
3974{
3975 struct channel *chn;
3976
3977 MAY_LJMP(check_args(L, 1, "is_resp"));
3978 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3979
3980 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3981 return 1;
3982}
3983
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003984/* Just returns the number of bytes available in the output
3985 * side of the buffer. This function never fails.
3986 */
3987__LJMP static int hlua_channel_get_out_len(lua_State *L)
3988{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003989 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003990 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003991
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003992 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003993 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003994
3995 output = co_data(chn);
3996 input = ci_data(chn);
3997 hlua_channel_filter(L, 1, chn, &output, &input);
3998
3999 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004000 return 1;
4001}
4002
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004003/*
4004 *
4005 *
4006 * Class Fetches
4007 *
4008 *
4009 */
4010
4011/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004012 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004013 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004014__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004015{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004016 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004017}
4018
4019/* This function creates and push in the stack a fetch object according
4020 * with a current TXN.
4021 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004022static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004023{
Willy Tarreau7073c472015-04-06 11:15:40 +02004024 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004025
4026 /* Check stack size. */
4027 if (!lua_checkstack(L, 3))
4028 return 0;
4029
4030 /* Create the object: obj[0] = userdata.
4031 * Note that the base of the Fetches object is the
4032 * transaction object.
4033 */
4034 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004035 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004036 lua_rawseti(L, -2, 0);
4037
Willy Tarreau7073c472015-04-06 11:15:40 +02004038 hsmp->s = txn->s;
4039 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004040 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004041 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004042
4043 /* Pop a class sesison metatable and affect it to the userdata. */
4044 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4045 lua_setmetatable(L, -2);
4046
4047 return 1;
4048}
4049
4050/* This function is an LUA binding. It is called with each sample-fetch.
4051 * It uses closure argument to store the associated sample-fetch. It
4052 * returns only one argument or throws an error. An error is thrown
4053 * only if an error is encountered during the argument parsing. If
4054 * the "sample-fetch" function fails, nil is returned.
4055 */
4056__LJMP static int hlua_run_sample_fetch(lua_State *L)
4057{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004058 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004059 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004060 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004061 int i;
4062 struct sample smp;
4063
4064 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004065 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004066
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004067 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004068 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004069
Thierry FOURNIERca988662015-12-20 18:43:03 +01004070 /* Check execution authorization. */
4071 if (f->use & SMP_USE_HTTP_ANY &&
4072 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4073 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4074 "is not available in Lua services", f->kw);
4075 WILL_LJMP(lua_error(L));
4076 }
4077
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004078 /* Get extra arguments. */
4079 for (i = 0; i < lua_gettop(L) - 1; i++) {
4080 if (i >= ARGM_NBARGS)
4081 break;
4082 hlua_lua2arg(L, i + 2, &args[i]);
4083 }
4084 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004085 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004086
4087 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004088 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004089
4090 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004091 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004092 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004093 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004094 }
4095
4096 /* Initialise the sample. */
4097 memset(&smp, 0, sizeof(smp));
4098
4099 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004100 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004101 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004102 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004103 lua_pushstring(L, "");
4104 else
4105 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004106 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004107 }
4108
4109 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004110 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004111 hlua_smp2lua_str(L, &smp);
4112 else
4113 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004114
4115 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004116 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004117 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004118
4119 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004120 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004121 WILL_LJMP(lua_error(L));
4122 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004123}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004124
4125/*
4126 *
4127 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004128 * Class Converters
4129 *
4130 *
4131 */
4132
4133/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004134 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004135 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004136__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004137{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004138 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004139}
4140
4141/* This function creates and push in the stack a Converters object
4142 * according with a current TXN.
4143 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004144static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004145{
Willy Tarreau7073c472015-04-06 11:15:40 +02004146 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004147
4148 /* Check stack size. */
4149 if (!lua_checkstack(L, 3))
4150 return 0;
4151
4152 /* Create the object: obj[0] = userdata.
4153 * Note that the base of the Converters object is the
4154 * same than the TXN object.
4155 */
4156 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004157 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004158 lua_rawseti(L, -2, 0);
4159
Willy Tarreau7073c472015-04-06 11:15:40 +02004160 hsmp->s = txn->s;
4161 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004162 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004163 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004164
Willy Tarreau87b09662015-04-03 00:22:06 +02004165 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004166 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4167 lua_setmetatable(L, -2);
4168
4169 return 1;
4170}
4171
4172/* This function is an LUA binding. It is called with each converter.
4173 * It uses closure argument to store the associated converter. It
4174 * returns only one argument or throws an error. An error is thrown
4175 * only if an error is encountered during the argument parsing. If
4176 * the converter function function fails, nil is returned.
4177 */
4178__LJMP static int hlua_run_sample_conv(lua_State *L)
4179{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004180 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004181 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004182 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004183 int i;
4184 struct sample smp;
4185
4186 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004187 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004188
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004189 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004190 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004191
4192 /* Get extra arguments. */
4193 for (i = 0; i < lua_gettop(L) - 2; i++) {
4194 if (i >= ARGM_NBARGS)
4195 break;
4196 hlua_lua2arg(L, i + 3, &args[i]);
4197 }
4198 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004199 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004200
4201 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004202 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004203
4204 /* Run the special args checker. */
4205 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4206 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004207 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004208 }
4209
4210 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004211 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004212 if (!hlua_lua2smp(L, 2, &smp)) {
4213 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004214 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004215 }
4216
Willy Tarreau1777ea62016-03-10 16:15:46 +01004217 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4218
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004219 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004220 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004221 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004222 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004223 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004224 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004225 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4226 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004227 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004228 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004229 }
4230
4231 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004232 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004233 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004234 lua_pushstring(L, "");
4235 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004236 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004237 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004238 }
4239
4240 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004241 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004242 hlua_smp2lua_str(L, &smp);
4243 else
4244 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004245 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004246 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004247 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004248
4249 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004250 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004251 WILL_LJMP(lua_error(L));
4252 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004253}
4254
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004255/*
4256 *
4257 *
4258 * Class AppletTCP
4259 *
4260 *
4261 */
4262
4263/* Returns a struct hlua_txn if the stack entry "ud" is
4264 * a class stream, otherwise it throws an error.
4265 */
4266__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4267{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004268 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004269}
4270
4271/* This function creates and push in the stack an Applet object
4272 * according with a current TXN.
4273 */
4274static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4275{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004276 struct hlua_appctx *luactx;
Christopher Faulet86e1c332021-12-20 17:09:39 +01004277 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004278 struct stream *s = si_strm(si);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004279 struct proxy *p;
4280
4281 ALREADY_CHECKED(s);
4282 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004283
4284 /* Check stack size. */
4285 if (!lua_checkstack(L, 3))
4286 return 0;
4287
4288 /* Create the object: obj[0] = userdata.
4289 * Note that the base of the Converters object is the
4290 * same than the TXN object.
4291 */
4292 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004293 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004294 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004295 luactx->appctx = ctx;
4296 luactx->htxn.s = s;
4297 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004298
4299 /* Create the "f" field that contains a list of fetches. */
4300 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004301 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004302 return 0;
4303 lua_settable(L, -3);
4304
4305 /* Create the "sf" field that contains a list of stringsafe fetches. */
4306 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004307 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004308 return 0;
4309 lua_settable(L, -3);
4310
4311 /* Create the "c" field that contains a list of converters. */
4312 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004313 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004314 return 0;
4315 lua_settable(L, -3);
4316
4317 /* Create the "sc" field that contains a list of stringsafe converters. */
4318 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004319 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004320 return 0;
4321 lua_settable(L, -3);
4322
4323 /* Pop a class stream metatable and affect it to the table. */
4324 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4325 lua_setmetatable(L, -2);
4326
4327 return 1;
4328}
4329
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004330__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4331{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004332 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004333 struct stream *s;
4334 const char *name;
4335 size_t len;
4336 struct sample smp;
4337
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004338 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4339 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004340
4341 /* It is useles to retrieve the stream, but this function
4342 * runs only in a stream context.
4343 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004344 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004345 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004346 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004347
4348 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004349 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004350 hlua_lua2smp(L, 3, &smp);
4351
4352 /* Store the sample in a variable. */
4353 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004354
4355 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4356 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4357 else
4358 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4359
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004360 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004361}
4362
4363__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4364{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004365 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004366 struct stream *s;
4367 const char *name;
4368 size_t len;
4369 struct sample smp;
4370
4371 MAY_LJMP(check_args(L, 2, "unset_var"));
4372
4373 /* It is useles to retrieve the stream, but this function
4374 * runs only in a stream context.
4375 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004376 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004377 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004378 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004379
4380 /* Unset the variable. */
4381 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004382 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4383 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004384}
4385
4386__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4387{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004388 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004389 struct stream *s;
4390 const char *name;
4391 size_t len;
4392 struct sample smp;
4393
4394 MAY_LJMP(check_args(L, 2, "get_var"));
4395
4396 /* It is useles to retrieve the stream, but this function
4397 * runs only in a stream context.
4398 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004399 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004400 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004401 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004402
4403 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004404 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004405 lua_pushnil(L);
4406 return 1;
4407 }
4408
4409 return hlua_smp2lua(L, &smp);
4410}
4411
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004412__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4413{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004414 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4415 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004416 struct hlua *hlua;
4417
4418 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004419 if (!s->hlua)
4420 return 0;
4421 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004422
4423 MAY_LJMP(check_args(L, 2, "set_priv"));
4424
4425 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004426 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004427
4428 /* Get and store new value. */
4429 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4430 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4431
4432 return 0;
4433}
4434
4435__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4436{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004437 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4438 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004439 struct hlua *hlua;
4440
4441 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004442 if (!s->hlua) {
4443 lua_pushnil(L);
4444 return 1;
4445 }
4446 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004447
4448 /* Push configuration index in the stack. */
4449 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4450
4451 return 1;
4452}
4453
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004454/* If expected data not yet available, it returns a yield. This function
4455 * consumes the data in the buffer. It returns a string containing the
4456 * data. This string can be empty.
4457 */
4458__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4459{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004460 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004461 struct stream_interface *si = cs_si(luactx->appctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004462 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004463 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004464 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004465 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004466 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004467
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004468 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004469 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004470
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004471 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004472 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004473 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004474 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004475 }
4476
4477 /* End of data: commit the total strings and return. */
4478 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004479 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004480 return 1;
4481 }
4482
4483 /* Ensure that the block 2 length is usable. */
4484 if (ret == 1)
4485 len2 = 0;
4486
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004487 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004488 luaL_addlstring(&luactx->b, blk1, len1);
4489 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004490
4491 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004492 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004493 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004494 return 1;
4495}
4496
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004497/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004498__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4499{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004500 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004501
4502 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004503 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004504
4505 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4506}
4507
4508/* If expected data not yet available, it returns a yield. This function
4509 * consumes the data in the buffer. It returns a string containing the
4510 * data. This string can be empty.
4511 */
4512__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4513{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004514 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004515 struct stream_interface *si = cs_si(luactx->appctx->owner);
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004516 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004517 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004518 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004519 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004520 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004521 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004522
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004523 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004524 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004525
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004526 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004527 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004528 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004529 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004530 }
4531
4532 /* End of data: commit the total strings and return. */
4533 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004534 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004535 return 1;
4536 }
4537
4538 /* Ensure that the block 2 length is usable. */
4539 if (ret == 1)
4540 len2 = 0;
4541
4542 if (len == -1) {
4543
4544 /* If len == -1, catenate all the data avalaile and
4545 * yield because we want to get all the data until
4546 * the end of data stream.
4547 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004548 luaL_addlstring(&luactx->b, blk1, len1);
4549 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004550 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004551 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004552 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553
4554 } else {
4555
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004556 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004557 if (len1 > len)
4558 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004559 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004560 len -= len1;
4561
4562 /* Copy the second block. */
4563 if (len2 > len)
4564 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004565 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004566 len -= len2;
4567
4568 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004569 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004570
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004571 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004572 if (len > 0) {
4573 lua_pushinteger(L, len);
4574 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004575 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004576 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004577 }
4578
4579 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004580 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004581 return 1;
4582 }
4583
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004584 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004585 hlua_pusherror(L, "Lua: internal error");
4586 WILL_LJMP(lua_error(L));
4587 return 0;
4588}
4589
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004590/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004591__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4592{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004593 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004594 int len = -1;
4595
4596 if (lua_gettop(L) > 2)
4597 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4598 if (lua_gettop(L) >= 2) {
4599 len = MAY_LJMP(luaL_checkinteger(L, 2));
4600 lua_pop(L, 1);
4601 }
4602
4603 /* Confirm or set the required length */
4604 lua_pushinteger(L, len);
4605
4606 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004607 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004608
4609 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4610}
4611
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004612/* Append data in the output side of the buffer. This data is immediately
4613 * sent. The function returns the amount of data written. If the buffer
4614 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004615 * if the channel is closed.
4616 */
4617__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4618{
4619 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004620 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004621 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4622 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004623 struct stream_interface *si = cs_si(luactx->appctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004624 struct channel *chn = si_ic(si);
4625 int max;
4626
4627 /* Get the max amount of data which can write as input in the channel. */
4628 max = channel_recv_max(chn);
4629 if (max > (len - l))
4630 max = len - l;
4631
4632 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004633 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004634
4635 /* update counters. */
4636 l += max;
4637 lua_pop(L, 1);
4638 lua_pushinteger(L, l);
4639
4640 /* If some data is not send, declares the situation to the
4641 * applet, and returns a yield.
4642 */
4643 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004644 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004645 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004646 }
4647
4648 return 1;
4649}
4650
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004651/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004652 * yield the LUA process, and resume it without checking the
4653 * input arguments.
4654 */
4655__LJMP static int hlua_applet_tcp_send(lua_State *L)
4656{
4657 MAY_LJMP(check_args(L, 2, "send"));
4658 lua_pushinteger(L, 0);
4659
4660 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4661}
4662
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004663/*
4664 *
4665 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004666 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004667 *
4668 *
4669 */
4670
4671/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004672 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004673 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004674__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004675{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004676 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004677}
4678
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004679/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004680 * according with a current TXN.
4681 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004682static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004683{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004684 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004685 struct hlua_txn htxn;
Christopher Faulet86e1c332021-12-20 17:09:39 +01004686 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004687 struct stream *s = si_strm(si);
4688 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004689 struct htx *htx;
4690 struct htx_blk *blk;
4691 struct htx_sl *sl;
4692 struct ist path;
4693 unsigned long long len = 0;
4694 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004695 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004696
4697 /* Check stack size. */
4698 if (!lua_checkstack(L, 3))
4699 return 0;
4700
4701 /* Create the object: obj[0] = userdata.
4702 * Note that the base of the Converters object is the
4703 * same than the TXN object.
4704 */
4705 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004706 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004707 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004708 luactx->appctx = ctx;
4709 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4710 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4711 luactx->htxn.s = s;
4712 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004713
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004714 /* Create the "f" field that contains a list of fetches. */
4715 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004716 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004717 return 0;
4718 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004719
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004720 /* Create the "sf" field that contains a list of stringsafe fetches. */
4721 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004722 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004723 return 0;
4724 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004725
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004726 /* Create the "c" field that contains a list of converters. */
4727 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004728 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004729 return 0;
4730 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004731
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004732 /* Create the "sc" field that contains a list of stringsafe converters. */
4733 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004734 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004735 return 0;
4736 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004737
Christopher Fauleta2097962019-07-15 16:25:33 +02004738 htx = htxbuf(&s->req.buf);
4739 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004740 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004741 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004742
Christopher Fauleta2097962019-07-15 16:25:33 +02004743 /* Stores the request method. */
4744 lua_pushstring(L, "method");
4745 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4746 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004747
Christopher Fauleta2097962019-07-15 16:25:33 +02004748 /* Stores the http version. */
4749 lua_pushstring(L, "version");
4750 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4751 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004752
Christopher Fauleta2097962019-07-15 16:25:33 +02004753 /* creates an array of headers. hlua_http_get_headers() crates and push
4754 * the array on the top of the stack.
4755 */
4756 lua_pushstring(L, "headers");
4757 htxn.s = s;
4758 htxn.p = px;
4759 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004760 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004761 return 0;
4762 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004763
Amaury Denoyellec453f952021-07-06 11:40:12 +02004764 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4765 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004766 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004767 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004768
Christopher Fauleta2097962019-07-15 16:25:33 +02004769 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004770 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004771 q = p;
4772 while (q < end && *q != '?')
4773 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004774
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004775 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004776 lua_pushstring(L, "path");
4777 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004778 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004779
Christopher Fauleta2097962019-07-15 16:25:33 +02004780 /* Stores the query string. */
4781 lua_pushstring(L, "qs");
4782 if (*q == '?')
4783 q++;
4784 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004785 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004786 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004787
Christopher Fauleta2097962019-07-15 16:25:33 +02004788 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4789 struct htx_blk *blk = htx_get_blk(htx, pos);
4790 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004791
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004792 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004793 break;
4794 if (type == HTX_BLK_DATA)
4795 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004796 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004797 if (htx->extra != ULLONG_MAX)
4798 len += htx->extra;
4799
4800 /* Stores the request path. */
4801 lua_pushstring(L, "length");
4802 lua_pushinteger(L, len);
4803 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004804
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004805 /* Create an empty array of HTTP request headers. */
4806 lua_pushstring(L, "response");
4807 lua_newtable(L);
4808 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004809
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004810 /* Pop a class stream metatable and affect it to the table. */
4811 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4812 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004813
4814 return 1;
4815}
4816
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004817__LJMP static int hlua_applet_http_set_var(lua_State *L)
4818{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004819 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004820 struct stream *s;
4821 const char *name;
4822 size_t len;
4823 struct sample smp;
4824
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004825 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4826 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004827
4828 /* It is useles to retrieve the stream, but this function
4829 * runs only in a stream context.
4830 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004831 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004832 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004833 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004834
4835 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004836 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004837 hlua_lua2smp(L, 3, &smp);
4838
4839 /* Store the sample in a variable. */
4840 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004841
4842 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4843 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4844 else
4845 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4846
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004847 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004848}
4849
4850__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4851{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004852 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004853 struct stream *s;
4854 const char *name;
4855 size_t len;
4856 struct sample smp;
4857
4858 MAY_LJMP(check_args(L, 2, "unset_var"));
4859
4860 /* It is useles to retrieve the stream, but this function
4861 * runs only in a stream context.
4862 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004863 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004864 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004865 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004866
4867 /* Unset the variable. */
4868 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004869 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4870 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004871}
4872
4873__LJMP static int hlua_applet_http_get_var(lua_State *L)
4874{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004875 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004876 struct stream *s;
4877 const char *name;
4878 size_t len;
4879 struct sample smp;
4880
4881 MAY_LJMP(check_args(L, 2, "get_var"));
4882
4883 /* It is useles to retrieve the stream, but this function
4884 * runs only in a stream context.
4885 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004886 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004887 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004888 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004889
4890 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004891 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004892 lua_pushnil(L);
4893 return 1;
4894 }
4895
4896 return hlua_smp2lua(L, &smp);
4897}
4898
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004899__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4900{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004901 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4902 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004903 struct hlua *hlua;
4904
4905 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004906 if (!s->hlua)
4907 return 0;
4908 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004909
4910 MAY_LJMP(check_args(L, 2, "set_priv"));
4911
4912 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004913 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004914
4915 /* Get and store new value. */
4916 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4917 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4918
4919 return 0;
4920}
4921
4922__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4923{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004924 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4925 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004926 struct hlua *hlua;
4927
4928 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004929 if (!s->hlua) {
4930 lua_pushnil(L);
4931 return 1;
4932 }
4933 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004934
4935 /* Push configuration index in the stack. */
4936 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4937
4938 return 1;
4939}
4940
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004941/* If expected data not yet available, it returns a yield. This function
4942 * consumes the data in the buffer. It returns a string containing the
4943 * data. This string can be empty.
4944 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004945__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004946{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004947 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01004948 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004949 struct channel *req = si_oc(si);
4950 struct htx *htx;
4951 struct htx_blk *blk;
4952 size_t count;
4953 int stop = 0;
4954
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004955 htx = htx_from_buf(&req->buf);
4956 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004957 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004958
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004959 while (count && !stop && blk) {
4960 enum htx_blk_type type = htx_get_blk_type(blk);
4961 uint32_t sz = htx_get_blksz(blk);
4962 struct ist v;
4963 uint32_t vlen;
4964 char *nl;
4965
4966 vlen = sz;
4967 if (vlen > count) {
4968 if (type != HTX_BLK_DATA)
4969 break;
4970 vlen = count;
4971 }
4972
4973 switch (type) {
4974 case HTX_BLK_UNUSED:
4975 break;
4976
4977 case HTX_BLK_DATA:
4978 v = htx_get_blk_value(htx, blk);
4979 v.len = vlen;
4980 nl = istchr(v, '\n');
4981 if (nl != NULL) {
4982 stop = 1;
4983 vlen = nl - v.ptr + 1;
4984 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004985 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004986 break;
4987
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004988 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004989 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004990 stop = 1;
4991 break;
4992
4993 default:
4994 break;
4995 }
4996
Willy Tarreau84240042022-02-28 16:51:23 +01004997 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004998 count -= vlen;
4999 if (sz == vlen)
5000 blk = htx_remove_blk(htx, blk);
5001 else {
5002 htx_cut_data_blk(htx, blk, vlen);
5003 break;
5004 }
5005 }
5006
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005007 /* The message was fully consumed and no more data are expected
5008 * (EOM flag set).
5009 */
5010 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5011 stop = 1;
5012
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005013 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005014 if (!stop) {
5015 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005016 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005017 }
5018
5019 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005020 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005021 return 1;
5022}
5023
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005024
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005025/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005026__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005027{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005028 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005029
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005030 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005031 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005032
Christopher Fauleta2097962019-07-15 16:25:33 +02005033 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005034}
5035
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005036/* If expected data not yet available, it returns a yield. This function
5037 * consumes the data in the buffer. It returns a string containing the
5038 * data. This string can be empty.
5039 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005040__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005041{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005042 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005043 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005044 struct channel *req = si_oc(si);
5045 struct htx *htx;
5046 struct htx_blk *blk;
5047 size_t count;
5048 int len;
5049
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005050 htx = htx_from_buf(&req->buf);
5051 len = MAY_LJMP(luaL_checkinteger(L, 2));
5052 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005053 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005054 while (count && len && blk) {
5055 enum htx_blk_type type = htx_get_blk_type(blk);
5056 uint32_t sz = htx_get_blksz(blk);
5057 struct ist v;
5058 uint32_t vlen;
5059
5060 vlen = sz;
5061 if (len > 0 && vlen > len)
5062 vlen = len;
5063 if (vlen > count) {
5064 if (type != HTX_BLK_DATA)
5065 break;
5066 vlen = count;
5067 }
5068
5069 switch (type) {
5070 case HTX_BLK_UNUSED:
5071 break;
5072
5073 case HTX_BLK_DATA:
5074 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005075 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005076 break;
5077
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005078 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005079 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005080 len = 0;
5081 break;
5082
5083 default:
5084 break;
5085 }
5086
Willy Tarreau84240042022-02-28 16:51:23 +01005087 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005088 count -= vlen;
5089 if (len > 0)
5090 len -= vlen;
5091 if (sz == vlen)
5092 blk = htx_remove_blk(htx, blk);
5093 else {
5094 htx_cut_data_blk(htx, blk, vlen);
5095 break;
5096 }
5097 }
5098
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005099 /* The message was fully consumed and no more data are expected
5100 * (EOM flag set).
5101 */
5102 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5103 len = 0;
5104
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005105 htx_to_buf(htx, &req->buf);
5106
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005107 /* If we are no other data available, yield waiting for new data. */
5108 if (len) {
5109 if (len > 0) {
5110 lua_pushinteger(L, len);
5111 lua_replace(L, 2);
5112 }
5113 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005114 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005115 }
5116
5117 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005118 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005119 return 1;
5120}
5121
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005122/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005123__LJMP static int hlua_applet_http_recv(lua_State *L)
5124{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005125 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005126 int len = -1;
5127
5128 /* Check arguments. */
5129 if (lua_gettop(L) > 2)
5130 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5131 if (lua_gettop(L) >= 2) {
5132 len = MAY_LJMP(luaL_checkinteger(L, 2));
5133 lua_pop(L, 1);
5134 }
5135
Christopher Fauleta2097962019-07-15 16:25:33 +02005136 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005137
Christopher Fauleta2097962019-07-15 16:25:33 +02005138 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005139 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005140
Christopher Fauleta2097962019-07-15 16:25:33 +02005141 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005142}
5143
5144/* Append data in the output side of the buffer. This data is immediately
5145 * sent. The function returns the amount of data written. If the buffer
5146 * cannot contain the data, the function yields. The function returns -1
5147 * if the channel is closed.
5148 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005149__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005150{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005151 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005152 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005153 struct channel *res = si_ic(si);
5154 struct htx *htx = htx_from_buf(&res->buf);
5155 const char *data;
5156 size_t len;
5157 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5158 int max;
5159
Christopher Faulet9060fc02019-07-03 11:39:30 +02005160 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005161 if (!max)
5162 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005163
5164 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5165
5166 /* Get the max amount of data which can write as input in the channel. */
5167 if (max > (len - l))
5168 max = len - l;
5169
5170 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005171 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005172 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005173
5174 /* update counters. */
5175 l += max;
5176 lua_pop(L, 1);
5177 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005178
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005179 /* If some data is not send, declares the situation to the
5180 * applet, and returns a yield.
5181 */
5182 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005183 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005184 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005185 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005186 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005187 }
5188
Christopher Fauleta2097962019-07-15 16:25:33 +02005189 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005190 return 1;
5191}
5192
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005193/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005194 * yield the LUA process, and resume it without checking the
5195 * input arguments.
5196 */
5197__LJMP static int hlua_applet_http_send(lua_State *L)
5198{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005199 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005200
5201 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005202 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005203 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5204 WILL_LJMP(lua_error(L));
5205 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005206
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005207 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005208 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005209
Christopher Fauleta2097962019-07-15 16:25:33 +02005210 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005211}
5212
5213__LJMP static int hlua_applet_http_addheader(lua_State *L)
5214{
5215 const char *name;
5216 int ret;
5217
5218 MAY_LJMP(hlua_checkapplet_http(L, 1));
5219 name = MAY_LJMP(luaL_checkstring(L, 2));
5220 MAY_LJMP(luaL_checkstring(L, 3));
5221
5222 /* Push in the stack the "response" entry. */
5223 ret = lua_getfield(L, 1, "response");
5224 if (ret != LUA_TTABLE) {
5225 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5226 "is expected as an array. %s found", lua_typename(L, ret));
5227 WILL_LJMP(lua_error(L));
5228 }
5229
5230 /* check if the header is already registered if it is not
5231 * the case, register it.
5232 */
5233 ret = lua_getfield(L, -1, name);
5234 if (ret == LUA_TNIL) {
5235
5236 /* Entry not found. */
5237 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5238
5239 /* Insert the new header name in the array in the top of the stack.
5240 * It left the new array in the top of the stack.
5241 */
5242 lua_newtable(L);
5243 lua_pushvalue(L, 2);
5244 lua_pushvalue(L, -2);
5245 lua_settable(L, -4);
5246
5247 } else if (ret != LUA_TTABLE) {
5248
5249 /* corruption error. */
5250 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5251 "is expected as an array. %s found", name, lua_typename(L, ret));
5252 WILL_LJMP(lua_error(L));
5253 }
5254
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005255 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005256 * the header value as new entry.
5257 */
5258 lua_pushvalue(L, 3);
5259 ret = lua_rawlen(L, -2);
5260 lua_rawseti(L, -2, ret + 1);
5261 lua_pushboolean(L, 1);
5262 return 1;
5263}
5264
5265__LJMP static int hlua_applet_http_status(lua_State *L)
5266{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005267 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005268 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005269 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005270
5271 if (status < 100 || status > 599) {
5272 lua_pushboolean(L, 0);
5273 return 1;
5274 }
5275
Willy Tarreau7e702d12021-04-28 17:59:21 +02005276 luactx->appctx->ctx.hlua_apphttp.status = status;
5277 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005278 lua_pushboolean(L, 1);
5279 return 1;
5280}
5281
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005282
Christopher Fauleta2097962019-07-15 16:25:33 +02005283__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005284{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005285 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005286 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005287 struct channel *res = si_ic(si);
5288 struct htx *htx;
5289 struct htx_sl *sl;
5290 struct h1m h1m;
5291 const char *status, *reason;
5292 const char *name, *value;
5293 size_t nlen, vlen;
5294 unsigned int flags;
5295
5296 /* Send the message at once. */
5297 htx = htx_from_buf(&res->buf);
5298 h1m_init_res(&h1m);
5299
5300 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005301 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5302 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005303 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005304 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5305 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005306 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5307 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5308 }
5309 else {
5310 flags = HTX_SL_F_IS_RESP;
5311 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5312 }
5313 if (!sl) {
5314 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\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 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005318 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005319
5320 /* Get the array associated to the field "response" in the object AppletHTTP. */
5321 lua_pushvalue(L, 0);
5322 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5323 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005324 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005325 WILL_LJMP(lua_error(L));
5326 }
5327
5328 /* Browse the list of headers. */
5329 lua_pushnil(L);
5330 while(lua_next(L, -2) != 0) {
5331 /* We expect a string as -2. */
5332 if (lua_type(L, -2) != LUA_TSTRING) {
5333 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. 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 lua_typename(L, lua_type(L, -2)));
5336 WILL_LJMP(lua_error(L));
5337 }
5338 name = lua_tolstring(L, -2, &nlen);
5339
5340 /* We expect an array as -1. */
5341 if (lua_type(L, -1) != LUA_TTABLE) {
5342 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 +02005343 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005344 name,
5345 lua_typename(L, lua_type(L, -1)));
5346 WILL_LJMP(lua_error(L));
5347 }
5348
5349 /* Browse the table who is on the top of the stack. */
5350 lua_pushnil(L);
5351 while(lua_next(L, -2) != 0) {
5352 int id;
5353
5354 /* We expect a number as -2. */
5355 if (lua_type(L, -2) != LUA_TNUMBER) {
5356 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 +02005357 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005358 name,
5359 lua_typename(L, lua_type(L, -2)));
5360 WILL_LJMP(lua_error(L));
5361 }
5362 id = lua_tointeger(L, -2);
5363
5364 /* We expect a string as -2. */
5365 if (lua_type(L, -1) != LUA_TSTRING) {
5366 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 +02005367 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005368 name, id,
5369 lua_typename(L, lua_type(L, -1)));
5370 WILL_LJMP(lua_error(L));
5371 }
5372 value = lua_tolstring(L, -1, &vlen);
5373
5374 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005375 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5376 int ret;
5377
5378 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5379 if (ret < 0) {
5380 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5381 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5382 name);
5383 WILL_LJMP(lua_error(L));
5384 }
5385 else if (ret == 0)
5386 goto next; /* Skip it */
5387 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005388 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5389 struct ist v = ist2(value, vlen);
5390 int ret;
5391
5392 ret = h1_parse_cont_len_header(&h1m, &v);
5393 if (ret < 0) {
5394 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005395 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005396 name);
5397 WILL_LJMP(lua_error(L));
5398 }
5399 else if (ret == 0)
5400 goto next; /* Skip it */
5401 }
5402
5403 /* Add a new header */
5404 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5405 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005406 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005407 name);
5408 WILL_LJMP(lua_error(L));
5409 }
5410 next:
5411 /* Remove the array from the stack, and get next element with a remaining string. */
5412 lua_pop(L, 1);
5413 }
5414
5415 /* Remove the array from the stack, and get next element with a remaining string. */
5416 lua_pop(L, 1);
5417 }
5418
5419 if (h1m.flags & H1_MF_CHNK)
5420 h1m.flags &= ~H1_MF_CLEN;
5421 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5422 h1m.flags |= H1_MF_XFER_LEN;
5423
5424 /* Uset HTX start-line flags */
5425 if (h1m.flags & H1_MF_XFER_ENC)
5426 flags |= HTX_SL_F_XFER_ENC;
5427 if (h1m.flags & H1_MF_XFER_LEN) {
5428 flags |= HTX_SL_F_XFER_LEN;
5429 if (h1m.flags & H1_MF_CHNK)
5430 flags |= HTX_SL_F_CHNK;
5431 else if (h1m.flags & H1_MF_CLEN)
5432 flags |= HTX_SL_F_CLEN;
5433 if (h1m.body_len == 0)
5434 flags |= HTX_SL_F_BODYLESS;
5435 }
5436 sl->flags |= flags;
5437
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005438 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005439 * and the status code implies the presence of a message body, we must
5440 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005441 * for the keepalive compliance. If the applet announces a transfer-encoding
5442 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005443 */
5444 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005445 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5446 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5447 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005448 /* Add a new header */
5449 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5450 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5451 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005452 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005453 WILL_LJMP(lua_error(L));
5454 }
5455 }
5456
5457 /* Finalize headers. */
5458 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5459 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005460 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005461 WILL_LJMP(lua_error(L));
5462 }
5463
5464 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5465 b_reset(&res->buf);
5466 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5467 WILL_LJMP(lua_error(L));
5468 }
5469
5470 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005471 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005472
5473 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005474 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005475 return 0;
5476
5477}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005478/* We will build the status line and the headers of the HTTP response.
5479 * We will try send at once if its not possible, we give back the hand
5480 * waiting for more room.
5481 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005482__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005483{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005484 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet86e1c332021-12-20 17:09:39 +01005485 struct stream_interface *si = cs_si(luactx->appctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005486 struct channel *res = si_ic(si);
5487
5488 if (co_data(res)) {
5489 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005490 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005491 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005492 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005493}
5494
5495
Christopher Fauleta2097962019-07-15 16:25:33 +02005496__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005497{
Christopher Fauleta2097962019-07-15 16:25:33 +02005498 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005499}
5500
Christopher Fauleta2097962019-07-15 16:25:33 +02005501/*
5502 *
5503 *
5504 * Class HTTP
5505 *
5506 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005507 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005508
5509/* Returns a struct hlua_txn if the stack entry "ud" is
5510 * a class stream, otherwise it throws an error.
5511 */
5512__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005513{
Christopher Fauleta2097962019-07-15 16:25:33 +02005514 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5515}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005516
Christopher Fauleta2097962019-07-15 16:25:33 +02005517/* This function creates and push in the stack a HTTP object
5518 * according with a current TXN.
5519 */
5520static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5521{
5522 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005523
Christopher Fauleta2097962019-07-15 16:25:33 +02005524 /* Check stack size. */
5525 if (!lua_checkstack(L, 3))
5526 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005527
Christopher Fauleta2097962019-07-15 16:25:33 +02005528 /* Create the object: obj[0] = userdata.
5529 * Note that the base of the Converters object is the
5530 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005531 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005532 lua_newtable(L);
5533 htxn = lua_newuserdata(L, sizeof(*htxn));
5534 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005535
5536 htxn->s = txn->s;
5537 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005538 htxn->dir = txn->dir;
5539 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005540
5541 /* Pop a class stream metatable and affect it to the table. */
5542 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5543 lua_setmetatable(L, -2);
5544
5545 return 1;
5546}
5547
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005548/* This function creates and returns an array containing the status-line
5549 * elements. This function does not fails.
5550 */
5551__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5552{
5553 /* Create the table. */
5554 lua_newtable(L);
5555
5556 if (sl->flags & HTX_SL_F_IS_RESP) {
5557 lua_pushstring(L, "version");
5558 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5559 lua_settable(L, -3);
5560 lua_pushstring(L, "code");
5561 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5562 lua_settable(L, -3);
5563 lua_pushstring(L, "reason");
5564 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5565 lua_settable(L, -3);
5566 }
5567 else {
5568 lua_pushstring(L, "method");
5569 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5570 lua_settable(L, -3);
5571 lua_pushstring(L, "uri");
5572 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5573 lua_settable(L, -3);
5574 lua_pushstring(L, "version");
5575 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5576 lua_settable(L, -3);
5577 }
5578 return 1;
5579}
5580
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005581/* This function creates ans returns an array of HTTP headers.
5582 * This function does not fails. It is used as wrapper with the
5583 * 2 following functions.
5584 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005585__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005586{
Christopher Fauleta2097962019-07-15 16:25:33 +02005587 struct htx *htx;
5588 int32_t pos;
5589
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005590 /* Create the table. */
5591 lua_newtable(L);
5592
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005593
Christopher Fauleta2097962019-07-15 16:25:33 +02005594 htx = htxbuf(&msg->chn->buf);
5595 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5596 struct htx_blk *blk = htx_get_blk(htx, pos);
5597 enum htx_blk_type type = htx_get_blk_type(blk);
5598 struct ist n, v;
5599 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005600
Christopher Fauleta2097962019-07-15 16:25:33 +02005601 if (type == HTX_BLK_HDR) {
5602 n = htx_get_blk_name(htx,blk);
5603 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005604 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005605 else if (type == HTX_BLK_EOH)
5606 break;
5607 else
5608 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005609
Christopher Fauleta2097962019-07-15 16:25:33 +02005610 /* Check for existing entry:
5611 * assume that the table is on the top of the stack, and
5612 * push the key in the stack, the function lua_gettable()
5613 * perform the lookup.
5614 */
5615 lua_pushlstring(L, n.ptr, n.len);
5616 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005617
Christopher Fauleta2097962019-07-15 16:25:33 +02005618 switch (lua_type(L, -1)) {
5619 case LUA_TNIL:
5620 /* Table not found, create it. */
5621 lua_pop(L, 1); /* remove the nil value. */
5622 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5623 lua_newtable(L); /* create and push empty table. */
5624 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5625 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5626 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005627 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005628
Christopher Fauleta2097962019-07-15 16:25:33 +02005629 case LUA_TTABLE:
5630 /* Entry found: push the value in the table. */
5631 len = lua_rawlen(L, -1);
5632 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5633 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5634 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5635 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005636
Christopher Fauleta2097962019-07-15 16:25:33 +02005637 default:
5638 /* Other cases are errors. */
5639 hlua_pusherror(L, "internal error during the parsing of headers.");
5640 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005641 }
5642 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005643 return 1;
5644}
5645
5646__LJMP static int hlua_http_req_get_headers(lua_State *L)
5647{
5648 struct hlua_txn *htxn;
5649
5650 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5651 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5652
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005653 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005654 WILL_LJMP(lua_error(L));
5655
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005656 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005657}
5658
5659__LJMP static int hlua_http_res_get_headers(lua_State *L)
5660{
5661 struct hlua_txn *htxn;
5662
5663 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5664 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5665
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005666 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005667 WILL_LJMP(lua_error(L));
5668
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005669 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005670}
5671
5672/* This function replace full header, or just a value in
5673 * the request or in the response. It is a wrapper fir the
5674 * 4 following functions.
5675 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005676__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005677{
5678 size_t name_len;
5679 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5680 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5681 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005682 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005683 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005684
Dragan Dosen26743032019-04-30 15:54:36 +02005685 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005686 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5687
Christopher Fauleta2097962019-07-15 16:25:33 +02005688 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005689 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005690 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005691 return 0;
5692}
5693
5694__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5695{
5696 struct hlua_txn *htxn;
5697
5698 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5699 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5700
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005701 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005702 WILL_LJMP(lua_error(L));
5703
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005704 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005705}
5706
5707__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5708{
5709 struct hlua_txn *htxn;
5710
5711 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5712 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5713
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005714 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005715 WILL_LJMP(lua_error(L));
5716
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005717 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005718}
5719
5720__LJMP static int hlua_http_req_rep_val(lua_State *L)
5721{
5722 struct hlua_txn *htxn;
5723
5724 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5725 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5726
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005727 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005728 WILL_LJMP(lua_error(L));
5729
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005730 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005731}
5732
5733__LJMP static int hlua_http_res_rep_val(lua_State *L)
5734{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005735 struct hlua_txn *htxn;
5736
5737 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5738 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5739
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005740 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005741 WILL_LJMP(lua_error(L));
5742
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005743 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005744}
5745
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005746/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005747 * It is a wrapper for the 2 following functions.
5748 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005749__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005750{
5751 size_t len;
5752 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005753 struct htx *htx = htxbuf(&msg->chn->buf);
5754 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005755
Christopher Fauleta2097962019-07-15 16:25:33 +02005756 ctx.blk = NULL;
5757 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5758 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005759 return 0;
5760}
5761
5762__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5763{
5764 struct hlua_txn *htxn;
5765
5766 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5767 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5768
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005769 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005770 WILL_LJMP(lua_error(L));
5771
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005772 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005773}
5774
5775__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5776{
5777 struct hlua_txn *htxn;
5778
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005779 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005780 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5781
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005782 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005783 WILL_LJMP(lua_error(L));
5784
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005785 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005786}
5787
5788/* This function adds an header. It is a wrapper used by
5789 * the 2 following functions.
5790 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005791__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005792{
5793 size_t name_len;
5794 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5795 size_t value_len;
5796 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005797 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005798
Christopher Fauleta2097962019-07-15 16:25:33 +02005799 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5800 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005801 return 0;
5802}
5803
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005804__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5805{
5806 struct hlua_txn *htxn;
5807
5808 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5809 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5810
5811 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5812 WILL_LJMP(lua_error(L));
5813
5814 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5815}
5816
5817__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5818{
5819 struct hlua_txn *htxn;
5820
5821 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5822 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5823
5824 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5825 WILL_LJMP(lua_error(L));
5826
5827 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5828}
5829
5830static int hlua_http_req_set_hdr(lua_State *L)
5831{
5832 struct hlua_txn *htxn;
5833
5834 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5835 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5836
5837 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5838 WILL_LJMP(lua_error(L));
5839
5840 hlua_http_del_hdr(L, &htxn->s->txn->req);
5841 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5842}
5843
5844static int hlua_http_res_set_hdr(lua_State *L)
5845{
5846 struct hlua_txn *htxn;
5847
5848 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5849 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5850
5851 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5852 WILL_LJMP(lua_error(L));
5853
5854 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5855 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5856}
5857
5858/* This function set the method. */
5859static int hlua_http_req_set_meth(lua_State *L)
5860{
5861 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5862 size_t name_len;
5863 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5864
5865 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5866 WILL_LJMP(lua_error(L));
5867
5868 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5869 return 1;
5870}
5871
5872/* This function set the method. */
5873static int hlua_http_req_set_path(lua_State *L)
5874{
5875 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5876 size_t name_len;
5877 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5878
5879 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5880 WILL_LJMP(lua_error(L));
5881
5882 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5883 return 1;
5884}
5885
5886/* This function set the query-string. */
5887static int hlua_http_req_set_query(lua_State *L)
5888{
5889 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5890 size_t name_len;
5891 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5892
5893 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5894 WILL_LJMP(lua_error(L));
5895
5896 /* Check length. */
5897 if (name_len > trash.size - 1) {
5898 lua_pushboolean(L, 0);
5899 return 1;
5900 }
5901
5902 /* Add the mark question as prefix. */
5903 chunk_reset(&trash);
5904 trash.area[trash.data++] = '?';
5905 memcpy(trash.area + trash.data, name, name_len);
5906 trash.data += name_len;
5907
5908 lua_pushboolean(L,
5909 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5910 return 1;
5911}
5912
5913/* This function set the uri. */
5914static int hlua_http_req_set_uri(lua_State *L)
5915{
5916 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5917 size_t name_len;
5918 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5919
5920 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5921 WILL_LJMP(lua_error(L));
5922
5923 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5924 return 1;
5925}
5926
5927/* This function set the response code & optionally reason. */
5928static int hlua_http_res_set_status(lua_State *L)
5929{
5930 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5931 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5932 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5933 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5934
5935 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5936 WILL_LJMP(lua_error(L));
5937
5938 http_res_set_status(code, reason, htxn->s);
5939 return 0;
5940}
5941
5942/*
5943 *
5944 *
5945 * Class HTTPMessage
5946 *
5947 *
5948 */
5949
5950/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5951 * otherwise it throws an error.
5952 */
5953__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5954{
5955 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5956}
5957
5958/* Creates and pushes on the stack a HTTP object according with a current TXN.
5959 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005960static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005961{
5962 /* Check stack size. */
5963 if (!lua_checkstack(L, 3))
5964 return 0;
5965
5966 lua_newtable(L);
5967 lua_pushlightuserdata(L, msg);
5968 lua_rawseti(L, -2, 0);
5969
5970 /* Create the "channel" field that contains the request channel object. */
5971 lua_pushstring(L, "channel");
5972 if (!hlua_channel_new(L, msg->chn))
5973 return 0;
5974 lua_rawset(L, -3);
5975
5976 /* Pop a class stream metatable and affect it to the table. */
5977 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5978 lua_setmetatable(L, -2);
5979
5980 return 1;
5981}
5982
5983/* Helper function returning a filter attached to the HTTP message at the
5984 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05005985 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005986 * filled with output and input length respectively.
5987 */
5988static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5989{
5990 struct channel *chn = msg->chn;
5991 struct htx *htx = htxbuf(&chn->buf);
5992 struct filter *filter = NULL;
5993
5994 *offset = co_data(msg->chn);
5995 *len = htx->data - co_data(msg->chn);
5996
5997 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5998 filter = lua_touserdata (L, -1);
5999 if (msg->msg_state >= HTTP_MSG_DATA) {
6000 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6001
6002 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6003 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6004 }
6005 }
6006
6007 lua_pop(L, 1);
6008 return filter;
6009}
6010
6011/* Returns true if the channel attached to the HTTP message is the response
6012 * channel.
6013 */
6014__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6015{
6016 struct http_msg *msg;
6017
6018 MAY_LJMP(check_args(L, 1, "is_resp"));
6019 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6020
6021 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6022 return 1;
6023}
6024
6025/* Returns an array containing the elements status-line of the HTTP message. It relies
6026 * on hlua_http_get_stline().
6027 */
6028__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6029{
6030 struct http_msg *msg;
6031 struct htx *htx;
6032 struct htx_sl *sl;
6033
6034 MAY_LJMP(check_args(L, 1, "get_stline"));
6035 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6036
6037 if (msg->msg_state > HTTP_MSG_BODY)
6038 WILL_LJMP(lua_error(L));
6039
6040 htx = htxbuf(&msg->chn->buf);
6041 sl = http_get_stline(htx);
6042 if (!sl)
6043 return 0;
6044 return hlua_http_get_stline(L, sl);
6045}
6046
6047/* Returns an array containing all headers of the HTTP message. it relies on
6048 * hlua_http_get_headers().
6049 */
6050__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6051{
6052 struct http_msg *msg;
6053
6054 MAY_LJMP(check_args(L, 1, "get_headers"));
6055 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6056
6057 if (msg->msg_state > HTTP_MSG_BODY)
6058 WILL_LJMP(lua_error(L));
6059
6060 return hlua_http_get_headers(L, msg);
6061}
6062
6063/* Deletes all occurrences of an header in the HTTP message matching on its
6064 * name. It relies on hlua_http_del_hdr().
6065 */
6066__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6067{
6068 struct http_msg *msg;
6069
6070 MAY_LJMP(check_args(L, 2, "del_header"));
6071 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6072
6073 if (msg->msg_state > HTTP_MSG_BODY)
6074 WILL_LJMP(lua_error(L));
6075
6076 return hlua_http_del_hdr(L, msg);
6077}
6078
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006079/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006080 * message given its name against a regex and replaces it if it matches. It
6081 * relies on hlua_http_rep_hdr().
6082 */
6083__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6084{
6085 struct http_msg *msg;
6086
6087 MAY_LJMP(check_args(L, 4, "rep_header"));
6088 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6089
6090 if (msg->msg_state > HTTP_MSG_BODY)
6091 WILL_LJMP(lua_error(L));
6092
6093 return hlua_http_rep_hdr(L, msg, 1);
6094}
6095
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006096/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006097 * message given its name against a regex and replaces it if it matches. It
6098 * relies on hlua_http_rep_hdr().
6099 */
6100__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6101{
6102 struct http_msg *msg;
6103
6104 MAY_LJMP(check_args(L, 4, "rep_value"));
6105 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6106
6107 if (msg->msg_state > HTTP_MSG_BODY)
6108 WILL_LJMP(lua_error(L));
6109
6110 return hlua_http_rep_hdr(L, msg, 0);
6111}
6112
6113/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6114__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6115{
6116 struct http_msg *msg;
6117
6118 MAY_LJMP(check_args(L, 3, "add_header"));
6119 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6120
6121 if (msg->msg_state > HTTP_MSG_BODY)
6122 WILL_LJMP(lua_error(L));
6123
6124 return hlua_http_add_hdr(L, msg);
6125}
6126
6127/* Add an header in the HTTP message removing existing headers with the same
6128 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6129 */
6130__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6131{
6132 struct http_msg *msg;
6133
6134 MAY_LJMP(check_args(L, 3, "set_header"));
6135 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6136
6137 if (msg->msg_state > HTTP_MSG_BODY)
6138 WILL_LJMP(lua_error(L));
6139
6140 hlua_http_del_hdr(L, msg);
6141 return hlua_http_add_hdr(L, msg);
6142}
6143
6144/* Rewrites the request method. It relies on http_req_replace_stline(). */
6145__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6146{
6147 struct stream *s;
6148 struct http_msg *msg;
6149 const char *name;
6150 size_t name_len;
6151
6152 MAY_LJMP(check_args(L, 2, "set_method"));
6153 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6154 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6155
6156 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6157 WILL_LJMP(lua_error(L));
6158
6159 s = chn_strm(msg->chn);
6160 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6161 return 1;
6162}
6163
6164/* Rewrites the request path. It relies on http_req_replace_stline(). */
6165__LJMP static int hlua_http_msg_set_path(lua_State *L)
6166{
6167 struct stream *s;
6168 struct http_msg *msg;
6169 const char *name;
6170 size_t name_len;
6171
6172 MAY_LJMP(check_args(L, 2, "set_path"));
6173 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6174 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6175
6176 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6177 WILL_LJMP(lua_error(L));
6178
6179 s = chn_strm(msg->chn);
6180 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6181 return 1;
6182}
6183
6184/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6185__LJMP static int hlua_http_msg_set_query(lua_State *L)
6186{
6187 struct stream *s;
6188 struct http_msg *msg;
6189 const char *name;
6190 size_t name_len;
6191
6192 MAY_LJMP(check_args(L, 2, "set_query"));
6193 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6194 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6195
6196 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6197 WILL_LJMP(lua_error(L));
6198
6199 /* Check length. */
6200 if (name_len > trash.size - 1) {
6201 lua_pushboolean(L, 0);
6202 return 1;
6203 }
6204
6205 /* Add the mark question as prefix. */
6206 chunk_reset(&trash);
6207 trash.area[trash.data++] = '?';
6208 memcpy(trash.area + trash.data, name, name_len);
6209 trash.data += name_len;
6210
6211 s = chn_strm(msg->chn);
6212 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6213 return 1;
6214}
6215
6216/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6217__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6218{
6219 struct stream *s;
6220 struct http_msg *msg;
6221 const char *name;
6222 size_t name_len;
6223
6224 MAY_LJMP(check_args(L, 2, "set_uri"));
6225 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6226 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6227
6228 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6229 WILL_LJMP(lua_error(L));
6230
6231 s = chn_strm(msg->chn);
6232 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6233 return 1;
6234}
6235
6236/* Rewrites the response status code. It relies on http_res_set_status(). */
6237__LJMP static int hlua_http_msg_set_status(lua_State *L)
6238{
6239 struct http_msg *msg;
6240 unsigned int code;
6241 const char *reason;
6242 size_t reason_len;
6243
6244 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6245 code = MAY_LJMP(luaL_checkinteger(L, 2));
6246 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6247
6248 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6249 WILL_LJMP(lua_error(L));
6250
6251 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6252 return 1;
6253}
6254
6255/* Returns true if the HTTP message is full. */
6256__LJMP static int hlua_http_msg_is_full(lua_State *L)
6257{
6258 struct http_msg *msg;
6259
6260 MAY_LJMP(check_args(L, 1, "is_full"));
6261 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6262 lua_pushboolean(L, channel_full(msg->chn, 0));
6263 return 1;
6264}
6265
6266/* Returns true if the HTTP message may still receive data. */
6267__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6268{
6269 struct http_msg *msg;
6270 struct htx *htx;
6271
6272 MAY_LJMP(check_args(L, 1, "may_recv"));
6273 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6274 htx = htxbuf(&msg->chn->buf);
6275 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6276 return 1;
6277}
6278
6279/* Returns true if the HTTP message EOM was received */
6280__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6281{
6282 struct http_msg *msg;
6283 struct htx *htx;
6284
6285 MAY_LJMP(check_args(L, 1, "may_recv"));
6286 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6287 htx = htxbuf(&msg->chn->buf);
6288 lua_pushboolean(L, !htx_expect_more(htx));
6289 return 1;
6290}
6291
6292/* Returns the number of bytes available in the input side of the HTTP
6293 * message. This function never fails.
6294 */
6295__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6296{
6297 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006298 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006299
6300 MAY_LJMP(check_args(L, 1, "input"));
6301 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006302 hlua_http_msg_filter(L, 1, msg, &output, &input);
6303 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006304 return 1;
6305}
6306
6307/* Returns the number of bytes available in the output side of the HTTP
6308 * message. This function never fails.
6309 */
6310__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6311{
6312 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006313 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006314
6315 MAY_LJMP(check_args(L, 1, "output"));
6316 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006317 hlua_http_msg_filter(L, 1, msg, &output, &input);
6318 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006319 return 1;
6320}
6321
6322/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6323 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006324 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006325 * block. This function is called during the payload filtering, so the headers
6326 * are already scheduled for output (from the filter point of view).
6327 */
6328static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6329{
6330 struct htx *htx = htxbuf(&msg->chn->buf);
6331 struct htx_blk *blk;
6332 struct htx_ret htxret;
6333 luaL_Buffer b;
6334 int ret = 0;
6335
6336 luaL_buffinit(L, &b);
6337 htxret = htx_find_offset(htx, offset);
6338 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6339 enum htx_blk_type type = htx_get_blk_type(blk);
6340 struct ist v;
6341
6342 switch (type) {
6343 case HTX_BLK_UNUSED:
6344 break;
6345
6346 case HTX_BLK_DATA:
6347 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006348 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006349 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006350
6351 luaL_addlstring(&b, v.ptr, v.len);
6352 ret += v.len;
6353 break;
6354
6355 default:
vishnu0af4bd72021-10-24 06:46:24 +05306356 if (!ret)
6357 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006358 goto end;
6359 }
6360 offset = 0;
6361 }
6362
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006363end:
vishnu0af4bd72021-10-24 06:46:24 +05306364 if (!ret && (htx->flags & HTX_FL_EOM))
6365 goto no_data;
6366 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006367 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306368
6369 no_data:
6370 /* Remove the empty string and push nil on the stack */
6371 lua_pop(L, 1);
6372 lua_pushnil(L);
6373 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006374}
6375
6376/* Copies the string <str> to the HTTP message <msg> at the offset
6377 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006378 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006379 * the filter context.
6380 */
6381static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6382{
6383 struct htx *htx = htx_from_buf(&msg->chn->buf);
6384 struct htx_ret htxret;
6385 int /*max, */ret = 0;
6386
6387 /* Nothing to do, just return */
6388 if (unlikely(istlen(str) == 0))
6389 goto end;
6390
6391 if (istlen(str) > htx_free_data_space(htx)) {
6392 ret = -1;
6393 goto end;
6394 }
6395
6396 htxret = htx_find_offset(htx, offset);
6397 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6398 if (!htx_add_last_data(htx, str))
6399 goto end;
6400 }
6401 else {
6402 struct ist v = htx_get_blk_value(htx, htxret.blk);
6403 v.ptr += htxret.ret;
6404 v.len = 0;
6405 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6406 goto end;
6407 }
6408 ret = str.len;
6409 if (ret) {
6410 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6411 flt_update_offsets(filter, msg->chn, ret);
6412 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6413 }
6414
6415 end:
6416 htx_to_buf(htx, &msg->chn->buf);
6417 return ret;
6418}
6419
6420/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6421 * position <offset>. It stops on the first non-DATA HTX block. This function is
6422 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006423 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006424 * update the filter context.
6425 */
6426static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6427{
6428 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6429 struct htx *htx = htx_from_buf(&msg->chn->buf);
6430 struct htx_blk *blk;
6431 struct htx_ret htxret;
6432 size_t ret = 0;
6433
6434 /* Be sure <len> is always the amount of DATA to remove */
6435 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6436 htx_truncate(htx, offset);
6437 ret = len;
6438 goto end;
6439 }
6440
6441 htxret = htx_find_offset(htx, offset);
6442 blk = htxret.blk;
6443 if (htxret.ret) {
6444 struct ist v;
6445
6446 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6447 goto end;
6448 v = htx_get_blk_value(htx, blk);
6449 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006450 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006451 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006452 len -= v.len;
6453 ret += v.len;
6454 }
6455
6456
6457 while (blk && len) {
6458 enum htx_blk_type type = htx_get_blk_type(blk);
6459 uint32_t sz = htx_get_blksz(blk);
6460
6461 switch (type) {
6462 case HTX_BLK_UNUSED:
6463 break;
6464
6465 case HTX_BLK_DATA:
6466 if (len < sz) {
6467 htx_cut_data_blk(htx, blk, len);
6468 ret += len;
6469 goto end;
6470 }
6471 break;
6472
6473 default:
6474 goto end;
6475 }
6476
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006477 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006478 len -= sz;
6479 ret += sz;
6480 blk = htx_remove_blk(htx, blk);
6481 }
6482
6483end:
6484 flt_update_offsets(filter, msg->chn, -ret);
6485 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6486 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6487 * to loose the EOM flag if the message is empty.
6488 */
6489}
6490
6491/* Copies input data found in an HTTP message. Unlike the channel function used
6492 * to duplicate raw data, this one can only be called inside a filter, from
6493 * http_payload callback. So it cannot yield. An exception is returned if it is
6494 * called from another callback. If nothing was copied, a nil value is pushed on
6495 * the stack.
6496 */
6497__LJMP static int hlua_http_msg_get_body(lua_State *L)
6498{
6499 struct http_msg *msg;
6500 struct filter *filter;
6501 size_t output, input;
6502 int offset, len;
6503
6504 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6505 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6506 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6507
6508 if (msg->msg_state < HTTP_MSG_DATA)
6509 WILL_LJMP(lua_error(L));
6510
6511 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6512 if (!filter || !hlua_filter_from_payload(filter))
6513 WILL_LJMP(lua_error(L));
6514
6515 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6516 lua_pushnil(L);
6517 return 1;
6518 }
6519
6520 offset = output;
6521 if (lua_gettop(L) > 1) {
6522 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6523 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006524 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006525 offset += output;
6526 if (offset < output || offset > input + output) {
6527 lua_pushfstring(L, "offset out of range.");
6528 WILL_LJMP(lua_error(L));
6529 }
6530 }
6531 len = output + input - offset;
6532 if (lua_gettop(L) == 3) {
6533 len = MAY_LJMP(luaL_checkinteger(L, 3));
6534 if (!len)
6535 goto dup;
6536 if (len == -1)
6537 len = global.tune.bufsize;
6538 if (len < 0) {
6539 lua_pushfstring(L, "length out of range.");
6540 WILL_LJMP(lua_error(L));
6541 }
6542 }
6543
6544 dup:
6545 _hlua_http_msg_dup(msg, L, offset, len);
6546 return 1;
6547}
6548
6549/* Appends a string to the HTTP message, after all existing DATA blocks but
6550 * before the trailers, if any. It returns the amount of data written or -1 if
6551 * nothing was copied. Unlike the channel function used to append data, this one
6552 * can only be called inside a filter, from http_payload callback. So it cannot
6553 * yield. An exception is returned if it is called from another callback.
6554 */
6555__LJMP static int hlua_http_msg_append(lua_State *L)
6556{
6557 struct http_msg *msg;
6558 struct filter *filter;
6559 const char *str;
6560 size_t offset, len, sz;
6561 int ret;
6562
6563 MAY_LJMP(check_args(L, 2, "append"));
6564 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6565
6566 if (msg->msg_state < HTTP_MSG_DATA)
6567 WILL_LJMP(lua_error(L));
6568
6569 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6570 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6571 if (!filter || !hlua_filter_from_payload(filter))
6572 WILL_LJMP(lua_error(L));
6573
6574 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6575 lua_pushinteger(L, ret);
6576 return 1;
6577}
6578
6579/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6580 * returns the amount of data written or -1 if nothing was copied. Unlike the
6581 * channel function used to prepend data, this one can only be called inside a
6582 * filter, from http_payload callback. So it cannot yield. An exception is
6583 * returned if it is called from another callback.
6584 */
6585__LJMP static int hlua_http_msg_prepend(lua_State *L)
6586{
6587 struct http_msg *msg;
6588 struct filter *filter;
6589 const char *str;
6590 size_t offset, len, sz;
6591 int ret;
6592
6593 MAY_LJMP(check_args(L, 2, "prepend"));
6594 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006595
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006596 if (msg->msg_state < HTTP_MSG_DATA)
6597 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006598
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006599 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6600 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6601 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006602 WILL_LJMP(lua_error(L));
6603
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006604 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6605 lua_pushinteger(L, ret);
6606 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006607}
6608
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006609/* Inserts a string to the HTTP message at a given offset. By default the string
6610 * is appended at the end of DATA blocks. It returns the amount of data written
6611 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6612 * this one can only be called inside a filter, from http_payload callback. So
6613 * it cannot yield. An exception is returned if it is called from another
6614 * callback.
6615 */
6616__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006617{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006618 struct http_msg *msg;
6619 struct filter *filter;
6620 const char *str;
6621 size_t input, output, sz;
6622 int offset;
6623 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006624
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006625 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6626 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6627 MAY_LJMP(check_args(L, 2, "insert"));
6628 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006629
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006630 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006631 WILL_LJMP(lua_error(L));
6632
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006633 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6634 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6635 if (!filter || !hlua_filter_from_payload(filter))
6636 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006637
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006638 offset = input + output;
6639 if (lua_gettop(L) > 2) {
6640 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6641 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006642 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006643 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006644 if (offset < output || offset > output + input) {
6645 lua_pushfstring(L, "offset out of range.");
6646 WILL_LJMP(lua_error(L));
6647 }
6648 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006649
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006650 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6651 lua_pushinteger(L, ret);
6652 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006653}
6654
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006655/* Removes a given amount of data from the HTTP message at a given offset. By
6656 * default all DATA blocks are removed. It returns the amount of data
6657 * removed. Unlike the channel function used to remove data, this one can only
6658 * be called inside a filter, from http_payload callback. So it cannot yield. An
6659 * exception is returned if it is called from another callback.
6660 */
6661__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006662{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006663 struct http_msg *msg;
6664 struct filter *filter;
6665 size_t input, output;
6666 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006667
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006668 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6669 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6670 MAY_LJMP(check_args(L, 2, "insert"));
6671 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006672
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006673 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006674 WILL_LJMP(lua_error(L));
6675
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006676 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6677 if (!filter || !hlua_filter_from_payload(filter))
6678 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006679
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006680 offset = input + output;
6681 if (lua_gettop(L) > 2) {
6682 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6683 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006684 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006685 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006686 if (offset < output || offset > output + input) {
6687 lua_pushfstring(L, "offset out of range.");
6688 WILL_LJMP(lua_error(L));
6689 }
6690 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006691
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006692 len = output + input - offset;
6693 if (lua_gettop(L) == 4) {
6694 len = MAY_LJMP(luaL_checkinteger(L, 4));
6695 if (!len)
6696 goto end;
6697 if (len == -1)
6698 len = output + input - offset;
6699 if (len < 0 || offset + len > output + input) {
6700 lua_pushfstring(L, "length out of range.");
6701 WILL_LJMP(lua_error(L));
6702 }
6703 }
6704
6705 _hlua_http_msg_delete(msg, filter, offset, len);
6706
6707 end:
6708 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006709 return 1;
6710}
6711
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006712/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006713 * all remaining data are removed, accordingly to the filter context. It returns
6714 * the amount of data written or -1 if nothing was copied. Unlike the channel
6715 * function used to replace data, this one can only be called inside a filter,
6716 * from http_payload callback. So it cannot yield. An exception is returned if
6717 * it is called from another callback.
6718 */
6719__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006720{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006721 struct http_msg *msg;
6722 struct filter *filter;
6723 struct htx *htx;
6724 const char *str;
6725 size_t input, output, sz;
6726 int offset, len;
6727 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006728
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006729 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6730 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6731 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6732
6733 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006734 WILL_LJMP(lua_error(L));
6735
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006736 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6737 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6738 if (!filter || !hlua_filter_from_payload(filter))
6739 WILL_LJMP(lua_error(L));
6740
6741 offset = output;
6742 if (lua_gettop(L) > 2) {
6743 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6744 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006745 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 offset += output;
6747 if (offset < output || offset > input + output) {
6748 lua_pushfstring(L, "offset out of range.");
6749 WILL_LJMP(lua_error(L));
6750 }
6751 }
6752
6753 len = output + input - offset;
6754 if (lua_gettop(L) == 4) {
6755 len = MAY_LJMP(luaL_checkinteger(L, 4));
6756 if (!len)
6757 goto set;
6758 if (len == -1)
6759 len = output + input - offset;
6760 if (len < 0 || offset + len > output + input) {
6761 lua_pushfstring(L, "length out of range.");
6762 WILL_LJMP(lua_error(L));
6763 }
6764 }
6765
6766 set:
6767 /* Be sure we can copied the string once input data will be removed. */
6768 htx = htx_from_buf(&msg->chn->buf);
6769 if (sz > htx_free_data_space(htx) + len)
6770 lua_pushinteger(L, -1);
6771 else {
6772 _hlua_http_msg_delete(msg, filter, offset, len);
6773 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6774 lua_pushinteger(L, ret);
6775 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006776 return 1;
6777}
6778
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006779/* Prepends data into an HTTP message and forward it, from the filter point of
6780 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6781 * the channel function used to send data, this one can only be called inside a
6782 * filter, from http_payload callback. So it cannot yield. An exception is
6783 * returned if it is called from another callback.
6784 */
6785__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006786{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006787 struct http_msg *msg;
6788 struct filter *filter;
6789 struct htx *htx;
6790 const char *str;
6791 size_t offset, len, sz;
6792 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006793
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006794 MAY_LJMP(check_args(L, 2, "send"));
6795 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6796
6797 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006798 WILL_LJMP(lua_error(L));
6799
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006800 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6801 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6802 if (!filter || !hlua_filter_from_payload(filter))
6803 WILL_LJMP(lua_error(L));
6804
6805 /* Return an error if the channel's output is closed */
6806 if (unlikely(channel_output_closed(msg->chn))) {
6807 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006808 return 1;
6809 }
6810
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006811 htx = htx_from_buf(&msg->chn->buf);
6812 if (sz > htx_free_data_space(htx)) {
6813 lua_pushinteger(L, -1);
6814 return 1;
6815 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006816
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006817 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6818 if (ret > 0) {
6819 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6820
6821 FLT_OFF(filter, msg->chn) += ret;
6822 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6823 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6824 }
6825
6826 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006827 return 1;
6828}
6829
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006830/* Forwards a given amount of bytes. It return -1 if the channel's output is
6831 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6832 * channel function used to forward data, this one can only be called inside a
6833 * filter, from http_payload callback. So it cannot yield. An exception is
6834 * returned if it is called from another callback. All other functions deal with
6835 * DATA block, this one not.
6836*/
6837__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006838{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006839 struct http_msg *msg;
6840 struct filter *filter;
6841 size_t offset, len;
6842 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006843
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006844 MAY_LJMP(check_args(L, 2, "forward"));
6845 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6846
6847 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006848 WILL_LJMP(lua_error(L));
6849
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006850 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6851 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6852 if (!filter || !hlua_filter_from_payload(filter))
6853 WILL_LJMP(lua_error(L));
6854
6855 /* Nothing to do, just return */
6856 if (!fwd)
6857 goto end;
6858
6859 /* Return an error if the channel's output is closed */
6860 if (unlikely(channel_output_closed(msg->chn))) {
6861 ret = -1;
6862 goto end;
6863 }
6864
6865 ret = fwd;
6866 if (ret > len)
6867 ret = len;
6868
6869 if (ret) {
6870 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6871
6872 FLT_OFF(filter, msg->chn) += ret;
6873 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6874 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6875 }
6876
6877 end:
6878 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006879 return 1;
6880}
6881
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006882/* Set EOM flag on the HTX message.
6883 *
6884 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6885 * really know how to do without this feature.
6886 */
6887__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006888{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006889 struct http_msg *msg;
6890 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006891
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006892 MAY_LJMP(check_args(L, 1, "set_eom"));
6893 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6894 htx = htxbuf(&msg->chn->buf);
6895 htx->flags |= HTX_FL_EOM;
6896 return 0;
6897}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006898
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006899/* Unset EOM flag on the HTX message.
6900 *
6901 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6902 * really know how to do without this feature.
6903 */
6904__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6905{
6906 struct http_msg *msg;
6907 struct htx *htx;
6908
6909 MAY_LJMP(check_args(L, 1, "set_eom"));
6910 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6911 htx = htxbuf(&msg->chn->buf);
6912 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006913 return 0;
6914}
6915
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006916/*
6917 *
6918 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006919 * Class HTTPClient
6920 *
6921 *
6922 */
6923__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6924{
6925 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6926}
6927
William Lallemandf77f1de2021-09-28 19:10:38 +02006928
6929/* stops the httpclient and ask it to kill itself */
6930__LJMP static int hlua_httpclient_gc(lua_State *L)
6931{
6932 struct hlua_httpclient *hlua_hc;
6933
6934 MAY_LJMP(check_args(L, 1, "__gc"));
6935
6936 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6937
6938 httpclient_stop_and_destroy(hlua_hc->hc);
6939
6940 hlua_hc->hc = NULL;
6941
6942
6943 return 0;
6944}
6945
6946
William Lallemand3956c4e2021-09-21 16:25:15 +02006947__LJMP static int hlua_httpclient_new(lua_State *L)
6948{
6949 struct hlua_httpclient *hlua_hc;
6950 struct hlua *hlua;
6951
6952 /* Get hlua struct, or NULL if we execute from main lua state */
6953 hlua = hlua_gethlua(L);
6954 if (!hlua)
6955 return 0;
6956
6957 /* Check stack size. */
6958 if (!lua_checkstack(L, 3)) {
6959 hlua_pusherror(L, "httpclient: full stack");
6960 goto err;
6961 }
6962 /* Create the object: obj[0] = userdata. */
6963 lua_newtable(L);
6964 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6965 lua_rawseti(L, -2, 0);
6966 memset(hlua_hc, 0, sizeof(*hlua_hc));
6967
6968 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6969 if (!hlua_hc->hc)
6970 goto err;
6971
6972 /* Pop a class stream metatable and affect it to the userdata. */
6973 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6974 lua_setmetatable(L, -2);
6975
6976 return 1;
6977
6978 err:
6979 WILL_LJMP(lua_error(L));
6980 return 0;
6981}
6982
6983
6984/*
6985 * Callback of the httpclient, this callback wakes the lua task up, once the
6986 * httpclient receives some data
6987 *
6988 */
6989
William Lallemandbd5739e2021-10-28 15:41:38 +02006990static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02006991{
6992 struct hlua *hlua = hc->caller;
6993
6994 if (!hlua || !hlua->task)
6995 return;
6996
6997 task_wakeup(hlua->task, TASK_WOKEN_MSG);
6998}
6999
7000/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007001 * Fill the lua stack with headers from the httpclient response
7002 * This works the same way as the hlua_http_get_headers() function
7003 */
7004__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7005{
7006 struct http_hdr *hdr;
7007
7008 lua_newtable(L);
7009
William Lallemandef574b22021-10-05 16:19:31 +02007010 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007011 struct ist n, v;
7012 int len;
7013
7014 n = hdr->n;
7015 v = hdr->v;
7016
7017 /* Check for existing entry:
7018 * assume that the table is on the top of the stack, and
7019 * push the key in the stack, the function lua_gettable()
7020 * perform the lookup.
7021 */
7022
7023 lua_pushlstring(L, n.ptr, n.len);
7024 lua_gettable(L, -2);
7025
7026 switch (lua_type(L, -1)) {
7027 case LUA_TNIL:
7028 /* Table not found, create it. */
7029 lua_pop(L, 1); /* remove the nil value. */
7030 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7031 lua_newtable(L); /* create and push empty table. */
7032 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7033 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7034 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7035 break;
7036
7037 case LUA_TTABLE:
7038 /* Entry found: push the value in the table. */
7039 len = lua_rawlen(L, -1);
7040 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7041 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7042 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7043 break;
7044
7045 default:
7046 /* Other cases are errors. */
7047 hlua_pusherror(L, "internal error during the parsing of headers.");
7048 WILL_LJMP(lua_error(L));
7049 }
7050 }
7051 return 1;
7052}
7053
7054/*
William Lallemand746e6f32021-10-06 10:57:44 +02007055 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7056 *
7057 * Caller must free the result
7058 */
7059struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7060{
7061 struct http_hdr hdrs[global.tune.max_http_hdr];
7062 struct http_hdr *result = NULL;
7063 uint32_t hdr_num = 0;
7064
7065 lua_pushnil(L);
7066 while (lua_next(L, -2) != 0) {
7067 struct ist name, value;
7068 const char *n, *v;
7069 size_t nlen, vlen;
7070
7071 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7072 /* Skip element if the key is not a string or if the value is not a table */
7073 goto next_hdr;
7074 }
7075
7076 n = lua_tolstring(L, -2, &nlen);
7077 name = ist2(n, nlen);
7078
7079 /* Loop on header's values */
7080 lua_pushnil(L);
7081 while (lua_next(L, -2)) {
7082 if (!lua_isstring(L, -1)) {
7083 /* Skip the value if it is not a string */
7084 goto next_value;
7085 }
7086
7087 v = lua_tolstring(L, -1, &vlen);
7088 value = ist2(v, vlen);
7089 name = ist2(n, nlen);
7090
7091 hdrs[hdr_num].n = istdup(name);
7092 hdrs[hdr_num].v = istdup(value);
7093
7094 hdr_num++;
7095
7096 next_value:
7097 lua_pop(L, 1);
7098 }
7099
7100 next_hdr:
7101 lua_pop(L, 1);
7102
7103 }
7104
7105 if (hdr_num) {
7106 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007107 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007108 if (!result)
7109 goto skip_headers;
7110 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7111
7112 result[hdr_num].n = IST_NULL;
7113 result[hdr_num].v = IST_NULL;
7114 }
7115
7116skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007117
7118 return result;
7119}
7120
7121
William Lallemandbd5739e2021-10-28 15:41:38 +02007122/*
7123 * For each yield, checks if there is some data in the httpclient and push them
7124 * in the lua buffer, once the httpclient finished its job, push the result on
7125 * the stack
7126 */
7127__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7128{
7129 struct buffer *tr;
7130 int res;
7131 struct hlua *hlua = hlua_gethlua(L);
7132 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7133
7134
7135 tr = get_trash_chunk();
7136
7137 res = httpclient_res_xfer(hlua_hc->hc, tr);
7138 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7139
7140 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7141
7142 luaL_pushresult(&hlua_hc->b);
7143 lua_settable(L, -3);
7144
7145 lua_pushstring(L, "status");
7146 lua_pushinteger(L, hlua_hc->hc->res.status);
7147 lua_settable(L, -3);
7148
7149
7150 lua_pushstring(L, "reason");
7151 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7152 lua_settable(L, -3);
7153
7154 lua_pushstring(L, "headers");
7155 hlua_httpclient_get_headers(L, hlua_hc);
7156 lua_settable(L, -3);
7157
7158 return 1;
7159 }
7160
7161 if (httpclient_data(hlua_hc->hc))
7162 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7163
7164 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7165
7166 return 0;
7167}
7168
7169/*
7170 * Call this when trying to stream a body during a request
7171 */
7172__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7173{
7174 struct hlua *hlua;
7175 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7176 const char *body_str = NULL;
7177 int ret;
7178 int end = 0;
7179 size_t buf_len;
7180 size_t to_send = 0;
7181
7182 hlua = hlua_gethlua(L);
7183
7184 if (!hlua || !hlua->task)
7185 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7186 "'frontend', 'backend' or 'task'"));
7187
7188 ret = lua_getfield(L, -1, "body");
7189 if (ret != LUA_TSTRING)
7190 goto rcv;
7191
7192 body_str = lua_tolstring(L, -1, &buf_len);
7193 lua_pop(L, 1);
7194
Christopher Fauletfc591292022-01-12 14:46:03 +01007195 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007196
7197 if ((hlua_hc->sent + to_send) >= buf_len)
7198 end = 1;
7199
7200 /* the end flag is always set since we are using the whole remaining size */
7201 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7202
7203 if (buf_len > hlua_hc->sent) {
7204 /* still need to process the buffer */
7205 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7206 } else {
7207 goto rcv;
7208 /* we sent the whole request buffer we can recv */
7209 }
7210 return 0;
7211
7212rcv:
7213
7214 /* we return a "res" object */
7215 lua_newtable(L);
7216
William Lallemandbd5739e2021-10-28 15:41:38 +02007217 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007218 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007219
William Lallemand933fe392021-11-04 09:45:58 +01007220 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007221 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7222
7223 return 1;
7224}
William Lallemand746e6f32021-10-06 10:57:44 +02007225
William Lallemand3956c4e2021-09-21 16:25:15 +02007226/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007227 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007228 */
7229
William Lallemanddc2cc902021-10-26 11:43:26 +02007230__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007231{
7232 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007233 struct http_hdr *hdrs = NULL;
7234 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007235 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007236 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007237 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007238 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007239 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007240
7241 hlua = hlua_gethlua(L);
7242
7243 if (!hlua || !hlua->task)
7244 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7245 "'frontend', 'backend' or 'task'"));
7246
William Lallemand746e6f32021-10-06 10:57:44 +02007247 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7248 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7249
William Lallemand4f4f2b72022-02-17 20:00:23 +01007250 hlua_hc = hlua_checkhttpclient(L, 1);
7251
William Lallemand7177a952022-03-03 15:33:12 +01007252 lua_pushnil(L); /* first key */
7253 while (lua_next(L, 2)) {
7254 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7255 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7256 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007257
William Lallemand7177a952022-03-03 15:33:12 +01007258 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7259 if (lua_type(L, -1) != LUA_TSTRING)
7260 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7261 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007262
William Lallemand7177a952022-03-03 15:33:12 +01007263 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7264 if (lua_type(L, -1) != LUA_TNUMBER)
7265 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7266 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007267
William Lallemand7177a952022-03-03 15:33:12 +01007268 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7269 if (lua_type(L, -1) != LUA_TTABLE)
7270 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7271 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007272
William Lallemand7177a952022-03-03 15:33:12 +01007273 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7274 if (lua_type(L, -1) != LUA_TSTRING)
7275 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7276 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007277
William Lallemand7177a952022-03-03 15:33:12 +01007278 } else {
7279 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7280 }
7281 /* removes 'value'; keeps 'key' for next iteration */
7282 lua_pop(L, 1);
7283 }
William Lallemanddec25c32021-10-25 19:48:37 +02007284
William Lallemand746e6f32021-10-06 10:57:44 +02007285 if (!url_str) {
7286 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7287 return 0;
7288 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007289
William Lallemand10a37362022-03-02 16:18:26 +01007290 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007291
7292 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007293 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007294
7295 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007296 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7297 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7298 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007299 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007300
William Lallemandbd5739e2021-10-28 15:41:38 +02007301 /* a body is available, it will use the request callback */
7302 if (body_str) {
7303 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7304 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007305
William Lallemandbd5739e2021-10-28 15:41:38 +02007306 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007307
William Lallemand746e6f32021-10-06 10:57:44 +02007308 /* free the temporary headers array */
7309 hdrs_i = hdrs;
7310 while (hdrs_i && isttest(hdrs_i->n)) {
7311 istfree(&hdrs_i->n);
7312 istfree(&hdrs_i->v);
7313 hdrs_i++;
7314 }
7315 ha_free(&hdrs);
7316
7317
William Lallemand6137a9e2021-10-26 15:01:53 +02007318 if (ret != ERR_NONE) {
7319 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7320 return 0;
7321 }
7322
William Lallemand6137a9e2021-10-26 15:01:53 +02007323 httpclient_start(hlua_hc->hc);
7324
William Lallemandbd5739e2021-10-28 15:41:38 +02007325 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007326
William Lallemand3956c4e2021-09-21 16:25:15 +02007327 return 0;
7328}
7329
7330/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007331 * Sends an HTTP HEAD request and wait for a response
7332 *
7333 * httpclient:head(url, headers, payload)
7334 */
7335__LJMP static int hlua_httpclient_head(lua_State *L)
7336{
7337 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7338}
7339
7340/*
7341 * Send an HTTP GET request and wait for a response
7342 *
7343 * httpclient:get(url, headers, payload)
7344 */
7345__LJMP static int hlua_httpclient_get(lua_State *L)
7346{
7347 return hlua_httpclient_send(L, HTTP_METH_GET);
7348
7349}
7350
7351/*
7352 * Sends an HTTP PUT request and wait for a response
7353 *
7354 * httpclient:put(url, headers, payload)
7355 */
7356__LJMP static int hlua_httpclient_put(lua_State *L)
7357{
7358 return hlua_httpclient_send(L, HTTP_METH_PUT);
7359}
7360
7361/*
7362 * Send an HTTP POST request and wait for a response
7363 *
7364 * httpclient:post(url, headers, payload)
7365 */
7366__LJMP static int hlua_httpclient_post(lua_State *L)
7367{
7368 return hlua_httpclient_send(L, HTTP_METH_POST);
7369}
7370
7371
7372/*
7373 * Sends an HTTP DELETE request and wait for a response
7374 *
7375 * httpclient:delete(url, headers, payload)
7376 */
7377__LJMP static int hlua_httpclient_delete(lua_State *L)
7378{
7379 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7380}
7381
7382/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007383 *
7384 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007385 * Class TXN
7386 *
7387 *
7388 */
7389
7390/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007391 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007392 */
7393__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7394{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007395 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007396}
7397
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007398__LJMP static int hlua_set_var(lua_State *L)
7399{
7400 struct hlua_txn *htxn;
7401 const char *name;
7402 size_t len;
7403 struct sample smp;
7404
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007405 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7406 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007407
7408 /* It is useles to retrieve the stream, but this function
7409 * runs only in a stream context.
7410 */
7411 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7412 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7413
7414 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007415 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007416 hlua_lua2smp(L, 3, &smp);
7417
7418 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007419 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007420
7421 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7422 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7423 else
7424 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7425
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007426 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007427}
7428
Christopher Faulet85d79c92016-11-09 16:54:56 +01007429__LJMP static int hlua_unset_var(lua_State *L)
7430{
7431 struct hlua_txn *htxn;
7432 const char *name;
7433 size_t len;
7434 struct sample smp;
7435
7436 MAY_LJMP(check_args(L, 2, "unset_var"));
7437
7438 /* It is useles to retrieve the stream, but this function
7439 * runs only in a stream context.
7440 */
7441 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7442 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7443
7444 /* Unset the variable. */
7445 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007446 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7447 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007448}
7449
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007450__LJMP static int hlua_get_var(lua_State *L)
7451{
7452 struct hlua_txn *htxn;
7453 const char *name;
7454 size_t len;
7455 struct sample smp;
7456
7457 MAY_LJMP(check_args(L, 2, "get_var"));
7458
7459 /* It is useles to retrieve the stream, but this function
7460 * runs only in a stream context.
7461 */
7462 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7463 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7464
Willy Tarreau7560dd42016-03-10 16:28:58 +01007465 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007466 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007467 lua_pushnil(L);
7468 return 1;
7469 }
7470
7471 return hlua_smp2lua(L, &smp);
7472}
7473
Willy Tarreau59551662015-03-10 14:23:13 +01007474__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007475{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007476 struct hlua *hlua;
7477
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007478 MAY_LJMP(check_args(L, 2, "set_priv"));
7479
Willy Tarreau87b09662015-04-03 00:22:06 +02007480 /* It is useles to retrieve the stream, but this function
7481 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007482 */
7483 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007484
7485 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007486 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007487 if (!hlua)
7488 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007489
7490 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007491 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007492
7493 /* Get and store new value. */
7494 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7495 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7496
7497 return 0;
7498}
7499
Willy Tarreau59551662015-03-10 14:23:13 +01007500__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007501{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007502 struct hlua *hlua;
7503
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007504 MAY_LJMP(check_args(L, 1, "get_priv"));
7505
Willy Tarreau87b09662015-04-03 00:22:06 +02007506 /* It is useles to retrieve the stream, but this function
7507 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007508 */
7509 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007510
7511 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007512 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007513 if (!hlua) {
7514 lua_pushnil(L);
7515 return 1;
7516 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007517
7518 /* Push configuration index in the stack. */
7519 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7520
7521 return 1;
7522}
7523
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007524/* Create stack entry containing a class TXN. This function
7525 * return 0 if the stack does not contains free slots,
7526 * otherwise it returns 1.
7527 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007528static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007529{
Willy Tarreaude491382015-04-06 11:04:28 +02007530 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007531
7532 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007533 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007534 return 0;
7535
7536 /* NOTE: The allocation never fails. The failure
7537 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007538 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007539 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007540 /* Create the object: obj[0] = userdata. */
7541 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007542 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007543 lua_rawseti(L, -2, 0);
7544
Willy Tarreaude491382015-04-06 11:04:28 +02007545 htxn->s = s;
7546 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007547 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007548 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007549
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007550 /* Create the "f" field that contains a list of fetches. */
7551 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007552 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007553 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007554 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007555
7556 /* Create the "sf" field that contains a list of stringsafe fetches. */
7557 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007558 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007559 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007560 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007561
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007562 /* Create the "c" field that contains a list of converters. */
7563 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007564 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007565 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007566 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007567
7568 /* Create the "sc" field that contains a list of stringsafe converters. */
7569 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007570 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007571 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007572 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007573
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007574 /* Create the "req" field that contains the request channel object. */
7575 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007576 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007577 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007578 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007579
7580 /* Create the "res" field that contains the response channel object. */
7581 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007582 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007583 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007584 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007585
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007586 /* Creates the HTTP object is the current proxy allows http. */
7587 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007588 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007589 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007590 return 0;
7591 }
7592 else
7593 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007594 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007595
Christopher Faulet78c35472020-02-26 17:14:08 +01007596 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7597 /* HTTPMessage object are created when a lua TXN is created from
7598 * a filter context only
7599 */
7600
7601 /* Creates the HTTP-Request object is the current proxy allows http. */
7602 lua_pushstring(L, "http_req");
7603 if (p->mode == PR_MODE_HTTP) {
7604 if (!hlua_http_msg_new(L, &s->txn->req))
7605 return 0;
7606 }
7607 else
7608 lua_pushnil(L);
7609 lua_rawset(L, -3);
7610
7611 /* Creates the HTTP-Response object is the current proxy allows http. */
7612 lua_pushstring(L, "http_res");
7613 if (p->mode == PR_MODE_HTTP) {
7614 if (!hlua_http_msg_new(L, &s->txn->rsp))
7615 return 0;
7616 }
7617 else
7618 lua_pushnil(L);
7619 lua_rawset(L, -3);
7620 }
7621
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007622 /* Pop a class sesison metatable and affect it to the userdata. */
7623 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7624 lua_setmetatable(L, -2);
7625
7626 return 1;
7627}
7628
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007629__LJMP static int hlua_txn_deflog(lua_State *L)
7630{
7631 const char *msg;
7632 struct hlua_txn *htxn;
7633
7634 MAY_LJMP(check_args(L, 2, "deflog"));
7635 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7636 msg = MAY_LJMP(luaL_checkstring(L, 2));
7637
7638 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7639 return 0;
7640}
7641
7642__LJMP static int hlua_txn_log(lua_State *L)
7643{
7644 int level;
7645 const char *msg;
7646 struct hlua_txn *htxn;
7647
7648 MAY_LJMP(check_args(L, 3, "log"));
7649 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7650 level = MAY_LJMP(luaL_checkinteger(L, 2));
7651 msg = MAY_LJMP(luaL_checkstring(L, 3));
7652
7653 if (level < 0 || level >= NB_LOG_LEVELS)
7654 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7655
7656 hlua_sendlog(htxn->s->be, level, msg);
7657 return 0;
7658}
7659
7660__LJMP static int hlua_txn_log_debug(lua_State *L)
7661{
7662 const char *msg;
7663 struct hlua_txn *htxn;
7664
7665 MAY_LJMP(check_args(L, 2, "Debug"));
7666 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7667 msg = MAY_LJMP(luaL_checkstring(L, 2));
7668 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7669 return 0;
7670}
7671
7672__LJMP static int hlua_txn_log_info(lua_State *L)
7673{
7674 const char *msg;
7675 struct hlua_txn *htxn;
7676
7677 MAY_LJMP(check_args(L, 2, "Info"));
7678 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7679 msg = MAY_LJMP(luaL_checkstring(L, 2));
7680 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7681 return 0;
7682}
7683
7684__LJMP static int hlua_txn_log_warning(lua_State *L)
7685{
7686 const char *msg;
7687 struct hlua_txn *htxn;
7688
7689 MAY_LJMP(check_args(L, 2, "Warning"));
7690 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7691 msg = MAY_LJMP(luaL_checkstring(L, 2));
7692 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7693 return 0;
7694}
7695
7696__LJMP static int hlua_txn_log_alert(lua_State *L)
7697{
7698 const char *msg;
7699 struct hlua_txn *htxn;
7700
7701 MAY_LJMP(check_args(L, 2, "Alert"));
7702 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7703 msg = MAY_LJMP(luaL_checkstring(L, 2));
7704 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7705 return 0;
7706}
7707
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007708__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7709{
7710 struct hlua_txn *htxn;
7711 int ll;
7712
7713 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7714 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7715 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7716
7717 if (ll < 0 || ll > 7)
7718 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7719
7720 htxn->s->logs.level = ll;
7721 return 0;
7722}
7723
7724__LJMP static int hlua_txn_set_tos(lua_State *L)
7725{
7726 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007727 int tos;
7728
7729 MAY_LJMP(check_args(L, 2, "set_tos"));
7730 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7731 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7732
Willy Tarreau1a18b542018-12-11 16:37:42 +01007733 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007734 return 0;
7735}
7736
7737__LJMP static int hlua_txn_set_mark(lua_State *L)
7738{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007739 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007740 int mark;
7741
7742 MAY_LJMP(check_args(L, 2, "set_mark"));
7743 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7744 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7745
Lukas Tribus579e3e32019-08-11 18:03:45 +02007746 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007747 return 0;
7748}
7749
Patrick Hemmer268a7072018-05-11 12:52:31 -04007750__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7751{
7752 struct hlua_txn *htxn;
7753
7754 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7755 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7756 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7757 return 0;
7758}
7759
7760__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7761{
7762 struct hlua_txn *htxn;
7763
7764 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7765 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7766 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7767 return 0;
7768}
7769
Christopher Faulet700d9e82020-01-31 12:21:52 +01007770/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007771 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007772 * message and terminate the transaction. It returns 1 on success and 0 on
7773 * error. The Reply must be on top of the stack.
7774 */
7775__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7776{
7777 struct htx *htx;
7778 struct htx_sl *sl;
7779 struct h1m h1m;
7780 const char *status, *reason, *body;
7781 size_t status_len, reason_len, body_len;
7782 int ret, code, flags;
7783
7784 code = 200;
7785 status = "200";
7786 status_len = 3;
7787 ret = lua_getfield(L, -1, "status");
7788 if (ret == LUA_TNUMBER) {
7789 code = lua_tointeger(L, -1);
7790 status = lua_tolstring(L, -1, &status_len);
7791 }
7792 lua_pop(L, 1);
7793
7794 reason = http_get_reason(code);
7795 reason_len = strlen(reason);
7796 ret = lua_getfield(L, -1, "reason");
7797 if (ret == LUA_TSTRING)
7798 reason = lua_tolstring(L, -1, &reason_len);
7799 lua_pop(L, 1);
7800
7801 body = NULL;
7802 body_len = 0;
7803 ret = lua_getfield(L, -1, "body");
7804 if (ret == LUA_TSTRING)
7805 body = lua_tolstring(L, -1, &body_len);
7806 lua_pop(L, 1);
7807
7808 /* Prepare the response before inserting the headers */
7809 h1m_init_res(&h1m);
7810 htx = htx_from_buf(&s->res.buf);
7811 channel_htx_truncate(&s->res, htx);
7812 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7813 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7814 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7815 ist2(status, status_len), ist2(reason, reason_len));
7816 }
7817 else {
7818 flags = HTX_SL_F_IS_RESP;
7819 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7820 ist2(status, status_len), ist2(reason, reason_len));
7821 }
7822 if (!sl)
7823 goto fail;
7824 sl->info.res.status = code;
7825
7826 /* Push in the stack the "headers" entry. */
7827 ret = lua_getfield(L, -1, "headers");
7828 if (ret != LUA_TTABLE)
7829 goto skip_headers;
7830
7831 lua_pushnil(L);
7832 while (lua_next(L, -2) != 0) {
7833 struct ist name, value;
7834 const char *n, *v;
7835 size_t nlen, vlen;
7836
7837 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7838 /* Skip element if the key is not a string or if the value is not a table */
7839 goto next_hdr;
7840 }
7841
7842 n = lua_tolstring(L, -2, &nlen);
7843 name = ist2(n, nlen);
7844 if (isteqi(name, ist("content-length"))) {
7845 /* Always skip content-length header. It will be added
7846 * later with the correct len
7847 */
7848 goto next_hdr;
7849 }
7850
7851 /* Loop on header's values */
7852 lua_pushnil(L);
7853 while (lua_next(L, -2)) {
7854 if (!lua_isstring(L, -1)) {
7855 /* Skip the value if it is not a string */
7856 goto next_value;
7857 }
7858
7859 v = lua_tolstring(L, -1, &vlen);
7860 value = ist2(v, vlen);
7861
7862 if (isteqi(name, ist("transfer-encoding")))
7863 h1_parse_xfer_enc_header(&h1m, value);
7864 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7865 goto fail;
7866
7867 next_value:
7868 lua_pop(L, 1);
7869 }
7870
7871 next_hdr:
7872 lua_pop(L, 1);
7873 }
7874 skip_headers:
7875 lua_pop(L, 1);
7876
7877 /* Update h1m flags: CLEN is set if CHNK is not present */
7878 if (!(h1m.flags & H1_MF_CHNK)) {
7879 const char *clen = ultoa(body_len);
7880
7881 h1m.flags |= H1_MF_CLEN;
7882 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7883 goto fail;
7884 }
7885 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7886 h1m.flags |= H1_MF_XFER_LEN;
7887
7888 /* Update HTX start-line flags */
7889 if (h1m.flags & H1_MF_XFER_ENC)
7890 flags |= HTX_SL_F_XFER_ENC;
7891 if (h1m.flags & H1_MF_XFER_LEN) {
7892 flags |= HTX_SL_F_XFER_LEN;
7893 if (h1m.flags & H1_MF_CHNK)
7894 flags |= HTX_SL_F_CHNK;
7895 else if (h1m.flags & H1_MF_CLEN)
7896 flags |= HTX_SL_F_CLEN;
7897 if (h1m.body_len == 0)
7898 flags |= HTX_SL_F_BODYLESS;
7899 }
7900 sl->flags |= flags;
7901
7902
7903 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007904 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007905 goto fail;
7906
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007907 htx->flags |= HTX_FL_EOM;
7908
Christopher Faulet700d9e82020-01-31 12:21:52 +01007909 /* Now, forward the response and terminate the transaction */
7910 s->txn->status = code;
7911 htx_to_buf(htx, &s->res.buf);
7912 if (!http_forward_proxy_resp(s, 1))
7913 goto fail;
7914
7915 return 1;
7916
7917 fail:
7918 channel_htx_truncate(&s->res, htx);
7919 return 0;
7920}
7921
7922/* Terminate a transaction if called from a lua action. For TCP streams,
7923 * processing is just aborted. Nothing is returned to the client and all
7924 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7925 * is forwarded to the client before terminating the transaction. On success,
7926 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7927 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7928 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007929 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007930__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007931{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007932 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007933 struct stream *s;
7934 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007935
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007936 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007937
Christopher Faulet700d9e82020-01-31 12:21:52 +01007938 /* If the flags NOTERM is set, we cannot terminate the session, so we
7939 * just end the execution of the current lua code. */
7940 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007941 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007942
Christopher Faulet700d9e82020-01-31 12:21:52 +01007943 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007944 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007945 struct channel *req = &s->req;
7946 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007947
Christopher Faulet700d9e82020-01-31 12:21:52 +01007948 channel_auto_read(req);
7949 channel_abort(req);
7950 channel_auto_close(req);
7951 channel_erase(req);
7952
7953 res->wex = tick_add_ifset(now_ms, res->wto);
7954 channel_auto_read(res);
7955 channel_auto_close(res);
7956 channel_shutr_now(res);
7957
7958 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7959 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007960 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007961
Christopher Faulet700d9e82020-01-31 12:21:52 +01007962 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7963 /* No reply or invalid reply */
7964 s->txn->status = 0;
7965 http_reply_and_close(s, 0, NULL);
7966 }
7967 else {
7968 /* Remove extra args to have the reply on top of the stack */
7969 if (lua_gettop(L) > 2)
7970 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007971
Christopher Faulet700d9e82020-01-31 12:21:52 +01007972 if (!hlua_txn_forward_reply(L, s)) {
7973 if (!(s->flags & SF_ERR_MASK))
7974 s->flags |= SF_ERR_PRXCOND;
7975 lua_pushinteger(L, ACT_RET_ERR);
7976 WILL_LJMP(hlua_done(L));
7977 return 0; /* Never reached */
7978 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007979 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007980
Christopher Faulet700d9e82020-01-31 12:21:52 +01007981 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7982 if (htxn->dir == SMP_OPT_DIR_REQ) {
7983 /* let's log the request time */
7984 s->logs.tv_request = now;
7985 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007986 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007987 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007988
Christopher Faulet700d9e82020-01-31 12:21:52 +01007989 done:
7990 if (!(s->flags & SF_ERR_MASK))
7991 s->flags |= SF_ERR_LOCAL;
7992 if (!(s->flags & SF_FINST_MASK))
7993 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007994
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007995 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7996 lua_pushinteger(L, -1);
7997 else
7998 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007999 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008000 return 0;
8001}
8002
Christopher Faulet700d9e82020-01-31 12:21:52 +01008003/*
8004 *
8005 *
8006 * Class REPLY
8007 *
8008 *
8009 */
8010
8011/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8012 * free slots, the function fails and returns 0;
8013 */
8014static int hlua_txn_reply_new(lua_State *L)
8015{
8016 struct hlua_txn *htxn;
8017 const char *reason, *body = NULL;
8018 int ret, status;
8019
8020 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008021 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008022 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8023 WILL_LJMP(lua_error(L));
8024 }
8025
8026 /* Default value */
8027 status = 200;
8028 reason = http_get_reason(status);
8029
8030 if (lua_istable(L, 2)) {
8031 /* load status and reason from the table argument at index 2 */
8032 ret = lua_getfield(L, 2, "status");
8033 if (ret == LUA_TNIL)
8034 goto reason;
8035 else if (ret != LUA_TNUMBER) {
8036 /* invalid status: ignore the reason */
8037 goto body;
8038 }
8039 status = lua_tointeger(L, -1);
8040
8041 reason:
8042 lua_pop(L, 1); /* restore the stack: remove status */
8043 ret = lua_getfield(L, 2, "reason");
8044 if (ret == LUA_TSTRING)
8045 reason = lua_tostring(L, -1);
8046
8047 body:
8048 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8049 ret = lua_getfield(L, 2, "body");
8050 if (ret == LUA_TSTRING)
8051 body = lua_tostring(L, -1);
8052 lua_pop(L, 1); /* restore the stack: remove body */
8053 }
8054
8055 /* Create the Reply table */
8056 lua_newtable(L);
8057
8058 /* Add status element */
8059 lua_pushstring(L, "status");
8060 lua_pushinteger(L, status);
8061 lua_settable(L, -3);
8062
8063 /* Add reason element */
8064 reason = http_get_reason(status);
8065 lua_pushstring(L, "reason");
8066 lua_pushstring(L, reason);
8067 lua_settable(L, -3);
8068
8069 /* Add body element, nil if undefined */
8070 lua_pushstring(L, "body");
8071 if (body)
8072 lua_pushstring(L, body);
8073 else
8074 lua_pushnil(L);
8075 lua_settable(L, -3);
8076
8077 /* Add headers element */
8078 lua_pushstring(L, "headers");
8079 lua_newtable(L);
8080
8081 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8082 if (lua_istable(L, 2)) {
8083 /* load headers from the table argument at index 2. If it is a table, copy it. */
8084 ret = lua_getfield(L, 2, "headers");
8085 if (ret == LUA_TTABLE) {
8086 /* stack: [ ... <headers:table>, <table> ] */
8087 lua_pushnil(L);
8088 while (lua_next(L, -2) != 0) {
8089 /* stack: [ ... <headers:table>, <table>, k, v] */
8090 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8091 /* invalid value type, skip it */
8092 lua_pop(L, 1);
8093 continue;
8094 }
8095
8096
8097 /* Duplicate the key and swap it with the value. */
8098 lua_pushvalue(L, -2);
8099 lua_insert(L, -2);
8100 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8101
8102 lua_newtable(L);
8103 lua_insert(L, -2);
8104 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8105
8106 if (lua_isstring(L, -1)) {
8107 /* push the value in the inner table */
8108 lua_rawseti(L, -2, 1);
8109 }
8110 else { /* table */
8111 lua_pushnil(L);
8112 while (lua_next(L, -2) != 0) {
8113 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8114 if (!lua_isstring(L, -1)) {
8115 /* invalid value type, skip it*/
8116 lua_pop(L, 1);
8117 continue;
8118 }
8119 /* push the value in the inner table */
8120 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8121 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8122 }
8123 lua_pop(L, 1);
8124 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8125 }
8126
8127 /* push (k,v) on the stack in the headers table:
8128 * stack: [ ... <headers:table>, <table>, k, k, v ]
8129 */
8130 lua_settable(L, -5);
8131 /* stack: [ ... <headers:table>, <table>, k ] */
8132 }
8133 }
8134 lua_pop(L, 1);
8135 }
8136 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8137 lua_settable(L, -3);
8138 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8139
8140 /* Pop a class sesison metatable and affect it to the userdata. */
8141 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8142 lua_setmetatable(L, -2);
8143 return 1;
8144}
8145
8146/* Set the reply status code, and optionally the reason. If no reason is
8147 * provided, the default one corresponding to the status code is used.
8148 */
8149__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8150{
8151 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8152 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8153
8154 /* First argument (self) must be a table */
8155 luaL_checktype(L, 1, LUA_TTABLE);
8156
8157 if (status < 100 || status > 599) {
8158 lua_pushboolean(L, 0);
8159 return 1;
8160 }
8161 if (!reason)
8162 reason = http_get_reason(status);
8163
8164 lua_pushinteger(L, status);
8165 lua_setfield(L, 1, "status");
8166
8167 lua_pushstring(L, reason);
8168 lua_setfield(L, 1, "reason");
8169
8170 lua_pushboolean(L, 1);
8171 return 1;
8172}
8173
8174/* Add a header into the reply object. Each header name is associated to an
8175 * array of values in the "headers" table. If the header name is not found, a
8176 * new entry is created.
8177 */
8178__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8179{
8180 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8181 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8182 int ret;
8183
8184 /* First argument (self) must be a table */
8185 luaL_checktype(L, 1, LUA_TTABLE);
8186
8187 /* Push in the stack the "headers" entry. */
8188 ret = lua_getfield(L, 1, "headers");
8189 if (ret != LUA_TTABLE) {
8190 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8191 WILL_LJMP(lua_error(L));
8192 }
8193
8194 /* check if the header is already registered. If not, register it. */
8195 ret = lua_getfield(L, -1, name);
8196 if (ret == LUA_TNIL) {
8197 /* Entry not found. */
8198 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8199
8200 /* Insert the new header name in the array in the top of the stack.
8201 * It left the new array in the top of the stack.
8202 */
8203 lua_newtable(L);
8204 lua_pushstring(L, name);
8205 lua_pushvalue(L, -2);
8206 lua_settable(L, -4);
8207 }
8208 else if (ret != LUA_TTABLE) {
8209 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8210 WILL_LJMP(lua_error(L));
8211 }
8212
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008213 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008214 * the header value as new entry.
8215 */
8216 lua_pushstring(L, value);
8217 ret = lua_rawlen(L, -2);
8218 lua_rawseti(L, -2, ret + 1);
8219
8220 lua_pushboolean(L, 1);
8221 return 1;
8222}
8223
8224/* Remove all occurrences of a given header name. */
8225__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8226{
8227 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8228 int ret;
8229
8230 /* First argument (self) must be a table */
8231 luaL_checktype(L, 1, LUA_TTABLE);
8232
8233 /* Push in the stack the "headers" entry. */
8234 ret = lua_getfield(L, 1, "headers");
8235 if (ret != LUA_TTABLE) {
8236 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8237 WILL_LJMP(lua_error(L));
8238 }
8239
8240 lua_pushstring(L, name);
8241 lua_pushnil(L);
8242 lua_settable(L, -3);
8243
8244 lua_pushboolean(L, 1);
8245 return 1;
8246}
8247
8248/* Set the reply's body. Overwrite any existing entry. */
8249__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8250{
8251 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8252
8253 /* First argument (self) must be a table */
8254 luaL_checktype(L, 1, LUA_TTABLE);
8255
8256 lua_pushstring(L, payload);
8257 lua_setfield(L, 1, "body");
8258
8259 lua_pushboolean(L, 1);
8260 return 1;
8261}
8262
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008263__LJMP static int hlua_log(lua_State *L)
8264{
8265 int level;
8266 const char *msg;
8267
8268 MAY_LJMP(check_args(L, 2, "log"));
8269 level = MAY_LJMP(luaL_checkinteger(L, 1));
8270 msg = MAY_LJMP(luaL_checkstring(L, 2));
8271
8272 if (level < 0 || level >= NB_LOG_LEVELS)
8273 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8274
8275 hlua_sendlog(NULL, level, msg);
8276 return 0;
8277}
8278
8279__LJMP static int hlua_log_debug(lua_State *L)
8280{
8281 const char *msg;
8282
8283 MAY_LJMP(check_args(L, 1, "debug"));
8284 msg = MAY_LJMP(luaL_checkstring(L, 1));
8285 hlua_sendlog(NULL, LOG_DEBUG, msg);
8286 return 0;
8287}
8288
8289__LJMP static int hlua_log_info(lua_State *L)
8290{
8291 const char *msg;
8292
8293 MAY_LJMP(check_args(L, 1, "info"));
8294 msg = MAY_LJMP(luaL_checkstring(L, 1));
8295 hlua_sendlog(NULL, LOG_INFO, msg);
8296 return 0;
8297}
8298
8299__LJMP static int hlua_log_warning(lua_State *L)
8300{
8301 const char *msg;
8302
8303 MAY_LJMP(check_args(L, 1, "warning"));
8304 msg = MAY_LJMP(luaL_checkstring(L, 1));
8305 hlua_sendlog(NULL, LOG_WARNING, msg);
8306 return 0;
8307}
8308
8309__LJMP static int hlua_log_alert(lua_State *L)
8310{
8311 const char *msg;
8312
8313 MAY_LJMP(check_args(L, 1, "alert"));
8314 msg = MAY_LJMP(luaL_checkstring(L, 1));
8315 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008316 return 0;
8317}
8318
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008319__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008320{
8321 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008322 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008323 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008324 return 0;
8325}
8326
8327__LJMP static int hlua_sleep(lua_State *L)
8328{
8329 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008330 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008331
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008332 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008333
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008334 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008335 wakeup_ms = tick_add(now_ms, delay);
8336 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008337
Willy Tarreau9635e032018-10-16 17:52:55 +02008338 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008339 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008340}
8341
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008342__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008343{
8344 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008345 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008346
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008347 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008348
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008349 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008350 wakeup_ms = tick_add(now_ms, delay);
8351 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008352
Willy Tarreau9635e032018-10-16 17:52:55 +02008353 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008354 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008355}
8356
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008357/* This functionis an LUA binding. it permits to give back
8358 * the hand at the HAProxy scheduler. It is used when the
8359 * LUA processing consumes a lot of time.
8360 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008361__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008362{
8363 return 0;
8364}
8365
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008366__LJMP static int hlua_yield(lua_State *L)
8367{
Willy Tarreau9635e032018-10-16 17:52:55 +02008368 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008369 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008370}
8371
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008372/* This function change the nice of the currently executed
8373 * task. It is used set low or high priority at the current
8374 * task.
8375 */
Willy Tarreau59551662015-03-10 14:23:13 +01008376__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008377{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008378 struct hlua *hlua;
8379 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008380
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008381 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008382 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008383
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008384 /* Get hlua struct, or NULL if we execute from main lua state */
8385 hlua = hlua_gethlua(L);
8386
8387 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008388 if (!hlua || !hlua->task)
8389 return 0;
8390
8391 if (nice < -1024)
8392 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008393 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008394 nice = 1024;
8395
8396 hlua->task->nice = nice;
8397 return 0;
8398}
8399
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008400/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008401 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8402 * return an E_AGAIN signal, the emmiter of this signal must set a
8403 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008404 *
8405 * Task wrapper are longjmp safe because the only one Lua code
8406 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008407 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008408struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008409{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008410 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008411 enum hlua_exec status;
8412
Christopher Faulet5bc99722018-04-25 10:34:45 +02008413 if (task->thread_mask == MAX_THREADS_MASK)
8414 task_set_affinity(task, tid_bit);
8415
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008416 /* If it is the first call to the task, we must initialize the
8417 * execution timeouts.
8418 */
8419 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008420 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008421
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008422 /* Execute the Lua code. */
8423 status = hlua_ctx_resume(hlua, 1);
8424
8425 switch (status) {
8426 /* finished or yield */
8427 case HLUA_E_OK:
8428 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008429 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008430 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008431 break;
8432
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008433 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008434 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008435 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008436 break;
8437
8438 /* finished with error. */
8439 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008440 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008441 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008442 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008443 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008444 break;
8445
8446 case HLUA_E_ERR:
8447 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008448 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008449 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008450 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008451 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008452 break;
8453 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008454 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008455}
8456
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008457/* This function is an LUA binding that register LUA function to be
8458 * executed after the HAProxy configuration parsing and before the
8459 * HAProxy scheduler starts. This function expect only one LUA
8460 * argument that is a function. This function returns nothing, but
8461 * throws if an error is encountered.
8462 */
8463__LJMP static int hlua_register_init(lua_State *L)
8464{
8465 struct hlua_init_function *init;
8466 int ref;
8467
8468 MAY_LJMP(check_args(L, 1, "register_init"));
8469
8470 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8471
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008472 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008473 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008474 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008475
8476 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008477 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008478 return 0;
8479}
8480
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008481/* This functio is an LUA binding. It permits to register a task
8482 * executed in parallel of the main HAroxy activity. The task is
8483 * created and it is set in the HAProxy scheduler. It can be called
8484 * from the "init" section, "post init" or during the runtime.
8485 *
8486 * Lua prototype:
8487 *
8488 * <none> core.register_task(<function>)
8489 */
8490static int hlua_register_task(lua_State *L)
8491{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008492 struct hlua *hlua = NULL;
8493 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008494 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008495 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008496
8497 MAY_LJMP(check_args(L, 1, "register_task"));
8498
8499 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8500
Thierry Fournier75fc0292020-11-28 13:18:56 +01008501 /* Get the reference state. If the reference is NULL, L is the master
8502 * state, otherwise hlua->T is.
8503 */
8504 hlua = hlua_gethlua(L);
8505 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008506 /* we are in runtime processing */
8507 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008508 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008509 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008510 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008511
Willy Tarreaubafbe012017-11-24 17:34:44 +01008512 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008513 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008514 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008515 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008516
Thierry Fournier59f11be2020-11-29 00:37:41 +01008517 /* We are in the common lua state, execute the task anywhere,
8518 * otherwise, inherit the current thread identifier
8519 */
8520 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008521 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008522 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008523 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008524 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008525 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008526
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008527 task->context = hlua;
8528 task->process = hlua_process_task;
8529
Thierry Fournier021d9862020-11-28 23:42:03 +01008530 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008531 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008532
8533 /* Restore the function in the stack. */
8534 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8535 hlua->nargs = 0;
8536
8537 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008538 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008539
8540 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008541
8542 alloc_error:
8543 task_destroy(task);
8544 hlua_ctx_destroy(hlua);
8545 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8546 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008547}
8548
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008549/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8550 * doesn't allow "yield" functions because the HAProxy engine cannot
8551 * resume converters.
8552 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008553static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008554{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008555 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008556 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008557 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008558
Willy Tarreaube508f12016-03-10 11:47:01 +01008559 if (!stream)
8560 return 0;
8561
Willy Tarreau87b09662015-04-03 00:22:06 +02008562 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008563 * Lua context can be not initialized. This behavior
8564 * permits to save performances because a systematic
8565 * Lua initialization cause 5% performances loss.
8566 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008567 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008568 struct hlua *hlua;
8569
8570 hlua = pool_alloc(pool_head_hlua);
8571 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008572 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8573 return 0;
8574 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008575 HLUA_INIT(hlua);
8576 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008577 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008578 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8579 return 0;
8580 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008581 }
8582
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008583 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008584 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008585
8586 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008587 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008588 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8589 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008590 else
8591 error = "critical error";
8592 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008593 return 0;
8594 }
8595
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008596 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008597 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008598 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008599 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008600 return 0;
8601 }
8602
8603 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008604 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008605
8606 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008607 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008608 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008609 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008610 return 0;
8611 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008612 hlua_smp2lua(stream->hlua->T, smp);
8613 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008614
8615 /* push keywords in the stack. */
8616 if (arg_p) {
8617 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008618 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008619 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008620 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008621 return 0;
8622 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008623 hlua_arg2lua(stream->hlua->T, arg_p);
8624 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008625 }
8626 }
8627
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008628 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008629 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008630
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008631 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008632 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008633 }
8634
8635 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008636 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008637 /* finished. */
8638 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008639 /* If the stack is empty, the function fails. */
8640 if (lua_gettop(stream->hlua->T) <= 0)
8641 return 0;
8642
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008643 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008644 hlua_lua2smp(stream->hlua->T, -1, smp);
8645 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008646 return 1;
8647
8648 /* yield. */
8649 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008650 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008651 return 0;
8652
8653 /* finished with error. */
8654 case HLUA_E_ERRMSG:
8655 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008656 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008657 fcn->name, lua_tostring(stream->hlua->T, -1));
8658 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008659 return 0;
8660
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008661 case HLUA_E_ETMOUT:
8662 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8663 return 0;
8664
8665 case HLUA_E_NOMEM:
8666 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8667 return 0;
8668
8669 case HLUA_E_YIELD:
8670 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8671 return 0;
8672
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008673 case HLUA_E_ERR:
8674 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008675 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008676 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008677
8678 default:
8679 return 0;
8680 }
8681}
8682
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008683/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8684 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008685 * resume sample-fetches. This function will be called by the sample
8686 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008687 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008688static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8689 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008690{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008691 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008692 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008693 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008694 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008695
Willy Tarreaube508f12016-03-10 11:47:01 +01008696 if (!stream)
8697 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008698
Willy Tarreau87b09662015-04-03 00:22:06 +02008699 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008700 * Lua context can be not initialized. This behavior
8701 * permits to save performances because a systematic
8702 * Lua initialization cause 5% performances loss.
8703 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008704 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008705 struct hlua *hlua;
8706
8707 hlua = pool_alloc(pool_head_hlua);
8708 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008709 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8710 return 0;
8711 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008712 hlua->T = NULL;
8713 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008714 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008715 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8716 return 0;
8717 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008718 }
8719
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008720 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008721 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008722
8723 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008724 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008725 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8726 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008727 else
8728 error = "critical error";
8729 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008730 return 0;
8731 }
8732
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008733 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008734 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008735 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008736 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008737 return 0;
8738 }
8739
8740 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008741 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008742
8743 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008744 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008745 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008746 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008747 return 0;
8748 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008749 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008750
8751 /* push keywords in the stack. */
8752 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8753 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008754 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008755 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008756 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008757 return 0;
8758 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008759 hlua_arg2lua(stream->hlua->T, arg_p);
8760 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008761 }
8762
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008763 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008764 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008765
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008766 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008767 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008768 }
8769
8770 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008771 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008772 /* finished. */
8773 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008774 /* If the stack is empty, the function fails. */
8775 if (lua_gettop(stream->hlua->T) <= 0)
8776 return 0;
8777
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008778 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008779 hlua_lua2smp(stream->hlua->T, -1, smp);
8780 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008781
8782 /* Set the end of execution flag. */
8783 smp->flags &= ~SMP_F_MAY_CHANGE;
8784 return 1;
8785
8786 /* yield. */
8787 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008788 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008789 return 0;
8790
8791 /* finished with error. */
8792 case HLUA_E_ERRMSG:
8793 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008794 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008795 fcn->name, lua_tostring(stream->hlua->T, -1));
8796 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008797 return 0;
8798
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008799 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008800 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8801 return 0;
8802
8803 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008804 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8805 return 0;
8806
8807 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008808 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8809 return 0;
8810
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008811 case HLUA_E_ERR:
8812 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008813 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008814 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008815
8816 default:
8817 return 0;
8818 }
8819}
8820
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008821/* This function is an LUA binding used for registering
8822 * "sample-conv" functions. It expects a converter name used
8823 * in the haproxy configuration file, and an LUA function.
8824 */
8825__LJMP static int hlua_register_converters(lua_State *L)
8826{
8827 struct sample_conv_kw_list *sck;
8828 const char *name;
8829 int ref;
8830 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008831 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008832 struct sample_conv *sc;
8833 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008834
8835 MAY_LJMP(check_args(L, 2, "register_converters"));
8836
8837 /* First argument : converter name. */
8838 name = MAY_LJMP(luaL_checkstring(L, 1));
8839
8840 /* Second argument : lua function. */
8841 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8842
Thierry Fournierf67442e2020-11-28 20:41:07 +01008843 /* Check if the converter is already registered */
8844 trash = get_trash_chunk();
8845 chunk_printf(trash, "lua.%s", name);
8846 sc = find_sample_conv(trash->area, trash->data);
8847 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008848 fcn = sc->private;
8849 if (fcn->function_ref[hlua_state_id] != -1) {
8850 ha_warning("Trying to register converter 'lua.%s' more than once. "
8851 "This will become a hard error in version 2.5.\n", name);
8852 }
8853 fcn->function_ref[hlua_state_id] = ref;
8854 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008855 }
8856
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008857 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008858 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008859 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008860 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008861 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008862 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008863 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008864
8865 /* Fill fcn. */
8866 fcn->name = strdup(name);
8867 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008868 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008869 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008870
8871 /* List head */
8872 sck->list.n = sck->list.p = NULL;
8873
8874 /* converter keyword. */
8875 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008876 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008877 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008878 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008879
8880 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8881 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008882 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 +01008883 sck->kw[0].val_args = NULL;
8884 sck->kw[0].in_type = SMP_T_STR;
8885 sck->kw[0].out_type = SMP_T_STR;
8886 sck->kw[0].private = fcn;
8887
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008888 /* Register this new converter */
8889 sample_register_convs(sck);
8890
8891 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008892
8893 alloc_error:
8894 release_hlua_function(fcn);
8895 ha_free(&sck);
8896 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8897 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008898}
8899
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008900/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008901 * "sample-fetch" functions. It expects a converter name used
8902 * in the haproxy configuration file, and an LUA function.
8903 */
8904__LJMP static int hlua_register_fetches(lua_State *L)
8905{
8906 const char *name;
8907 int ref;
8908 int len;
8909 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008910 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008911 struct sample_fetch *sf;
8912 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008913
8914 MAY_LJMP(check_args(L, 2, "register_fetches"));
8915
8916 /* First argument : sample-fetch name. */
8917 name = MAY_LJMP(luaL_checkstring(L, 1));
8918
8919 /* Second argument : lua function. */
8920 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8921
Thierry Fournierf67442e2020-11-28 20:41:07 +01008922 /* Check if the sample-fetch is already registered */
8923 trash = get_trash_chunk();
8924 chunk_printf(trash, "lua.%s", name);
8925 sf = find_sample_fetch(trash->area, trash->data);
8926 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008927 fcn = sf->private;
8928 if (fcn->function_ref[hlua_state_id] != -1) {
8929 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8930 "This will become a hard error in version 2.5.\n", name);
8931 }
8932 fcn->function_ref[hlua_state_id] = ref;
8933 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008934 }
8935
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008936 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008937 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008938 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008939 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008940 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008941 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008942 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008943
8944 /* Fill fcn. */
8945 fcn->name = strdup(name);
8946 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008947 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008948 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008949
8950 /* List head */
8951 sfk->list.n = sfk->list.p = NULL;
8952
8953 /* sample-fetch keyword. */
8954 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008955 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008956 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008957 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008958
8959 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8960 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008961 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 +01008962 sfk->kw[0].val_args = NULL;
8963 sfk->kw[0].out_type = SMP_T_STR;
8964 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8965 sfk->kw[0].val = 0;
8966 sfk->kw[0].private = fcn;
8967
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008968 /* Register this new fetch. */
8969 sample_register_fetches(sfk);
8970
8971 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008972
8973 alloc_error:
8974 release_hlua_function(fcn);
8975 ha_free(&sfk);
8976 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8977 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008978}
8979
Christopher Faulet501465d2020-02-26 14:54:16 +01008980/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008981 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008982__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008983{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008984 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008985 unsigned int delay;
8986 unsigned int wakeup_ms;
8987
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008988 /* Get hlua struct, or NULL if we execute from main lua state */
8989 hlua = hlua_gethlua(L);
8990 if (!hlua) {
8991 return 0;
8992 }
8993
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008994 MAY_LJMP(check_args(L, 1, "wake_time"));
8995
8996 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8997 wakeup_ms = tick_add(now_ms, delay);
8998 hlua->wake_time = wakeup_ms;
8999 return 0;
9000}
9001
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009002/* This function is a wrapper to execute each LUA function declared as an action
9003 * wrapper during the initialisation period. This function may return any
9004 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9005 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9006 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009007 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009008static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009009 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009010{
9011 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009012 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009013 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009014 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009015
9016 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009017 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9018 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9019 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9020 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009021 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009022 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009023 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009024 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009025
Willy Tarreau87b09662015-04-03 00:22:06 +02009026 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009027 * Lua context can be not initialized. This behavior
9028 * permits to save performances because a systematic
9029 * Lua initialization cause 5% performances loss.
9030 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009031 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009032 struct hlua *hlua;
9033
9034 hlua = pool_alloc(pool_head_hlua);
9035 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009036 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009037 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009038 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009039 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009040 HLUA_INIT(hlua);
9041 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009042 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 +01009043 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009044 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009045 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009046 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009047 }
9048
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009049 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009050 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009051
9052 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009053 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009054 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9055 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009056 else
9057 error = "critical error";
9058 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009059 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009060 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009061 }
9062
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009063 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009064 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009065 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009066 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009067 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009068 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009069 }
9070
9071 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009072 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 +01009073
Willy Tarreau87b09662015-04-03 00:22:06 +02009074 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009075 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009076 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009077 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009078 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009079 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009080 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009081 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009082
9083 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009084 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009085 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009086 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009087 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009088 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009089 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009090 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009091 lua_pushstring(s->hlua->T, *arg);
9092 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009093 }
9094
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009095 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009096 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009097
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009098 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009099 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009100 }
9101
9102 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009103 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009104 /* finished. */
9105 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009106 /* Catch the return value */
9107 if (lua_gettop(s->hlua->T) > 0)
9108 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009109
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009110 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009111 if (act_ret == ACT_RET_YIELD) {
9112 if (flags & ACT_OPT_FINAL)
9113 goto err_yield;
9114
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009115 if (dir == SMP_OPT_DIR_REQ)
9116 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9117 s->hlua->wake_time);
9118 else
9119 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9120 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009121 }
9122 goto end;
9123
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009124 /* yield. */
9125 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009126 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009127 if (dir == SMP_OPT_DIR_REQ)
9128 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9129 s->hlua->wake_time);
9130 else
9131 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9132 s->hlua->wake_time);
9133
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009134 /* Some actions can be wake up when a "write" event
9135 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009136 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009137 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009138 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009139 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009140 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009141 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009142 act_ret = ACT_RET_YIELD;
9143 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009144
9145 /* finished with error. */
9146 case HLUA_E_ERRMSG:
9147 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009148 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009149 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009150 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009151 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009152
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009153 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009154 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009155 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009156
9157 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009158 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009159 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009160
9161 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009162 err_yield:
9163 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009164 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009165 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009166 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009167
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009168 case HLUA_E_ERR:
9169 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009170 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009171 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009172
9173 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009174 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009175 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009176
9177 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009178 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009179 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009180 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009181}
9182
Willy Tarreau144f84a2021-03-02 16:09:26 +01009183struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009184{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009185 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009186
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009187 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009188 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009189 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009190}
9191
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009192static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009193{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009194 struct stream_interface *si = cs_si(ctx->owner);
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009195 struct stream *strm = si_strm(si);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009196 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009197 struct task *task;
9198 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009199 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009200
Willy Tarreaubafbe012017-11-24 17:34:44 +01009201 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009202 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009203 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009204 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009205 return 0;
9206 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009207 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009208 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009209 ctx->ctx.hlua_apptcp.flags = 0;
9210
9211 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009212 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009213 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009214 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009215 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009216 return 0;
9217 }
9218 task->nice = 0;
9219 task->context = ctx;
9220 task->process = hlua_applet_wakeup;
9221 ctx->ctx.hlua_apptcp.task = task;
9222
9223 /* In the execution wrappers linked with a stream, the
9224 * Lua context can be not initialized. This behavior
9225 * permits to save performances because a systematic
9226 * Lua initialization cause 5% performances loss.
9227 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009228 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 +01009229 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009230 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009231 return 0;
9232 }
9233
9234 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009235 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009236
9237 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009238 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009239 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9240 error = lua_tostring(hlua->T, -1);
9241 else
9242 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009243 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009244 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009245 return 0;
9246 }
9247
9248 /* Check stack available size. */
9249 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009250 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009251 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009252 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009253 return 0;
9254 }
9255
9256 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009257 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009258
9259 /* Create and and push object stream in the stack. */
9260 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009261 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009262 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009263 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009264 return 0;
9265 }
9266 hlua->nargs = 1;
9267
9268 /* push keywords in the stack. */
9269 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9270 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009271 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009272 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009273 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009274 return 0;
9275 }
9276 lua_pushstring(hlua->T, *arg);
9277 hlua->nargs++;
9278 }
9279
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009280 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009281
9282 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009283 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01009284 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009285
9286 return 1;
9287}
9288
Willy Tarreau60409db2019-08-21 14:14:50 +02009289void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009290{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009291 struct stream_interface *si = cs_si(ctx->owner);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009292 struct stream *strm = si_strm(si);
9293 struct channel *res = si_ic(si);
9294 struct act_rule *rule = ctx->rule;
9295 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009296 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009297
9298 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02009299 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
9300 /* eat the whole request */
9301 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009302 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009303 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009304
9305 /* If the stream is disconnect or closed, ldo nothing. */
9306 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9307 return;
9308
9309 /* Execute the function. */
9310 switch (hlua_ctx_resume(hlua, 1)) {
9311 /* finished. */
9312 case HLUA_E_OK:
9313 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9314
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009315 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02009316 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009317 res->flags |= CF_READ_NULL;
9318 si_shutr(si);
9319 return;
9320
9321 /* yield. */
9322 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009323 if (hlua->wake_time != TICK_ETERNITY)
9324 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009325 return;
9326
9327 /* finished with error. */
9328 case HLUA_E_ERRMSG:
9329 /* Display log. */
9330 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009331 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009332 lua_pop(hlua->T, 1);
9333 goto error;
9334
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009335 case HLUA_E_ETMOUT:
9336 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009337 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009338 goto error;
9339
9340 case HLUA_E_NOMEM:
9341 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009342 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009343 goto error;
9344
9345 case HLUA_E_YIELD: /* unexpected */
9346 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009347 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009348 goto error;
9349
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009350 case HLUA_E_ERR:
9351 /* Display log. */
9352 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009353 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009354 goto error;
9355
9356 default:
9357 goto error;
9358 }
9359
9360error:
9361
9362 /* For all other cases, just close the stream. */
9363 si_shutw(si);
9364 si_shutr(si);
9365 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9366}
9367
9368static void hlua_applet_tcp_release(struct appctx *ctx)
9369{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009370 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009371 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009372 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009373 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009374}
9375
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009376/* The function returns 1 if the initialisation is complete, 0 if
9377 * an errors occurs and -1 if more data are required for initializing
9378 * the applet.
9379 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009380static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009381{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009382 struct stream_interface *si = cs_si(ctx->owner);
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009383 struct stream *strm = si_strm(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009384 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009385 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009386 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009387 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009388 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009389
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009390 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009391 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009392 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009393 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009394 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009395 return 0;
9396 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009397 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009398 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009399 ctx->ctx.hlua_apphttp.left_bytes = -1;
9400 ctx->ctx.hlua_apphttp.flags = 0;
9401
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009402 if (txn->req.flags & HTTP_MSGF_VER_11)
9403 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
9404
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009405 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009406 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009407 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009408 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009409 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009410 return 0;
9411 }
9412 task->nice = 0;
9413 task->context = ctx;
9414 task->process = hlua_applet_wakeup;
9415 ctx->ctx.hlua_apphttp.task = task;
9416
9417 /* In the execution wrappers linked with a stream, the
9418 * Lua context can be not initialized. This behavior
9419 * permits to save performances because a systematic
9420 * Lua initialization cause 5% performances loss.
9421 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009422 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 +01009423 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009424 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009425 return 0;
9426 }
9427
9428 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009429 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009430
9431 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009432 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009433 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9434 error = lua_tostring(hlua->T, -1);
9435 else
9436 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009437 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009438 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009439 return 0;
9440 }
9441
9442 /* Check stack available size. */
9443 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009444 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009445 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009446 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009447 return 0;
9448 }
9449
9450 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009451 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009452
9453 /* Create and and push object stream in the stack. */
9454 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009455 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009456 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009457 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009458 return 0;
9459 }
9460 hlua->nargs = 1;
9461
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009462 /* push keywords in the stack. */
9463 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9464 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009465 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009466 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009467 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009468 return 0;
9469 }
9470 lua_pushstring(hlua->T, *arg);
9471 hlua->nargs++;
9472 }
9473
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009474 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009475
9476 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009477 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009478
9479 return 1;
9480}
9481
Willy Tarreau60409db2019-08-21 14:14:50 +02009482void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009483{
Christopher Faulet86e1c332021-12-20 17:09:39 +01009484 struct stream_interface *si = cs_si(ctx->owner);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009485 struct stream *strm = si_strm(si);
9486 struct channel *req = si_oc(si);
9487 struct channel *res = si_ic(si);
9488 struct act_rule *rule = ctx->rule;
9489 struct proxy *px = strm->be;
9490 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
9491 struct htx *req_htx, *res_htx;
9492
9493 res_htx = htx_from_buf(&res->buf);
9494
9495 /* If the stream is disconnect or closed, ldo nothing. */
9496 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9497 goto out;
9498
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009499 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009500 if (!b_size(&res->buf)) {
9501 si_rx_room_blk(si);
9502 goto out;
9503 }
9504 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009505 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009506 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9507
9508 /* Set the currently running flag. */
9509 if (!HLUA_IS_RUNNING(hlua) &&
9510 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009511 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009512 si_cant_get(si);
9513 goto out;
9514 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009515 }
9516
9517 /* Executes The applet if it is not done. */
9518 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9519
9520 /* Execute the function. */
9521 switch (hlua_ctx_resume(hlua, 1)) {
9522 /* finished. */
9523 case HLUA_E_OK:
9524 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9525 break;
9526
9527 /* yield. */
9528 case HLUA_E_AGAIN:
9529 if (hlua->wake_time != TICK_ETERNITY)
9530 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009531 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009532
9533 /* finished with error. */
9534 case HLUA_E_ERRMSG:
9535 /* Display log. */
9536 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009537 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009538 lua_pop(hlua->T, 1);
9539 goto error;
9540
9541 case HLUA_E_ETMOUT:
9542 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009543 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009544 goto error;
9545
9546 case HLUA_E_NOMEM:
9547 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009548 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009549 goto error;
9550
9551 case HLUA_E_YIELD: /* unexpected */
9552 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009553 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009554 goto error;
9555
9556 case HLUA_E_ERR:
9557 /* Display log. */
9558 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009559 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009560 goto error;
9561
9562 default:
9563 goto error;
9564 }
9565 }
9566
9567 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009568 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9569 goto done;
9570
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009571 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9572 goto error;
9573
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009574 /* no more data are expected. If the response buffer is empty
9575 * for a chunked message, be sure to add something (EOT block in
9576 * this case) to have something to send. It is important to be
9577 * sure the EOM flags will be handled by the endpoint.
9578 */
9579 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9580 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
9581 si_rx_room_blk(si);
9582 goto out;
9583 }
9584 channel_add_input(res, 1);
9585 }
9586
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009587 res_htx->flags |= HTX_FL_EOM;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009588 si->cs->flags |= CS_FL_EOI;
9589 res->flags |= CF_EOI;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009590 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9591 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009592 }
9593
9594 done:
9595 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009596 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009597 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009598 si_shutr(si);
9599 }
9600
9601 /* eat the whole request */
9602 if (co_data(req)) {
9603 req_htx = htx_from_buf(&req->buf);
9604 co_htx_skip(req, req_htx, co_data(req));
9605 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009606 }
9607 }
9608
9609 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009610 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009611 return;
9612
9613 error:
9614
9615 /* If we are in HTTP mode, and we are not send any
9616 * data, return a 500 server error in best effort:
9617 * if there is no room available in the buffer,
9618 * just close the connection.
9619 */
9620 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009621 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009622
9623 channel_erase(res);
9624 res->buf.data = b_data(err);
9625 memcpy(res->buf.area, b_head(err), b_data(err));
9626 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009627 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009628 }
9629 if (!(strm->flags & SF_ERR_MASK))
9630 strm->flags |= SF_ERR_RESOURCE;
9631 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9632 goto done;
9633}
9634
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009635static void hlua_applet_http_release(struct appctx *ctx)
9636{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009637 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009638 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009639 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009640 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009641}
9642
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009643/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009644 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009645 *
9646 * This function can fail with an abort() due to an Lua critical error.
9647 * We are in the configuration parsing process of HAProxy, this abort() is
9648 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009649 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009650static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9651 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009652{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009653 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009654 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009655
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009656 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009657 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009658 if (!rule->arg.hlua_rule) {
9659 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009660 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009661 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009662
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009663 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009664 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9665 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009666 if (!rule->arg.hlua_rule->args) {
9667 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009668 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009669 }
9670
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009671 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009672 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009673
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009674 /* Expect some arguments */
9675 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009676 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009677 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009678 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009679 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009680 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009681 if (!rule->arg.hlua_rule->args[i]) {
9682 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009683 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009684 }
9685 (*cur_arg)++;
9686 }
9687 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009688
Thierry FOURNIER42148732015-09-02 17:17:33 +02009689 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009690 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009691 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009692
9693 error:
9694 if (rule->arg.hlua_rule) {
9695 if (rule->arg.hlua_rule->args) {
9696 for (i = 0; i < fcn->nargs; i++)
9697 ha_free(&rule->arg.hlua_rule->args[i]);
9698 ha_free(&rule->arg.hlua_rule->args);
9699 }
9700 ha_free(&rule->arg.hlua_rule);
9701 }
9702 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009703}
9704
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009705static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9706 struct act_rule *rule, char **err)
9707{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009708 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009709
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009710 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009711 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009712 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009713 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009714 * the call of this analyzer.
9715 */
9716 if (rule->from != ACT_F_HTTP_REQ) {
9717 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9718 return ACT_RET_PRS_ERR;
9719 }
9720
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009721 /* Memory for the rule. */
9722 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9723 if (!rule->arg.hlua_rule) {
9724 memprintf(err, "out of memory error");
9725 return ACT_RET_PRS_ERR;
9726 }
9727
9728 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009729 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009730
9731 /* TODO: later accept arguments. */
9732 rule->arg.hlua_rule->args = NULL;
9733
9734 /* Add applet pointer in the rule. */
9735 rule->applet.obj_type = OBJ_TYPE_APPLET;
9736 rule->applet.name = fcn->name;
9737 rule->applet.init = hlua_applet_http_init;
9738 rule->applet.fct = hlua_applet_http_fct;
9739 rule->applet.release = hlua_applet_http_release;
9740 rule->applet.timeout = hlua_timeout_applet;
9741
9742 return ACT_RET_PRS_OK;
9743}
9744
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009745/* This function is an LUA binding used for registering
9746 * "sample-conv" functions. It expects a converter name used
9747 * in the haproxy configuration file, and an LUA function.
9748 */
9749__LJMP static int hlua_register_action(lua_State *L)
9750{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009751 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009752 const char *name;
9753 int ref;
9754 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009755 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009756 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009757 struct buffer *trash;
9758 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009759
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009760 /* Initialise the number of expected arguments at 0. */
9761 nargs = 0;
9762
9763 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9764 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009765
9766 /* First argument : converter name. */
9767 name = MAY_LJMP(luaL_checkstring(L, 1));
9768
9769 /* Second argument : environment. */
9770 if (lua_type(L, 2) != LUA_TTABLE)
9771 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9772
9773 /* Third argument : lua function. */
9774 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9775
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009776 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009777 if (lua_gettop(L) >= 4)
9778 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9779
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009780 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009781 lua_pushnil(L);
9782 while (lua_next(L, 2) != 0) {
9783 if (lua_type(L, -1) != LUA_TSTRING)
9784 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9785
Thierry Fournierf67442e2020-11-28 20:41:07 +01009786 /* Check if action exists */
9787 trash = get_trash_chunk();
9788 chunk_printf(trash, "lua.%s", name);
9789 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9790 akw = tcp_req_cont_action(trash->area);
9791 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9792 akw = tcp_res_cont_action(trash->area);
9793 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9794 akw = action_http_req_custom(trash->area);
9795 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9796 akw = action_http_res_custom(trash->area);
9797 } else {
9798 akw = NULL;
9799 }
9800 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009801 fcn = akw->private;
9802 if (fcn->function_ref[hlua_state_id] != -1) {
9803 ha_warning("Trying to register action 'lua.%s' more than once. "
9804 "This will become a hard error in version 2.5.\n", name);
9805 }
9806 fcn->function_ref[hlua_state_id] = ref;
9807
9808 /* pop the environment string. */
9809 lua_pop(L, 1);
9810 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009811 }
9812
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009813 /* Check required environment. Only accepted "http" or "tcp". */
9814 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009815 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009816 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009817 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009818 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009819 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009820 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009821
9822 /* Fill fcn. */
9823 fcn->name = strdup(name);
9824 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009825 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009826 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009827
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009828 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009829 fcn->nargs = nargs;
9830
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009831 /* List head */
9832 akl->list.n = akl->list.p = NULL;
9833
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009834 /* action keyword. */
9835 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009836 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009837 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009838 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009839
9840 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9841
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009842 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009843 akl->kw[0].private = fcn;
9844 akl->kw[0].parse = action_register_lua;
9845
9846 /* select the action registering point. */
9847 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9848 tcp_req_cont_keywords_register(akl);
9849 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9850 tcp_res_cont_keywords_register(akl);
9851 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9852 http_req_keywords_register(akl);
9853 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9854 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009855 else {
9856 release_hlua_function(fcn);
9857 if (akl)
9858 ha_free((char **)&(akl->kw[0].kw));
9859 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009860 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009861 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9862 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009863 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009864
9865 /* pop the environment string. */
9866 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009867
9868 /* reset for next loop */
9869 akl = NULL;
9870 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009871 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009872 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009873
9874 alloc_error:
9875 release_hlua_function(fcn);
9876 ha_free(&akl);
9877 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9878 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009879}
9880
9881static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9882 struct act_rule *rule, char **err)
9883{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009884 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009885
Christopher Faulet280f85b2019-07-15 15:02:04 +02009886 if (px->mode == PR_MODE_HTTP) {
9887 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009888 return ACT_RET_PRS_ERR;
9889 }
9890
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009891 /* Memory for the rule. */
9892 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9893 if (!rule->arg.hlua_rule) {
9894 memprintf(err, "out of memory error");
9895 return ACT_RET_PRS_ERR;
9896 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009897
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009898 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009899 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009900
9901 /* TODO: later accept arguments. */
9902 rule->arg.hlua_rule->args = NULL;
9903
9904 /* Add applet pointer in the rule. */
9905 rule->applet.obj_type = OBJ_TYPE_APPLET;
9906 rule->applet.name = fcn->name;
9907 rule->applet.init = hlua_applet_tcp_init;
9908 rule->applet.fct = hlua_applet_tcp_fct;
9909 rule->applet.release = hlua_applet_tcp_release;
9910 rule->applet.timeout = hlua_timeout_applet;
9911
9912 return 0;
9913}
9914
9915/* This function is an LUA binding used for registering
9916 * "sample-conv" functions. It expects a converter name used
9917 * in the haproxy configuration file, and an LUA function.
9918 */
9919__LJMP static int hlua_register_service(lua_State *L)
9920{
9921 struct action_kw_list *akl;
9922 const char *name;
9923 const char *env;
9924 int ref;
9925 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009926 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009927 struct buffer *trash;
9928 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009929
9930 MAY_LJMP(check_args(L, 3, "register_service"));
9931
9932 /* First argument : converter name. */
9933 name = MAY_LJMP(luaL_checkstring(L, 1));
9934
9935 /* Second argument : environment. */
9936 env = MAY_LJMP(luaL_checkstring(L, 2));
9937
9938 /* Third argument : lua function. */
9939 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9940
Thierry Fournierf67442e2020-11-28 20:41:07 +01009941 /* Check for service already registered */
9942 trash = get_trash_chunk();
9943 chunk_printf(trash, "lua.%s", name);
9944 akw = service_find(trash->area);
9945 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009946 fcn = akw->private;
9947 if (fcn->function_ref[hlua_state_id] != -1) {
9948 ha_warning("Trying to register service 'lua.%s' more than once. "
9949 "This will become a hard error in version 2.5.\n", name);
9950 }
9951 fcn->function_ref[hlua_state_id] = ref;
9952 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009953 }
9954
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009955 /* Allocate and fill the sample fetch keyword struct. */
9956 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9957 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009958 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009959 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009960 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009961 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009962
9963 /* Fill fcn. */
9964 len = strlen("<lua.>") + strlen(name) + 1;
9965 fcn->name = calloc(1, len);
9966 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009967 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009968 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009969 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009970
9971 /* List head */
9972 akl->list.n = akl->list.p = NULL;
9973
9974 /* converter keyword. */
9975 len = strlen("lua.") + strlen(name) + 1;
9976 akl->kw[0].kw = calloc(1, len);
9977 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009978 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009979
9980 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9981
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009982 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009983 if (strcmp(env, "tcp") == 0)
9984 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009985 else if (strcmp(env, "http") == 0)
9986 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009987 else {
9988 release_hlua_function(fcn);
9989 if (akl)
9990 ha_free((char **)&(akl->kw[0].kw));
9991 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009992 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009993 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009994 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009995
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009996 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009997 akl->kw[0].private = fcn;
9998
9999 /* End of array. */
10000 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10001
10002 /* Register this new converter */
10003 service_keywords_register(akl);
10004
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010005 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010006
10007 alloc_error:
10008 release_hlua_function(fcn);
10009 ha_free(&akl);
10010 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10011 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010012}
10013
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010014/* This function initialises Lua cli handler. It copies the
10015 * arguments in the Lua stack and create channel IO objects.
10016 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010017static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010018{
10019 struct hlua *hlua;
10020 struct hlua_function *fcn;
10021 int i;
10022 const char *error;
10023
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010024 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010025 appctx->ctx.hlua_cli.fcn = private;
10026
Willy Tarreaubafbe012017-11-24 17:34:44 +010010027 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010028 if (!hlua) {
10029 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010030 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010031 }
10032 HLUA_INIT(hlua);
10033 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010034
10035 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010036 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010037 * applet_http. It is absolutely compatible.
10038 */
Willy Tarreaubeeabf52021-10-01 18:23:30 +020010039 appctx->ctx.hlua_cli.task = task_new_here();
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010040 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010041 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010042 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010043 }
10044 appctx->ctx.hlua_cli.task->nice = 0;
10045 appctx->ctx.hlua_cli.task->context = appctx;
10046 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
10047
10048 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +010010049 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 +010010050 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010051 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010052 }
10053
10054 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010055 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010056 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10057 error = lua_tostring(hlua->T, -1);
10058 else
10059 error = "critical error";
10060 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10061 goto error;
10062 }
10063
10064 /* Check stack available size. */
10065 if (!lua_checkstack(hlua->T, 2)) {
10066 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10067 goto error;
10068 }
10069
10070 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010071 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010072
10073 /* Once the arguments parsed, the CLI is like an AppletTCP,
10074 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010075 */
10076 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10077 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10078 goto error;
10079 }
10080 hlua->nargs = 1;
10081
10082 /* push keywords in the stack. */
10083 for (i = 0; *args[i]; i++) {
10084 /* Check stack available size. */
10085 if (!lua_checkstack(hlua->T, 1)) {
10086 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10087 goto error;
10088 }
10089 lua_pushstring(hlua->T, args[i]);
10090 hlua->nargs++;
10091 }
10092
10093 /* We must initialize the execution timeouts. */
10094 hlua->max_time = hlua_timeout_session;
10095
10096 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010097 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010098
10099 /* It's ok */
10100 return 0;
10101
10102 /* It's not ok. */
10103error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010104 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010105 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010106 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010107 return 1;
10108}
10109
10110static int hlua_cli_io_handler_fct(struct appctx *appctx)
10111{
10112 struct hlua *hlua;
10113 struct stream_interface *si;
10114 struct hlua_function *fcn;
10115
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010116 hlua = appctx->ctx.hlua_cli.hlua;
Christopher Faulet86e1c332021-12-20 17:09:39 +010010117 si = cs_si(appctx->owner);
Willy Tarreau8ae4f752016-12-14 15:41:45 +010010118 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010119
10120 /* If the stream is disconnect or closed, ldo nothing. */
10121 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
10122 return 1;
10123
10124 /* Execute the function. */
10125 switch (hlua_ctx_resume(hlua, 1)) {
10126
10127 /* finished. */
10128 case HLUA_E_OK:
10129 return 1;
10130
10131 /* yield. */
10132 case HLUA_E_AGAIN:
10133 /* We want write. */
10134 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +010010135 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010136 /* Set the timeout. */
10137 if (hlua->wake_time != TICK_ETERNITY)
10138 task_schedule(hlua->task, hlua->wake_time);
10139 return 0;
10140
10141 /* finished with error. */
10142 case HLUA_E_ERRMSG:
10143 /* Display log. */
10144 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10145 fcn->name, lua_tostring(hlua->T, -1));
10146 lua_pop(hlua->T, 1);
10147 return 1;
10148
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010149 case HLUA_E_ETMOUT:
10150 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10151 fcn->name);
10152 return 1;
10153
10154 case HLUA_E_NOMEM:
10155 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10156 fcn->name);
10157 return 1;
10158
10159 case HLUA_E_YIELD: /* unexpected */
10160 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10161 fcn->name);
10162 return 1;
10163
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010164 case HLUA_E_ERR:
10165 /* Display log. */
10166 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10167 fcn->name);
10168 return 1;
10169
10170 default:
10171 return 1;
10172 }
10173
10174 return 1;
10175}
10176
10177static void hlua_cli_io_release_fct(struct appctx *appctx)
10178{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010179 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010180 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010181}
10182
10183/* This function is an LUA binding used for registering
10184 * new keywords in the cli. It expects a list of keywords
10185 * which are the "path". It is limited to 5 keywords. A
10186 * description of the command, a function to be executed
10187 * for the parsing and a function for io handlers.
10188 */
10189__LJMP static int hlua_register_cli(lua_State *L)
10190{
10191 struct cli_kw_list *cli_kws;
10192 const char *message;
10193 int ref_io;
10194 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010195 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010196 int index;
10197 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010198 struct buffer *trash;
10199 const char *kw[5];
10200 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010201 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010202
10203 MAY_LJMP(check_args(L, 3, "register_cli"));
10204
10205 /* First argument : an array of maximum 5 keywords. */
10206 if (!lua_istable(L, 1))
10207 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10208
10209 /* Second argument : string with contextual message. */
10210 message = MAY_LJMP(luaL_checkstring(L, 2));
10211
10212 /* Third and fourth argument : lua function. */
10213 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10214
Thierry Fournierf67442e2020-11-28 20:41:07 +010010215 /* Check for CLI service already registered */
10216 trash = get_trash_chunk();
10217 index = 0;
10218 lua_pushnil(L);
10219 memset(kw, 0, sizeof(kw));
10220 while (lua_next(L, 1) != 0) {
10221 if (index >= CLI_PREFIX_KW_NB)
10222 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10223 if (lua_type(L, -1) != LUA_TSTRING)
10224 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10225 kw[index] = lua_tostring(L, -1);
10226 if (index == 0)
10227 chunk_printf(trash, "%s", kw[index]);
10228 else
10229 chunk_appendf(trash, " %s", kw[index]);
10230 index++;
10231 lua_pop(L, 1);
10232 }
10233 cli_kw = cli_find_kw_exact((char **)kw);
10234 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010235 fcn = cli_kw->private;
10236 if (fcn->function_ref[hlua_state_id] != -1) {
10237 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10238 "This will become a hard error in version 2.5.\n", trash->area);
10239 }
10240 fcn->function_ref[hlua_state_id] = ref_io;
10241 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010242 }
10243
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010244 /* Allocate and fill the sample fetch keyword struct. */
10245 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010246 if (!cli_kws) {
10247 errmsg = "Lua out of memory error.";
10248 goto error;
10249 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010250 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010251 if (!fcn) {
10252 errmsg = "Lua out of memory error.";
10253 goto error;
10254 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010255
10256 /* Fill path. */
10257 index = 0;
10258 lua_pushnil(L);
10259 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010260 if (index >= 5) {
10261 errmsg = "1st argument must be a table with a maximum of 5 entries";
10262 goto error;
10263 }
10264 if (lua_type(L, -1) != LUA_TSTRING) {
10265 errmsg = "1st argument must be a table filled with strings";
10266 goto error;
10267 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010268 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010269 if (!cli_kws->kw[0].str_kw[index]) {
10270 errmsg = "Lua out of memory error.";
10271 goto error;
10272 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010273 index++;
10274 lua_pop(L, 1);
10275 }
10276
10277 /* Copy help message. */
10278 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010279 if (!cli_kws->kw[0].usage) {
10280 errmsg = "Lua out of memory error.";
10281 goto error;
10282 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010283
10284 /* Fill fcn io handler. */
10285 len = strlen("<lua.cli>") + 1;
10286 for (i = 0; i < index; i++)
10287 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10288 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010289 if (!fcn->name) {
10290 errmsg = "Lua out of memory error.";
10291 goto error;
10292 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010293 strncat((char *)fcn->name, "<lua.cli", len);
10294 for (i = 0; i < index; i++) {
10295 strncat((char *)fcn->name, ".", len);
10296 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10297 }
10298 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010299 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010300
10301 /* Fill last entries. */
10302 cli_kws->kw[0].private = fcn;
10303 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10304 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10305 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10306
10307 /* Register this new converter */
10308 cli_register_kw(cli_kws);
10309
10310 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010311
10312 error:
10313 release_hlua_function(fcn);
10314 if (cli_kws) {
10315 for (i = 0; i < index; i++)
10316 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10317 ha_free((char **)&(cli_kws->kw[0].usage));
10318 }
10319 ha_free(&cli_kws);
10320 WILL_LJMP(luaL_error(L, errmsg));
10321 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010322}
10323
Christopher Faulet69c581a2021-05-31 08:54:04 +020010324static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10325{
10326 struct hlua_flt_config *conf = fconf->conf;
10327 lua_State *L;
10328 int error, pos, state_id, flt_ref;
10329
10330 state_id = reg_flt_to_stack_id(conf->reg);
10331 L = hlua_states[state_id];
10332 pos = lua_gettop(L);
10333
10334 /* The filter parsing function */
10335 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10336
10337 /* Push the filter class on the stack and resolve all callbacks */
10338 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10339
10340 /* Duplicate the filter class so each filter will have its own copy */
10341 lua_newtable(L);
10342 lua_pushnil(L);
10343
10344 while (lua_next(L, pos+2)) {
10345 lua_pushvalue(L, -2);
10346 lua_insert(L, -2);
10347 lua_settable(L, -4);
10348 }
10349 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10350
10351 /* Remove the original lua filter class from the stack */
10352 lua_pop(L, 1);
10353
10354 /* Push the copy on the stack */
10355 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10356
10357 /* extra args are pushed in a table */
10358 lua_newtable(L);
10359 for (pos = 0; conf->args[pos]; pos++) {
10360 /* Check stack available size. */
10361 if (!lua_checkstack(L, 1)) {
10362 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10363 goto error;
10364 }
10365 lua_pushstring(L, conf->args[pos]);
10366 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10367 }
10368
10369 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10370 switch (error) {
10371 case LUA_OK:
10372 /* replace the filter ref */
10373 conf->ref[state_id] = flt_ref;
10374 break;
10375 case LUA_ERRRUN:
10376 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10377 goto error;
10378 case LUA_ERRMEM:
10379 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10380 goto error;
10381 case LUA_ERRERR:
10382 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10383 goto error;
10384#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10385 case LUA_ERRGCMM:
10386 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10387 goto error;
10388#endif
10389 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010390 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010391 goto error;
10392 }
10393
10394 lua_settop(L, 0);
10395 return 0;
10396
10397 error:
10398 lua_settop(L, 0);
10399 return -1;
10400}
10401
10402static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10403{
10404 struct hlua_flt_config *conf = fconf->conf;
10405 lua_State *L;
10406 int state_id;
10407
10408 if (!conf)
10409 return;
10410
10411 state_id = reg_flt_to_stack_id(conf->reg);
10412 L = hlua_states[state_id];
10413 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10414}
10415
10416static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10417{
10418 struct hlua_flt_config *conf = fconf->conf;
10419 int state_id = reg_flt_to_stack_id(conf->reg);
10420
10421 /* Rely on per-thread init for global scripts */
10422 if (!state_id)
10423 return hlua_filter_init_per_thread(px, fconf);
10424 return 0;
10425}
10426
10427static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10428{
10429
10430 if (fconf->conf) {
10431 struct hlua_flt_config *conf = fconf->conf;
10432 int state_id = reg_flt_to_stack_id(conf->reg);
10433 int pos;
10434
10435 /* Rely on per-thread deinit for global scripts */
10436 if (!state_id)
10437 hlua_filter_deinit_per_thread(px, fconf);
10438
10439 for (pos = 0; conf->args[pos]; pos++)
10440 free(conf->args[pos]);
10441 free(conf->args);
10442 }
10443 ha_free(&fconf->conf);
10444 ha_free((char **)&fconf->id);
10445 ha_free(&fconf->ops);
10446}
10447
10448static int hlua_filter_new(struct stream *s, struct filter *filter)
10449{
10450 struct hlua_flt_config *conf = FLT_CONF(filter);
10451 struct hlua_flt_ctx *flt_ctx = NULL;
10452 int ret = 1;
10453
10454 /* In the execution wrappers linked with a stream, the
10455 * Lua context can be not initialized. This behavior
10456 * permits to save performances because a systematic
10457 * Lua initialization cause 5% performances loss.
10458 */
10459 if (!s->hlua) {
10460 struct hlua *hlua;
10461
10462 hlua = pool_alloc(pool_head_hlua);
10463 if (!hlua) {
10464 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10465 conf->reg->name);
10466 ret = 0;
10467 goto end;
10468 }
10469 HLUA_INIT(hlua);
10470 s->hlua = hlua;
10471 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10472 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10473 conf->reg->name);
10474 ret = 0;
10475 goto end;
10476 }
10477 }
10478
10479 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10480 if (!flt_ctx) {
10481 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10482 conf->reg->name);
10483 ret = 0;
10484 goto end;
10485 }
10486 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10487 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10488 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
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 HLUA_INIT(flt_ctx->hlua[0]);
10495 HLUA_INIT(flt_ctx->hlua[1]);
10496 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10497 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10498 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10499 conf->reg->name);
10500 ret = 0;
10501 goto end;
10502 }
10503
10504 if (!HLUA_IS_RUNNING(s->hlua)) {
10505 /* The following Lua calls can fail. */
10506 if (!SET_SAFE_LJMP(s->hlua)) {
10507 const char *error;
10508
10509 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10510 error = lua_tostring(s->hlua->T, -1);
10511 else
10512 error = "critical error";
10513 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10514 ret = 0;
10515 goto end;
10516 }
10517
10518 /* Check stack size. */
10519 if (!lua_checkstack(s->hlua->T, 1)) {
10520 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010521 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010522 ret = 0;
10523 goto end;
10524 }
10525
10526 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10527 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10528 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10529 conf->reg->name);
10530 RESET_SAFE_LJMP(s->hlua);
10531 ret = 0;
10532 goto end;
10533 }
10534 lua_insert(s->hlua->T, -2);
10535
10536 /* Push the copy on the stack */
10537 s->hlua->nargs = 1;
10538
10539 /* We must initialize the execution timeouts. */
10540 s->hlua->max_time = hlua_timeout_session;
10541
10542 /* At this point the execution is safe. */
10543 RESET_SAFE_LJMP(s->hlua);
10544 }
10545
10546 switch (hlua_ctx_resume(s->hlua, 0)) {
10547 case HLUA_E_OK:
10548 /* Nothing returned or not a table, ignore the filter for current stream */
10549 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10550 ret = 0;
10551 goto end;
10552 }
10553
10554 /* Attached the filter pointer to the ctx */
10555 lua_pushstring(s->hlua->T, "__filter");
10556 lua_pushlightuserdata(s->hlua->T, filter);
10557 lua_settable(s->hlua->T, -3);
10558
10559 /* Save a ref on the filter ctx */
10560 lua_pushvalue(s->hlua->T, 1);
10561 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10562 filter->ctx = flt_ctx;
10563 break;
10564 case HLUA_E_ERRMSG:
10565 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10566 ret = -1;
10567 goto end;
10568 case HLUA_E_ETMOUT:
10569 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10570 ret = 0;
10571 goto end;
10572 case HLUA_E_NOMEM:
10573 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10574 ret = 0;
10575 goto end;
10576 case HLUA_E_AGAIN:
10577 case HLUA_E_YIELD:
10578 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10579 " are not allowed from 'new' function.\n", conf->reg->name);
10580 ret = 0;
10581 goto end;
10582 case HLUA_E_ERR:
10583 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10584 ret = 0;
10585 goto end;
10586 default:
10587 ret = 0;
10588 goto end;
10589 }
10590
10591 end:
10592 if (s->hlua)
10593 lua_settop(s->hlua->T, 0);
10594 if (ret <= 0) {
10595 if (flt_ctx) {
10596 hlua_ctx_destroy(flt_ctx->hlua[0]);
10597 hlua_ctx_destroy(flt_ctx->hlua[1]);
10598 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10599 }
10600 }
10601 return ret;
10602}
10603
10604static void hlua_filter_delete(struct stream *s, struct filter *filter)
10605{
10606 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10607
10608 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10609 hlua_ctx_destroy(flt_ctx->hlua[0]);
10610 hlua_ctx_destroy(flt_ctx->hlua[1]);
10611 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10612 filter->ctx = NULL;
10613}
10614
Christopher Faulet9f55a502020-02-25 15:21:02 +010010615static int hlua_filter_from_payload(struct filter *filter)
10616{
10617 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10618
10619 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10620}
10621
Christopher Fauletc404f112020-02-26 15:03:09 +010010622static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10623 int dir, unsigned int flags)
10624{
10625 struct hlua *flt_hlua;
10626 struct hlua_flt_config *conf = FLT_CONF(filter);
10627 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10628 unsigned int hflags = HLUA_TXN_FLT_CTX;
10629 int ret = 1;
10630
10631 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10632 if (!flt_hlua)
10633 goto end;
10634
10635 if (!HLUA_IS_RUNNING(flt_hlua)) {
10636 int extra_idx = lua_gettop(flt_hlua->T);
10637
10638 /* The following Lua calls can fail. */
10639 if (!SET_SAFE_LJMP(flt_hlua)) {
10640 const char *error;
10641
10642 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10643 error = lua_tostring(flt_hlua->T, -1);
10644 else
10645 error = "critical error";
10646 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10647 goto end;
10648 }
10649
10650 /* Check stack size. */
10651 if (!lua_checkstack(flt_hlua->T, 3)) {
10652 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10653 RESET_SAFE_LJMP(flt_hlua);
10654 goto end;
10655 }
10656
10657 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10658 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10659 RESET_SAFE_LJMP(flt_hlua);
10660 goto end;
10661 }
10662 lua_insert(flt_hlua->T, -2);
10663
10664 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10665 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10666 RESET_SAFE_LJMP(flt_hlua);
10667 goto end;
10668 }
10669 flt_hlua->nargs = 2;
10670
10671 if (flags & HLUA_FLT_CB_ARG_CHN) {
10672 if (dir == SMP_OPT_DIR_REQ)
10673 lua_getfield(flt_hlua->T, -1, "req");
10674 else
10675 lua_getfield(flt_hlua->T, -1, "res");
10676 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10677 lua_pushstring(flt_hlua->T, "__filter");
10678 lua_pushlightuserdata(flt_hlua->T, filter);
10679 lua_settable(flt_hlua->T, -3);
10680 }
10681 flt_hlua->nargs++;
10682 }
10683 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010684 if (dir == SMP_OPT_DIR_REQ)
10685 lua_getfield(flt_hlua->T, -1, "http_req");
10686 else
10687 lua_getfield(flt_hlua->T, -1, "http_res");
10688 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10689 lua_pushstring(flt_hlua->T, "__filter");
10690 lua_pushlightuserdata(flt_hlua->T, filter);
10691 lua_settable(flt_hlua->T, -3);
10692 }
10693 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010694 }
10695
10696 /* Check stack size. */
10697 if (!lua_checkstack(flt_hlua->T, 1)) {
10698 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10699 RESET_SAFE_LJMP(flt_hlua);
10700 goto end;
10701 }
10702
10703 while (extra_idx--) {
10704 lua_pushvalue(flt_hlua->T, 1);
10705 lua_remove(flt_hlua->T, 1);
10706 flt_hlua->nargs++;
10707 }
10708
10709 /* We must initialize the execution timeouts. */
10710 flt_hlua->max_time = hlua_timeout_session;
10711
10712 /* At this point the execution is safe. */
10713 RESET_SAFE_LJMP(flt_hlua);
10714 }
10715
10716 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10717 case HLUA_E_OK:
10718 /* Catch the return value if it required */
10719 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10720 ret = lua_tointeger(flt_hlua->T, -1);
10721 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10722 }
10723
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 break;
10732 case HLUA_E_AGAIN:
10733 /* Set timeout in the required channel. */
10734 if (flt_hlua->wake_time != TICK_ETERNITY) {
10735 if (dir == SMP_OPT_DIR_REQ)
10736 s->req.analyse_exp = flt_hlua->wake_time;
10737 else
10738 s->res.analyse_exp = flt_hlua->wake_time;
10739 }
10740 /* Some actions can be wake up when a "write" event
10741 * is detected on a response channel. This is useful
10742 * only for actions targeted on the requests.
10743 */
10744 if (HLUA_IS_WAKERESWR(flt_hlua))
10745 s->res.flags |= CF_WAKE_WRITE;
10746 if (HLUA_IS_WAKEREQWR(flt_hlua))
10747 s->req.flags |= CF_WAKE_WRITE;
10748 ret = 0;
10749 goto end;
10750 case HLUA_E_ERRMSG:
10751 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10752 ret = -1;
10753 goto end;
10754 case HLUA_E_ETMOUT:
10755 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10756 goto end;
10757 case HLUA_E_NOMEM:
10758 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10759 goto end;
10760 case HLUA_E_YIELD:
10761 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10762 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10763 goto end;
10764 case HLUA_E_ERR:
10765 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10766 goto end;
10767 default:
10768 goto end;
10769 }
10770
10771
10772 end:
10773 return ret;
10774}
10775
10776static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10777{
10778 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10779
10780 flt_ctx->flags = 0;
10781 return hlua_filter_callback(s, filter, "start_analyze",
10782 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10783 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10784}
10785
10786static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10787{
10788 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10789
10790 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10791 return hlua_filter_callback(s, filter, "end_analyze",
10792 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10793 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10794}
10795
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010796static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10797{
10798 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10799
10800 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10801 return hlua_filter_callback(s, filter, "http_headers",
10802 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10803 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10804}
10805
10806static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10807 unsigned int offset, unsigned int len)
10808{
10809 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10810 struct hlua *flt_hlua;
10811 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10812 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10813 int ret;
10814
10815 flt_hlua = flt_ctx->hlua[idx];
10816 flt_ctx->cur_off[idx] = offset;
10817 flt_ctx->cur_len[idx] = len;
10818 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10819 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10820 if (ret != -1) {
10821 ret = flt_ctx->cur_len[idx];
10822 if (lua_gettop(flt_hlua->T) > 0) {
10823 ret = lua_tointeger(flt_hlua->T, -1);
10824 if (ret > flt_ctx->cur_len[idx])
10825 ret = flt_ctx->cur_len[idx];
10826 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10827 }
10828 }
10829 return ret;
10830}
10831
10832static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10833{
10834 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10835
10836 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10837 return hlua_filter_callback(s, filter, "http_end",
10838 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10839 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10840}
10841
Christopher Fauletc404f112020-02-26 15:03:09 +010010842static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10843 unsigned int offset, unsigned int len)
10844{
10845 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10846 struct hlua *flt_hlua;
10847 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10848 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10849 int ret;
10850
10851 flt_hlua = flt_ctx->hlua[idx];
10852 flt_ctx->cur_off[idx] = offset;
10853 flt_ctx->cur_len[idx] = len;
10854 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10855 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10856 if (ret != -1) {
10857 ret = flt_ctx->cur_len[idx];
10858 if (lua_gettop(flt_hlua->T) > 0) {
10859 ret = lua_tointeger(flt_hlua->T, -1);
10860 if (ret > flt_ctx->cur_len[idx])
10861 ret = flt_ctx->cur_len[idx];
10862 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10863 }
10864 }
10865 return ret;
10866}
10867
Christopher Faulet69c581a2021-05-31 08:54:04 +020010868static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10869 struct flt_conf *fconf, char **err, void *private)
10870{
10871 struct hlua_reg_filter *reg_flt = private;
10872 lua_State *L;
10873 struct hlua_flt_config *conf = NULL;
10874 const char *flt_id = NULL;
10875 int state_id, pos, flt_flags = 0;
10876 struct flt_ops *hlua_flt_ops = NULL;
10877
10878 state_id = reg_flt_to_stack_id(reg_flt);
10879 L = hlua_states[state_id];
10880
10881 /* Initialize the filter ops with default callbacks */
10882 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010883 if (!hlua_flt_ops)
10884 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010885 hlua_flt_ops->init = hlua_filter_init;
10886 hlua_flt_ops->deinit = hlua_filter_deinit;
10887 if (state_id) {
10888 /* Set per-thread callback if script is loaded per-thread */
10889 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10890 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10891 }
10892 hlua_flt_ops->attach = hlua_filter_new;
10893 hlua_flt_ops->detach = hlua_filter_delete;
10894
10895 /* Push the filter class on the stack and resolve all callbacks */
10896 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10897
Christopher Fauletc404f112020-02-26 15:03:09 +010010898 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10899 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10900 lua_pop(L, 1);
10901 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10902 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10903 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010904 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10905 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10906 lua_pop(L, 1);
10907 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10908 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10909 lua_pop(L, 1);
10910 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10911 hlua_flt_ops->http_end = hlua_filter_http_end;
10912 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010913 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10914 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10915 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010916
10917 /* Get id and flags of the filter class */
10918 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10919 flt_id = lua_tostring(L, -1);
10920 lua_pop(L, 1);
10921 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10922 flt_flags = lua_tointeger(L, -1);
10923 lua_pop(L, 1);
10924
10925 /* Create the filter config */
10926 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010927 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010928 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010929 conf->reg = reg_flt;
10930
10931 /* duplicate args */
10932 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10933 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010934 if (!conf->args)
10935 goto error;
10936 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010937 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010938 if (!conf->args[pos])
10939 goto error;
10940 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010941 conf->args[pos] = NULL;
10942 *cur_arg += pos + 1;
10943
Christopher Fauletc86bb872021-08-13 08:33:57 +020010944 if (flt_id) {
10945 fconf->id = strdup(flt_id);
10946 if (!fconf->id)
10947 goto error;
10948 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010949 fconf->flags = flt_flags;
10950 fconf->conf = conf;
10951 fconf->ops = hlua_flt_ops;
10952
10953 lua_settop(L, 0);
10954 return 0;
10955
10956 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010957 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010958 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010959 if (conf && conf->args) {
10960 for (pos = 0; conf->args[pos]; pos++)
10961 free(conf->args[pos]);
10962 free(conf->args);
10963 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010964 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010965 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010966 lua_settop(L, 0);
10967 return -1;
10968}
10969
Christopher Fauletc404f112020-02-26 15:03:09 +010010970__LJMP static int hlua_register_data_filter(lua_State *L)
10971{
10972 struct filter *filter;
10973 struct channel *chn;
10974
10975 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10976 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10977 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10978
10979 lua_getfield(L, 1, "__filter");
10980 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10981 filter = lua_touserdata (L, -1);
10982 lua_pop(L, 1);
10983
10984 register_data_filter(chn_strm(chn), chn, filter);
10985 return 1;
10986}
10987
10988__LJMP static int hlua_unregister_data_filter(lua_State *L)
10989{
10990 struct filter *filter;
10991 struct channel *chn;
10992
10993 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10994 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10995 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10996
10997 lua_getfield(L, 1, "__filter");
10998 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10999 filter = lua_touserdata (L, -1);
11000 lua_pop(L, 1);
11001
11002 unregister_data_filter(chn_strm(chn), chn, filter);
11003 return 1;
11004}
11005
Christopher Faulet69c581a2021-05-31 08:54:04 +020011006/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011007 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011008 * parse configuration arguments.
11009 */
11010__LJMP static int hlua_register_filter(lua_State *L)
11011{
11012 struct buffer *trash;
11013 struct flt_kw_list *fkl;
11014 struct flt_kw *fkw;
11015 const char *name;
11016 struct hlua_reg_filter *reg_flt= NULL;
11017 int flt_ref, fun_ref;
11018 int len;
11019
11020 MAY_LJMP(check_args(L, 3, "register_filter"));
11021
11022 /* First argument : filter name. */
11023 name = MAY_LJMP(luaL_checkstring(L, 1));
11024
11025 /* Second argument : The filter class */
11026 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11027
11028 /* Third argument : lua function. */
11029 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11030
11031 trash = get_trash_chunk();
11032 chunk_printf(trash, "lua.%s", name);
11033 fkw = flt_find_kw(trash->area);
11034 if (fkw != NULL) {
11035 reg_flt = fkw->private;
11036 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11037 ha_warning("Trying to register filter 'lua.%s' more than once. "
11038 "This will become a hard error in version 2.5.\n", name);
11039 }
11040 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11041 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11042 return 0;
11043 }
11044
11045 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11046 if (!fkl)
11047 goto alloc_error;
11048 fkl->scope = "HLUA";
11049
11050 reg_flt = new_hlua_reg_filter(name);
11051 if (!reg_flt)
11052 goto alloc_error;
11053
11054 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11055 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11056
11057 /* The filter keyword */
11058 len = strlen("lua.") + strlen(name) + 1;
11059 fkl->kw[0].kw = calloc(1, len);
11060 if (!fkl->kw[0].kw)
11061 goto alloc_error;
11062
11063 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11064
11065 fkl->kw[0].parse = hlua_filter_parse_fct;
11066 fkl->kw[0].private = reg_flt;
11067 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11068
11069 /* Register this new filter */
11070 flt_register_keywords(fkl);
11071
11072 return 0;
11073
11074 alloc_error:
11075 release_hlua_reg_filter(reg_flt);
11076 ha_free(&fkl);
11077 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11078 return 0; /* Never reached */
11079}
11080
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011081static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011082 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011083 char **err, unsigned int *timeout)
11084{
11085 const char *error;
11086
11087 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011088 if (error == PARSE_TIME_OVER) {
11089 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11090 args[1], args[0]);
11091 return -1;
11092 }
11093 else if (error == PARSE_TIME_UNDER) {
11094 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11095 args[1], args[0]);
11096 return -1;
11097 }
11098 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011099 memprintf(err, "%s: invalid timeout", args[0]);
11100 return -1;
11101 }
11102 return 0;
11103}
11104
11105static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011106 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011107 char **err)
11108{
11109 return hlua_read_timeout(args, section_type, curpx, defpx,
11110 file, line, err, &hlua_timeout_session);
11111}
11112
11113static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011114 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011115 char **err)
11116{
11117 return hlua_read_timeout(args, section_type, curpx, defpx,
11118 file, line, err, &hlua_timeout_task);
11119}
11120
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011121static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011122 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011123 char **err)
11124{
11125 return hlua_read_timeout(args, section_type, curpx, defpx,
11126 file, line, err, &hlua_timeout_applet);
11127}
11128
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011129static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011130 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011131 char **err)
11132{
11133 char *error;
11134
11135 hlua_nb_instruction = strtoll(args[1], &error, 10);
11136 if (*error != '\0') {
11137 memprintf(err, "%s: invalid number", args[0]);
11138 return -1;
11139 }
11140 return 0;
11141}
11142
Willy Tarreau32f61e22015-03-18 17:54:59 +010011143static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011144 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011145 char **err)
11146{
11147 char *error;
11148
11149 if (*(args[1]) == 0) {
11150 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11151 return -1;
11152 }
11153 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11154 if (*error != '\0') {
11155 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11156 return -1;
11157 }
11158 return 0;
11159}
11160
11161
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011162/* This function is called by the main configuration key "lua-load". It loads and
11163 * execute an lua file during the parsing of the HAProxy configuration file. It is
11164 * the main lua entry point.
11165 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011166 * This function runs with the HAProxy keywords API. It returns -1 if an error
11167 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011168 *
11169 * In some error case, LUA set an error message in top of the stack. This function
11170 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011171 *
11172 * This function can fail with an abort() due to an Lua critical error.
11173 * We are in the configuration parsing process of HAProxy, this abort() is
11174 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011175 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011176static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011177{
11178 int error;
11179
11180 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011181 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011182 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011183 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11184 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011185 return -1;
11186 }
11187
11188 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011189 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011190 switch (error) {
11191 case LUA_OK:
11192 break;
11193 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011194 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11195 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011196 return -1;
11197 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011198 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011199 return -1;
11200 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011201 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11202 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011203 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011204#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011205 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011206 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11207 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011208 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011209#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011210 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011211 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11212 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011213 return -1;
11214 }
11215
11216 return 0;
11217}
11218
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011219static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011220 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011221 char **err)
11222{
11223 if (*(args[1]) == 0) {
11224 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11225 return -1;
11226 }
11227
Thierry Fournier59f11be2020-11-29 00:37:41 +010011228 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011229 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011230 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011231 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011232}
11233
Thierry Fournier59f11be2020-11-29 00:37:41 +010011234static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011235 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011236 char **err)
11237{
11238 int len;
11239
11240 if (*(args[1]) == 0) {
11241 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11242 return -1;
11243 }
11244
11245 if (per_thread_load == NULL) {
11246 /* allocate the first entry large enough to store the final NULL */
11247 per_thread_load = calloc(1, sizeof(*per_thread_load));
11248 if (per_thread_load == NULL) {
11249 memprintf(err, "out of memory error");
11250 return -1;
11251 }
11252 }
11253
11254 /* count used entries */
11255 for (len = 0; per_thread_load[len] != NULL; len++)
11256 ;
11257
11258 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11259 if (per_thread_load == NULL) {
11260 memprintf(err, "out of memory error");
11261 return -1;
11262 }
11263
11264 per_thread_load[len] = strdup(args[1]);
11265 per_thread_load[len + 1] = NULL;
11266
11267 if (per_thread_load[len] == NULL) {
11268 memprintf(err, "out of memory error");
11269 return -1;
11270 }
11271
11272 /* loading for thread 1 only */
11273 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011274 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011275 return hlua_load_state(args[1], hlua_states[1], err);
11276}
11277
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011278/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11279 * in the given <ctx>.
11280 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011281static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011282{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011283 lua_getglobal(L, "package"); /* push package variable */
11284 lua_pushstring(L, path); /* push given path */
11285 lua_pushstring(L, ";"); /* push semicolon */
11286 lua_getfield(L, -3, type); /* push old path */
11287 lua_concat(L, 3); /* concatenate to new path */
11288 lua_setfield(L, -2, type); /* store new path */
11289 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011290
11291 return 0;
11292}
11293
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011294static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011295 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011296 char **err)
11297{
11298 char *path;
11299 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011300 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011301 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011302
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011303 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011304 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011305 }
11306
11307 if (!(*args[1])) {
11308 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011309 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011310 }
11311 path = args[1];
11312
11313 if (*args[2]) {
11314 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11315 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011316 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011317 }
11318 type = args[2];
11319 }
11320
Thierry Fournier59f11be2020-11-29 00:37:41 +010011321 p = calloc(1, sizeof(*p));
11322 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011323 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011324 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011325 }
11326 p->path = strdup(path);
11327 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011328 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011329 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011330 }
11331 p->type = strdup(type);
11332 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011333 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011334 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011335 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011336 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011337
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011338 /* Handle the global state and the per-thread state for the first
11339 * thread. The remaining threads will be initialized based on
11340 * prepend_path_list.
11341 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011342 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011343 lua_State *L = hlua_states[i];
11344 const char *error;
11345
11346 if (setjmp(safe_ljmp_env) != 0) {
11347 lua_atpanic(L, hlua_panic_safe);
11348 if (lua_type(L, -1) == LUA_TSTRING)
11349 error = lua_tostring(L, -1);
11350 else
11351 error = "critical error";
11352 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11353 exit(1);
11354 } else {
11355 lua_atpanic(L, hlua_panic_ljmp);
11356 }
11357
11358 hlua_prepend_path(L, type, path);
11359
11360 lua_atpanic(L, hlua_panic_safe);
11361 }
11362
Thierry Fournier59f11be2020-11-29 00:37:41 +010011363 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011364
11365err2:
11366 free(p->type);
11367 free(p->path);
11368err:
11369 free(p);
11370 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011371}
11372
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011373/* configuration keywords declaration */
11374static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011375 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011376 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011377 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011378 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11379 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011380 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011381 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011382 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011383 { 0, NULL, NULL },
11384}};
11385
Willy Tarreau0108d902018-11-25 19:14:37 +010011386INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11387
William Lallemand52139182022-03-30 15:05:42 +020011388#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011389
William Lallemand30fcca12022-03-30 12:03:12 +020011390/*
11391 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11392 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11393 * difference is that the yield in lua and for the CLI is not handled the same
11394 * way.
11395 */
11396__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11397{
11398 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11399 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11400 struct ckch_inst *ckchi = *lua_ckchi;
11401 struct ckch_store *old_ckchs = lua_ckchs[0];
11402 struct ckch_store *new_ckchs = lua_ckchs[1];
11403 struct hlua *hlua;
11404 char *err = NULL;
11405 int y = 1;
11406
11407 hlua = hlua_gethlua(L);
11408
11409 /* get the first ckchi to copy */
11410 if (ckchi == NULL)
11411 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11412
11413 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11414 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11415 struct ckch_inst *new_inst;
11416
11417 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11418 if (y % 10 == 0) {
11419
11420 *lua_ckchi = ckchi;
11421
11422 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11423 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11424 }
11425
11426 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11427 goto error;
11428
11429 /* link the new ckch_inst to the duplicate */
11430 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11431 y++;
11432 }
11433
11434 /* The generation is finished, we can insert everything */
11435 ckch_store_replace(old_ckchs, new_ckchs);
11436
11437 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11438
11439 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11440
11441 return 0;
11442
11443error:
11444 ckch_store_free(new_ckchs);
11445 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11446 WILL_LJMP(luaL_error(L, "%s", err));
11447 free(err);
11448
11449 return 0;
11450}
11451
11452/*
11453 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11454 * from the table in parameter.
11455 *
11456 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11457 * means it does not need to have a transaction since everything is done in the
11458 * same function.
11459 *
11460 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11461 *
11462 */
11463__LJMP static int hlua_ckch_set(lua_State *L)
11464{
11465 struct hlua *hlua;
11466 struct ckch_inst **lua_ckchi;
11467 struct ckch_store **lua_ckchs;
11468 struct ckch_store *old_ckchs = NULL;
11469 struct ckch_store *new_ckchs = NULL;
11470 int errcode = 0;
11471 char *err = NULL;
11472 struct cert_exts *cert_ext = NULL;
11473 char *filename;
11474 struct cert_key_and_chain *ckch;
11475 int ret;
11476
11477 if (lua_type(L, -1) != LUA_TTABLE)
11478 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11479
11480 hlua = hlua_gethlua(L);
11481
11482 /* FIXME: this should not return an error but should come back later */
11483 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11484 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11485
11486 ret = lua_getfield(L, -1, "filename");
11487 if (ret != LUA_TSTRING) {
11488 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11489 errcode |= ERR_ALERT | ERR_FATAL;
11490 goto end;
11491 }
11492 filename = (char *)lua_tostring(L, -1);
11493
11494
11495 /* look for the filename in the tree */
11496 old_ckchs = ckchs_lookup(filename);
11497 if (!old_ckchs) {
11498 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11499 errcode |= ERR_ALERT | ERR_FATAL;
11500 goto end;
11501 }
11502 /* TODO: handle extra_files_noext */
11503
11504 new_ckchs = ckchs_dup(old_ckchs);
11505 if (!new_ckchs) {
11506 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11507 errcode |= ERR_ALERT | ERR_FATAL;
11508 goto end;
11509 }
11510
11511 ckch = new_ckchs->ckch;
11512
11513 /* loop on the field in the table, which have the same name as the
11514 * possible extensions of files */
11515 lua_pushnil(L);
11516 while (lua_next(L, 1)) {
11517 int i;
11518 const char *field = lua_tostring(L, -2);
11519 char *payload = (char *)lua_tostring(L, -1);
11520
11521 if (!field || strcmp(field, "filename") == 0) {
11522 lua_pop(L, 1);
11523 continue;
11524 }
11525
11526 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11527 if (strcmp(field, cert_exts[i].ext) == 0) {
11528 cert_ext = &cert_exts[i];
11529 break;
11530 }
11531 }
11532
11533 /* this is the default type, the field is not supported */
11534 if (cert_ext == NULL) {
11535 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11536 errcode |= ERR_ALERT | ERR_FATAL;
11537 goto end;
11538 }
11539
11540 /* appply the change on the duplicate */
11541 if (cert_exts->load(filename, payload, ckch, &err) != 0) {
11542 memprintf(&err, "%sCan't load the payload\n", err ? err : "");
11543 errcode |= ERR_ALERT | ERR_FATAL;
11544 goto end;
11545 }
11546 lua_pop(L, 1);
11547 }
11548
11549 /* store the pointers on the lua stack */
11550 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11551 lua_ckchs[0] = old_ckchs;
11552 lua_ckchs[1] = new_ckchs;
11553 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11554 *lua_ckchi = NULL;
11555
11556 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11557 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11558
11559end:
11560 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11561
11562 if (errcode & ERR_CODE) {
11563 ckch_store_free(new_ckchs);
11564 WILL_LJMP(luaL_error(L, "%s", err));
11565 }
11566 free(err);
11567
11568 return 0;
11569}
11570
William Lallemand52139182022-03-30 15:05:42 +020011571#else
11572
11573__LJMP static int hlua_ckch_set(lua_State *L)
11574{
11575 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11576
11577 return 0;
11578}
11579#endif /* ! USE_OPENSSL */
11580
11581
11582
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011583/* This function can fail with an abort() due to an Lua critical error.
11584 * We are in the initialisation process of HAProxy, this abort() is
11585 * tolerated.
11586 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011587int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011588{
11589 struct hlua_init_function *init;
11590 const char *msg;
11591 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011592 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011593 const char *kind;
11594 const char *trace;
11595 int return_status = 1;
11596#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11597 int nres;
11598#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011599
Willy Tarreaucdb53462020-12-02 12:12:00 +010011600 /* disable memory limit checks if limit is not set */
11601 if (!hlua_global_allocator.limit)
11602 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11603
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011604 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011605 if (setjmp(safe_ljmp_env) != 0) {
11606 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011607 if (lua_type(L, -1) == LUA_TSTRING)
11608 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011609 else
11610 error = "critical error";
11611 fprintf(stderr, "Lua post-init: %s.\n", error);
11612 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011613 } else {
11614 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011615 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011616
Thierry Fournierb8cef172020-11-28 15:37:17 +010011617 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011618
Thierry Fournierc7492592020-11-28 23:57:24 +010011619 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011620 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011621
11622#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011623 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011624#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011625 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011626#endif
11627 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011628 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011629
11630 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011631 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011632 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011633
11634 case LUA_ERRERR:
11635 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011636 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011637 case LUA_ERRRUN:
11638 if (!kind)
11639 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011640 msg = lua_tostring(L, -1);
11641 lua_settop(L, 0); /* Empty the stack. */
11642 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011643 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011644 if (msg)
11645 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11646 else
11647 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11648 return_status = 0;
11649 break;
11650
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011651 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011652 /* Unknown error */
11653 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011654 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011655 case LUA_YIELD:
11656 /* yield is not configured at this step, this state doesn't happen */
11657 if (!kind)
11658 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011659 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011660 case LUA_ERRMEM:
11661 if (!kind)
11662 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011663 lua_settop(L, 0);
11664 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011665 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011666 ha_alert("Lua init: %s: %s\n", kind, trace);
11667 return_status = 0;
11668 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011669 }
Thierry Fournier670db242020-11-28 10:49:59 +010011670 if (!return_status)
11671 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011672 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011673
11674 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011675 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011676}
11677
Thierry Fournierb8cef172020-11-28 15:37:17 +010011678int hlua_post_init()
11679{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011680 int ret;
11681 int i;
11682 int errors;
11683 char *err = NULL;
11684 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011685 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011686
Willy Tarreaub1310492021-08-30 09:35:18 +020011687#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011688 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011689 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011690 int saved_used_backed = global.ssl_used_backend;
11691 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011692 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011693 global.ssl_used_backend = saved_used_backed;
11694 }
11695#endif
11696
Thierry Fournierc7492592020-11-28 23:57:24 +010011697 /* Perform post init of common thread */
11698 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011699 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011700 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11701 if (ret == 0)
11702 return 0;
11703
11704 /* init remaining lua states and load files */
11705 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11706
11707 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011708 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011709
11710 /* Init lua state */
11711 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11712
11713 /* Load lua files */
11714 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11715 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11716 if (ret != 0) {
11717 ha_alert("Lua init: %s\n", err);
11718 return 0;
11719 }
11720 }
11721 }
11722
11723 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011724 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011725
11726 /* Execute post init for all states */
11727 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11728
11729 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011730 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011731
11732 /* run post init */
11733 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11734 if (ret == 0)
11735 return 0;
11736 }
11737
11738 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011739 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011740
11741 /* control functions registering. Each function must have:
11742 * - only the function_ref[0] set positive and all other to -1
11743 * - only the function_ref[0] set to -1 and all other positive
11744 * This ensure a same reference is not used both in shared
11745 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011746 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011747 * complicated to found for the end user.
11748 */
11749 errors = 0;
11750 list_for_each_entry(fcn, &referenced_functions, l) {
11751 ret = 0;
11752 for (i = 1; i < global.nbthread + 1; i++) {
11753 if (fcn->function_ref[i] == -1)
11754 ret--;
11755 else
11756 ret++;
11757 }
11758 if (abs(ret) != global.nbthread) {
11759 ha_alert("Lua function '%s' is not referenced in all thread. "
11760 "Expect function in all thread or in none thread.\n", fcn->name);
11761 errors++;
11762 continue;
11763 }
11764
11765 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011766 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11767 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011768 "exclusive.\n", fcn->name);
11769 errors++;
11770 }
11771 }
11772
Christopher Faulet69c581a2021-05-31 08:54:04 +020011773 /* Do the same with registered filters */
11774 list_for_each_entry(reg_flt, &referenced_filters, l) {
11775 ret = 0;
11776 for (i = 1; i < global.nbthread + 1; i++) {
11777 if (reg_flt->flt_ref[i] == -1)
11778 ret--;
11779 else
11780 ret++;
11781 }
11782 if (abs(ret) != global.nbthread) {
11783 ha_alert("Lua filter '%s' is not referenced in all thread. "
11784 "Expect function in all thread or in none thread.\n", reg_flt->name);
11785 errors++;
11786 continue;
11787 }
11788
11789 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11790 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11791 "and per-thread Lua context (through lua-load-per-thread). these two context "
11792 "exclusive.\n", fcn->name);
11793 errors++;
11794 }
11795 }
11796
11797
Thierry Fournier59f11be2020-11-29 00:37:41 +010011798 if (errors > 0)
11799 return 0;
11800
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011801 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011802 * -1 in order to have probably a segfault if someone use it
11803 */
11804 hlua_state_id = -1;
11805
11806 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011807}
11808
Willy Tarreau32f61e22015-03-18 17:54:59 +010011809/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11810 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11811 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011812 * allocation. <nsize> is the requested new size. A new allocation is
11813 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011814 * zero. This one verifies that the limits are respected but is optimized
11815 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011816 *
11817 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11818 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11819 * that and will simply allocate zero as if it were the result of malloc(0),
11820 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11821 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011822 */
11823static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11824{
11825 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011826 size_t limit, old, new;
11827
11828 /* a limit of ~0 means unlimited and boot complete, so there's no need
11829 * for accounting anymore.
11830 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011831 if (likely(~zone->limit == 0)) {
11832 if (!nsize)
11833 ha_free(&ptr);
11834 else
11835 ptr = realloc(ptr, nsize);
11836 return ptr;
11837 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011838
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011839 if (!ptr)
11840 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011841
Willy Tarreaucdb53462020-12-02 12:12:00 +010011842 /* enforce strict limits across all threads */
11843 limit = zone->limit;
11844 old = _HA_ATOMIC_LOAD(&zone->allocated);
11845 do {
11846 new = old + nsize - osize;
11847 if (unlikely(nsize && limit && new > limit))
11848 return NULL;
11849 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011850
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011851 if (!nsize)
11852 ha_free(&ptr);
11853 else
11854 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011855
11856 if (unlikely(!ptr && nsize)) // failed
11857 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11858
11859 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011860 return ptr;
11861}
11862
Thierry Fournierecb83c22020-11-28 15:49:44 +010011863/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011864 * We are in the initialisation process of HAProxy, this abort() is
11865 * tolerated.
11866 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011867lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011868{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011869 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011870 int idx;
11871 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011872 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011873 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011874 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011875 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011876 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011877 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011878
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011879 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011880 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011881
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011882 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011883 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011884 *context = NULL;
11885
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011886 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011887 * the Lua function can fail with an abort. We are in the initialisation
11888 * process of HAProxy, this abort() is tolerated.
11889 */
11890
Thierry Fournier3c539322020-11-28 16:05:05 +010011891 /* Call post initialisation function in safe environment. */
11892 if (setjmp(safe_ljmp_env) != 0) {
11893 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011894 if (lua_type(L, -1) == LUA_TSTRING)
11895 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011896 else
11897 error_msg = "critical error";
11898 fprintf(stderr, "Lua init: %s.\n", error_msg);
11899 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011900 } else {
11901 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011902 }
11903
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011904 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011905 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011906#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11907#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11908#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011909 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011910#endif
11911#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011912 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011913#endif
11914#undef HLUA_PREPEND_PATH_TOSTRING
11915#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011916
Thierry Fournier59f11be2020-11-29 00:37:41 +010011917 /* Apply configured prepend path */
11918 list_for_each_entry(pp, &prepend_path_list, l)
11919 hlua_prepend_path(L, pp->type, pp->path);
11920
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011921 /*
11922 *
11923 * Create "core" object.
11924 *
11925 */
11926
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011927 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011928 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011929
Thierry Fournierecb83c22020-11-28 15:49:44 +010011930 /* set the thread id */
11931 hlua_class_const_int(L, "thread", thread_num);
11932
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011933 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011934 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011935 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011936
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011937 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011938 hlua_class_function(L, "register_init", hlua_register_init);
11939 hlua_class_function(L, "register_task", hlua_register_task);
11940 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11941 hlua_class_function(L, "register_converters", hlua_register_converters);
11942 hlua_class_function(L, "register_action", hlua_register_action);
11943 hlua_class_function(L, "register_service", hlua_register_service);
11944 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011945 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011946 hlua_class_function(L, "yield", hlua_yield);
11947 hlua_class_function(L, "set_nice", hlua_set_nice);
11948 hlua_class_function(L, "sleep", hlua_sleep);
11949 hlua_class_function(L, "msleep", hlua_msleep);
11950 hlua_class_function(L, "add_acl", hlua_add_acl);
11951 hlua_class_function(L, "del_acl", hlua_del_acl);
11952 hlua_class_function(L, "set_map", hlua_set_map);
11953 hlua_class_function(L, "del_map", hlua_del_map);
11954 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011955 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011956 hlua_class_function(L, "log", hlua_log);
11957 hlua_class_function(L, "Debug", hlua_log_debug);
11958 hlua_class_function(L, "Info", hlua_log_info);
11959 hlua_class_function(L, "Warning", hlua_log_warning);
11960 hlua_class_function(L, "Alert", hlua_log_alert);
11961 hlua_class_function(L, "done", hlua_done);
11962 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011963
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011964 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011965
11966 /*
11967 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011968 * Create "act" object.
11969 *
11970 */
11971
11972 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011973 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011974
11975 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011976 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11977 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11978 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11979 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11980 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11981 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11982 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11983 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011984
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011985 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011986
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011987 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011988
11989 /*
11990 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011991 * Create "Filter" object.
11992 *
11993 */
11994
11995 /* This table entry is the object "filter" base. */
11996 lua_newtable(L);
11997
11998 /* push flags and constants */
11999 hlua_class_const_int(L, "CONTINUE", 1);
12000 hlua_class_const_int(L, "WAIT", 0);
12001 hlua_class_const_int(L, "ERROR", -1);
12002
12003 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12004
Christopher Fauletc404f112020-02-26 15:03:09 +010012005 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12006 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12007 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12008
Christopher Faulet69c581a2021-05-31 08:54:04 +020012009 lua_setglobal(L, "filter");
12010
12011 /*
12012 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012013 * Register class Map
12014 *
12015 */
12016
12017 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012018 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012019
12020 /* register pattern types. */
12021 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012022 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012023 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012024 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012025 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012026 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012027
12028 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012029 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012030
12031 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012032 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012033
Ilya Shipitsind4259502020-04-08 01:07:56 +050012034 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012035 lua_pushstring(L, "__index");
12036 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012037
12038 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012039 hlua_class_function(L, "lookup", hlua_map_lookup);
12040 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012041
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012042 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012043
Thierry Fournier45e78d72016-02-19 18:34:46 +010012044 /* Register previous table in the registry with reference and named entry.
12045 * The function hlua_register_metatable() pops the stack, so we
12046 * previously create a copy of the table.
12047 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012048 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12049 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012050
12051 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012052 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012053
12054 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012055 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012056
12057 /*
12058 *
William Lallemand30fcca12022-03-30 12:03:12 +020012059 * Register "CertCache" class
12060 *
12061 */
12062
12063 /* Create and fill the metatable. */
12064 lua_newtable(L);
12065 /* Register */
12066 hlua_class_function(L, "set", hlua_ckch_set);
12067 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12068
12069 /*
12070 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012071 * Register class Channel
12072 *
12073 */
12074
12075 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012076 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012077
Ilya Shipitsind4259502020-04-08 01:07:56 +050012078 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012079 lua_pushstring(L, "__index");
12080 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012081
12082 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012083 hlua_class_function(L, "data", hlua_channel_get_data);
12084 hlua_class_function(L, "line", hlua_channel_get_line);
12085 hlua_class_function(L, "set", hlua_channel_set_data);
12086 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012087 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012088 hlua_class_function(L, "prepend", hlua_channel_prepend);
12089 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012090 hlua_class_function(L, "send", hlua_channel_send);
12091 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012092 hlua_class_function(L, "input", hlua_channel_get_in_len);
12093 hlua_class_function(L, "output", hlua_channel_get_out_len);
12094 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012095 hlua_class_function(L, "is_full", hlua_channel_is_full);
12096 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012097
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012098 /* Deprecated API */
12099 hlua_class_function(L, "get", hlua_channel_get);
12100 hlua_class_function(L, "dup", hlua_channel_dup);
12101 hlua_class_function(L, "getline", hlua_channel_getline);
12102 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12103 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12104
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012105 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012106
12107 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012108 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012109
12110 /*
12111 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012112 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012113 *
12114 */
12115
12116 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012117 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012118
Ilya Shipitsind4259502020-04-08 01:07:56 +050012119 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012120 lua_pushstring(L, "__index");
12121 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012122
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012123 /* Browse existing fetches and create the associated
12124 * object method.
12125 */
12126 sf = NULL;
12127 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012128 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12129 * by an underscore.
12130 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012131 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012132 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012133 if (*p == '.' || *p == '-' || *p == '+')
12134 *p = '_';
12135
12136 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012137 lua_pushstring(L, trash.area);
12138 lua_pushlightuserdata(L, sf);
12139 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12140 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012141 }
12142
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012143 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012144
12145 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012146 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012147
12148 /*
12149 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012150 * Register class Converters
12151 *
12152 */
12153
12154 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012155 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012156
12157 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012158 lua_pushstring(L, "__index");
12159 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012160
12161 /* Browse existing converters and create the associated
12162 * object method.
12163 */
12164 sc = NULL;
12165 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012166 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12167 * by an underscore.
12168 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012169 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012170 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012171 if (*p == '.' || *p == '-' || *p == '+')
12172 *p = '_';
12173
12174 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012175 lua_pushstring(L, trash.area);
12176 lua_pushlightuserdata(L, sc);
12177 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12178 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012179 }
12180
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012181 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012182
12183 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012184 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012185
12186 /*
12187 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012188 * Register class HTTP
12189 *
12190 */
12191
12192 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012193 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012194
Ilya Shipitsind4259502020-04-08 01:07:56 +050012195 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012196 lua_pushstring(L, "__index");
12197 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012198
12199 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012200 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12201 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12202 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12203 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12204 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12205 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12206 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12207 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12208 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12209 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012210
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012211 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12212 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12213 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12214 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12215 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12216 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12217 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012218
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012219 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012220
12221 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012222 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012223
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012224 /*
12225 *
12226 * Register class HTTPMessage
12227 *
12228 */
12229
12230 /* Create and fill the metatable. */
12231 lua_newtable(L);
12232
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012233 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012234 lua_pushstring(L, "__index");
12235 lua_newtable(L);
12236
12237 /* Register Lua functions. */
12238 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12239 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12240 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12241 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12242 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12243 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12244 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12245 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12246 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12247 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12248 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12249 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12250 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12251 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12252 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12253 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12254 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12255 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12256
12257 hlua_class_function(L, "body", hlua_http_msg_get_body);
12258 hlua_class_function(L, "set", hlua_http_msg_set_data);
12259 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12260 hlua_class_function(L, "append", hlua_http_msg_append);
12261 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12262 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12263 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12264 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12265
12266 hlua_class_function(L, "send", hlua_http_msg_send);
12267 hlua_class_function(L, "forward", hlua_http_msg_forward);
12268
12269 lua_rawset(L, -3);
12270
12271 /* Register previous table in the registry with reference and named entry. */
12272 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012273
12274 /*
12275 *
12276 * Register class HTTPClient
12277 *
12278 */
12279
12280 /* Create and fill the metatable. */
12281 lua_newtable(L);
12282 lua_pushstring(L, "__index");
12283 lua_newtable(L);
12284 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012285 hlua_class_function(L, "head", hlua_httpclient_head);
12286 hlua_class_function(L, "put", hlua_httpclient_put);
12287 hlua_class_function(L, "post", hlua_httpclient_post);
12288 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012289 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012290 /* Register the garbage collector entry. */
12291 lua_pushstring(L, "__gc");
12292 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12293 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12294
William Lallemand3956c4e2021-09-21 16:25:15 +020012295
12296
12297 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012298 /*
12299 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012300 * Register class AppletTCP
12301 *
12302 */
12303
12304 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012305 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012306
Ilya Shipitsind4259502020-04-08 01:07:56 +050012307 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012308 lua_pushstring(L, "__index");
12309 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012310
12311 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012312 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12313 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12314 hlua_class_function(L, "send", hlua_applet_tcp_send);
12315 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12316 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12317 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12318 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12319 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012320
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012321 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012322
12323 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012324 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012325
12326 /*
12327 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012328 * Register class AppletHTTP
12329 *
12330 */
12331
12332 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012333 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012334
Ilya Shipitsind4259502020-04-08 01:07:56 +050012335 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012336 lua_pushstring(L, "__index");
12337 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012338
12339 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012340 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12341 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12342 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12343 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12344 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12345 hlua_class_function(L, "getline", hlua_applet_http_getline);
12346 hlua_class_function(L, "receive", hlua_applet_http_recv);
12347 hlua_class_function(L, "send", hlua_applet_http_send);
12348 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12349 hlua_class_function(L, "set_status", hlua_applet_http_status);
12350 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012351
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012352 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012353
12354 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012355 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012356
12357 /*
12358 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012359 * Register class TXN
12360 *
12361 */
12362
12363 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012364 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012365
Ilya Shipitsind4259502020-04-08 01:07:56 +050012366 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012367 lua_pushstring(L, "__index");
12368 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012369
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012370 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012371 hlua_class_function(L, "set_priv", hlua_set_priv);
12372 hlua_class_function(L, "get_priv", hlua_get_priv);
12373 hlua_class_function(L, "set_var", hlua_set_var);
12374 hlua_class_function(L, "unset_var", hlua_unset_var);
12375 hlua_class_function(L, "get_var", hlua_get_var);
12376 hlua_class_function(L, "done", hlua_txn_done);
12377 hlua_class_function(L, "reply", hlua_txn_reply_new);
12378 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12379 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12380 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12381 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12382 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12383 hlua_class_function(L, "deflog", hlua_txn_deflog);
12384 hlua_class_function(L, "log", hlua_txn_log);
12385 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12386 hlua_class_function(L, "Info", hlua_txn_log_info);
12387 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12388 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012389
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012390 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012391
12392 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012393 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012394
12395 /*
12396 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012397 * Register class reply
12398 *
12399 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012400 lua_newtable(L);
12401 lua_pushstring(L, "__index");
12402 lua_newtable(L);
12403 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12404 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12405 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12406 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12407 lua_settable(L, -3); /* Sets the __index entry. */
12408 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012409
12410
12411 /*
12412 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012413 * Register class Socket
12414 *
12415 */
12416
12417 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012418 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012419
Ilya Shipitsind4259502020-04-08 01:07:56 +050012420 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012421 lua_pushstring(L, "__index");
12422 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012423
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012424#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012425 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012426#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012427 hlua_class_function(L, "connect", hlua_socket_connect);
12428 hlua_class_function(L, "send", hlua_socket_send);
12429 hlua_class_function(L, "receive", hlua_socket_receive);
12430 hlua_class_function(L, "close", hlua_socket_close);
12431 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12432 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12433 hlua_class_function(L, "setoption", hlua_socket_setoption);
12434 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012435
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012436 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012437
12438 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012439 lua_pushstring(L, "__gc");
12440 lua_pushcclosure(L, hlua_socket_gc, 0);
12441 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012442
12443 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012444 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012445
Thierry Fournieraafc7772020-12-04 11:47:47 +010012446 lua_atpanic(L, hlua_panic_safe);
12447
12448 return L;
12449}
12450
12451void hlua_init(void) {
12452 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012453 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012454#ifdef USE_OPENSSL
12455 struct srv_kw *kw;
12456 int tmp_error;
12457 char *error;
12458 char *args[] = { /* SSL client configuration. */
12459 "ssl",
12460 "verify",
12461 "none",
12462 NULL
12463 };
12464#endif
12465
12466 /* Init post init function list head */
12467 for (i = 0; i < MAX_THREADS + 1; i++)
12468 LIST_INIT(&hlua_init_functions[i]);
12469
12470 /* Init state for common/shared lua parts */
12471 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012472 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012473 hlua_states[0] = hlua_init_state(0);
12474
12475 /* Init state 1 for thread 0. We have at least one thread. */
12476 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012477 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012478 hlua_states[1] = hlua_init_state(1);
12479
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012480 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012481 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012482 if (!socket_proxy) {
12483 fprintf(stderr, "Lua init: %s\n", errmsg);
12484 exit(1);
12485 }
12486 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012487
12488 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012489 socket_tcp = new_server(socket_proxy);
12490 if (!socket_tcp) {
12491 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12492 exit(1);
12493 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012494
12495#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012496 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012497 socket_ssl = new_server(socket_proxy);
12498 if (!socket_ssl) {
12499 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12500 exit(1);
12501 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012502
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012503 socket_ssl->use_ssl = 1;
12504 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012505
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012506 for (i = 0; args[i] != NULL; i++) {
12507 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012508 /*
12509 *
12510 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012511 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012512 * features like client certificates and ssl_verify.
12513 *
12514 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012515 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012516 if (tmp_error != 0) {
12517 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12518 abort(); /* This must be never arrives because the command line
12519 not editable by the user. */
12520 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012521 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012522 }
12523 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012524#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012525
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012526}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012527
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012528static void hlua_deinit()
12529{
Willy Tarreau186f3762020-12-04 11:48:12 +010012530 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012531 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12532
12533 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12534 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012535
12536 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12537 if (hlua_states[thr])
12538 lua_close(hlua_states[thr]);
12539 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012540
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012541 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012542
Willy Tarreau0f143af2021-03-05 10:41:48 +010012543#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012544 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012545#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012546
12547 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012548}
12549
12550REGISTER_POST_DEINIT(hlua_deinit);
12551
Willy Tarreau80713382018-11-26 10:19:54 +010012552static void hlua_register_build_options(void)
12553{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012554 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012555
Willy Tarreaubb57d942016-12-21 19:04:56 +010012556 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12557 hap_register_build_opts(ptr, 1);
12558}
Willy Tarreau80713382018-11-26 10:19:54 +010012559
12560INITCALL0(STG_REGISTER, hlua_register_build_options);