blob: d630f6d2be3510b7aaefcdaf18a7434d43874640 [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 Faulet908628c2022-03-25 16:43:49 +010037#include <haproxy/conn_stream.h>
38#include <haproxy/cs_utils.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020039#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020040#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020041#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020042#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020043#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020044#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020045#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020047#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020048#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020049#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020050#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020051#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020052#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020053#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020054#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020055#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010056#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020057#include <haproxy/session.h>
William Lallemand30fcca12022-03-30 12:03:12 +020058#include <haproxy/ssl_ckch.h>
59#include <haproxy/ssl_sock.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020060#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020061#include <haproxy/stream.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020062#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020063#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020064#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020065#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020066#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020067#include <haproxy/xref.h>
68
Thierry FOURNIER380d0932015-01-23 14:27:52 +010069
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010070/* Lua uses longjmp to perform yield or throwing errors. This
71 * macro is used only for identifying the function that can
72 * not return because a longjmp is executed.
73 * __LJMP marks a prototype of hlua file that can use longjmp.
74 * WILL_LJMP() marks an lua function that will use longjmp.
75 * MAY_LJMP() marks an lua function that may use longjmp.
76 */
77#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020078#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010079#define MAY_LJMP(func) func
80
Thierry FOURNIERbabae282015-09-17 11:36:37 +020081/* This couple of function executes securely some Lua calls outside of
82 * the lua runtime environment. Each Lua call can return a longjmp
83 * if it encounter a memory error.
84 *
85 * Lua documentation extract:
86 *
87 * If an error happens outside any protected environment, Lua calls
88 * a panic function (see lua_atpanic) and then calls abort, thus
89 * exiting the host application. Your panic function can avoid this
90 * exit by never returning (e.g., doing a long jump to your own
91 * recovery point outside Lua).
92 *
93 * The panic function runs as if it were a message handler (see
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010094 * #2.3); in particular, the error message is at the top of the
Thierry FOURNIERbabae282015-09-17 11:36:37 +020095 * stack. However, there is no guarantee about stack space. To push
96 * anything on the stack, the panic function must first check the
Willy Tarreau3dfb7da2022-03-02 22:33:39 +010097 * available space (see #4.2).
Thierry FOURNIERbabae282015-09-17 11:36:37 +020098 *
99 * We must check all the Lua entry point. This includes:
100 * - The include/proto/hlua.h exported functions
101 * - the task wrapper function
102 * - The action wrapper function
103 * - The converters wrapper function
104 * - The sample-fetch wrapper functions
105 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500106 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800107 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200108 *
109 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
110 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
111 * because they must be exists in the program stack when the longjmp
112 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200113 *
114 * Note that the Lua processing is not really thread safe. It provides
115 * heavy system which consists to add our own lock function in the Lua
116 * code and recompile the library. This system will probably not accepted
117 * by maintainers of various distribs.
118 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500119 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200120 * quick looking on the Lua sources displays a lua_lock() a the start
121 * of function and a lua_unlock() at the end of the function. So I
122 * conclude that the Lua thread safe mode just perform a mutex around
123 * all execution. So I prefer to do this in the HAProxy code, it will be
124 * easier for distro maintainers.
125 *
126 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
127 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
128 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100130__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200131THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200133static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100135/* This is the chained list of struct hlua_function referenced
136 * for haproxy action, sample-fetches, converters, cli and
137 * applet bindings. It is used for a post-initialisation control.
138 */
139static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
140
Thierry Fournierc7492592020-11-28 23:57:24 +0100141/* This variable is used only during initialization to identify the Lua state
142 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
143 * states dedicated to each thread (in this case hlua_state_id==tid+1).
144 */
145static int hlua_state_id;
146
Thierry Fournier59f11be2020-11-29 00:37:41 +0100147/* This is a NULL-terminated list of lua file which are referenced to load per thread */
148static char **per_thread_load = NULL;
149
150lua_State *hlua_init_state(int thread_id);
151
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200152/* This function takes the Lua global lock. Keep this function's visibility
153 * global so that it can appear in stack dumps and performance profiles!
154 */
155void lua_take_global_lock()
156{
157 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
158}
159
160static inline void lua_drop_global_lock()
161{
162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
163}
164
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100165#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 ({ \
167 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100168 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200169 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200170 if (setjmp(safe_ljmp_env) != 0) { \
171 lua_atpanic(__L, hlua_panic_safe); \
172 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100173 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200174 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200175 } else { \
176 lua_atpanic(__L, hlua_panic_ljmp); \
177 ret = 1; \
178 } \
179 ret; \
180 })
181
182/* If we are the last function catching Lua errors, we
183 * must reset the panic function.
184 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100185#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 do { \
187 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100188 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200189 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200190 } while(0)
191
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100192#define SET_SAFE_LJMP(__HLUA) \
193 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
194
195#define RESET_SAFE_LJMP(__HLUA) \
196 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
197
198#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100199 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100200
201#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100202 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100203
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200204/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200205#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100206/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200208/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100209#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100210#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200211
Thierry Fournierafc63e22020-11-28 17:06:51 +0100212/* The main Lua execution context. The 0 index is the
213 * common state shared by all threads.
214 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100215static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100216
Christopher Fauletc404f112020-02-26 15:03:09 +0100217#define HLUA_FLT_CB_FINAL 0x00000001
218#define HLUA_FLT_CB_RETVAL 0x00000002
219#define HLUA_FLT_CB_ARG_CHN 0x00000004
220#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
221
Christopher Faulet9f55a502020-02-25 15:21:02 +0100222#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
223
Christopher Faulet69c581a2021-05-31 08:54:04 +0200224struct hlua_reg_filter {
225 char *name;
226 int flt_ref[MAX_THREADS + 1];
227 int fun_ref[MAX_THREADS + 1];
228 struct list l;
229};
230
231struct hlua_flt_config {
232 struct hlua_reg_filter *reg;
233 int ref[MAX_THREADS + 1];
234 char **args;
235};
236
237struct hlua_flt_ctx {
238 int ref; /* ref to the filter lua object */
239 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
240 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
241 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
242 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
243};
244
Willy Tarreau5321da92022-05-06 11:57:34 +0200245/* appctx context used by the cosockets */
246struct hlua_csk_ctx {
247 int connected;
248 struct xref xref; /* cross reference with the Lua object owner. */
249 struct list wake_on_read;
250 struct list wake_on_write;
251 struct appctx *appctx;
252 int die;
253};
254
Willy Tarreaubcda5f62022-05-03 18:13:39 +0200255/* used by registered CLI keywords */
256struct hlua_cli_ctx {
257 struct hlua *hlua;
258 struct task *task;
259 struct hlua_function *fcn;
260};
261
Christopher Faulet69c581a2021-05-31 08:54:04 +0200262DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
263
Christopher Faulet9f55a502020-02-25 15:21:02 +0100264static int hlua_filter_from_payload(struct filter *filter);
265
Christopher Faulet69c581a2021-05-31 08:54:04 +0200266/* This is the chained list of struct hlua_flt referenced
267 * for haproxy filters. It is used for a post-initialisation control.
268 */
269static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
270
271
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100272/* This is the memory pool containing struct lua for applets
273 * (including cli).
274 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100275DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100276
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100277/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100278static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100279static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100280#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100281static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100282#endif
283
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100284/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100285struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100286
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100287/* The following variables contains the reference of the different
288 * Lua classes. These references are useful for identify metadata
289 * associated with an object.
290 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100291static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100292static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100293static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100294static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100295static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100296static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100297static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200298static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200299static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200300static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200301static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100302static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100303
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100304/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200305 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100306 * short timeout. Lua linked with tasks doesn't have a timeout
307 * because a task may remain alive during all the haproxy execution.
308 */
309static unsigned int hlua_timeout_session = 4000; /* session timeout. */
310static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200311static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100312
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100313/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
314 * it is used for preventing infinite loops.
315 *
316 * I test the scheer with an infinite loop containing one incrementation
317 * and one test. I run this loop between 10 seconds, I raise a ceil of
318 * 710M loops from one interrupt each 9000 instructions, so I fix the value
319 * to one interrupt each 10 000 instructions.
320 *
321 * configured | Number of
322 * instructions | loops executed
323 * between two | in milions
324 * forced yields |
325 * ---------------+---------------
326 * 10 | 160
327 * 500 | 670
328 * 1000 | 680
329 * 5000 | 700
330 * 7000 | 700
331 * 8000 | 700
332 * 9000 | 710 <- ceil
333 * 10000 | 710
334 * 100000 | 710
335 * 1000000 | 710
336 *
337 */
338static unsigned int hlua_nb_instruction = 10000;
339
Willy Tarreaucdb53462020-12-02 12:12:00 +0100340/* Descriptor for the memory allocation state. The limit is pre-initialised to
341 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
342 * is replaced with ~0 during post_init after everything was loaded. This way
343 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
344 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100345 */
346struct hlua_mem_allocator {
347 size_t allocated;
348 size_t limit;
349};
350
Willy Tarreaucdb53462020-12-02 12:12:00 +0100351static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100352
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100353/* These functions converts types between HAProxy internal args or
354 * sample and LUA types. Another function permits to check if the
355 * LUA stack contains arguments according with an required ARG_T
356 * format.
357 */
358static int hlua_arg2lua(lua_State *L, const struct arg *arg);
359static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100360__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100361 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100362static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100363static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100364static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
365
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100366__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200367
Thierry Fournier59f11be2020-11-29 00:37:41 +0100368struct prepend_path {
369 struct list l;
370 char *type;
371 char *path;
372};
373
374static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
375
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200376#define SEND_ERR(__be, __fmt, __args...) \
377 do { \
378 send_log(__be, LOG_ERR, __fmt, ## __args); \
379 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100380 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200381 } while (0)
382
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100383static inline struct hlua_function *new_hlua_function()
384{
385 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100386 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100387
388 fcn = calloc(1, sizeof(*fcn));
389 if (!fcn)
390 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200391 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100392 for (i = 0; i < MAX_THREADS + 1; i++)
393 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100394 return fcn;
395}
396
Christopher Fauletdda44442021-04-12 14:05:43 +0200397static inline void release_hlua_function(struct hlua_function *fcn)
398{
399 if (!fcn)
400 return;
401 if (fcn->name)
402 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200403 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200404 ha_free(&fcn);
405}
406
Thierry Fournierc7492592020-11-28 23:57:24 +0100407/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
408static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
409{
410 if (fcn->function_ref[0] == -1)
411 return tid + 1;
412 return 0;
413}
414
Christopher Faulet69c581a2021-05-31 08:54:04 +0200415/* Create a new registered filter. Only its name is filled */
416static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
417{
418 struct hlua_reg_filter *reg_flt;
419 int i;
420
421 reg_flt = calloc(1, sizeof(*reg_flt));
422 if (!reg_flt)
423 return NULL;
424 reg_flt->name = strdup(name);
425 if (!reg_flt->name) {
426 free(reg_flt);
427 return NULL;
428 }
429 LIST_APPEND(&referenced_filters, &reg_flt->l);
430 for (i = 0; i < MAX_THREADS + 1; i++) {
431 reg_flt->flt_ref[i] = -1;
432 reg_flt->fun_ref[i] = -1;
433 }
434 return reg_flt;
435}
436
437/* Release a registered filter */
438static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
439{
440 if (!reg_flt)
441 return;
442 if (reg_flt->name)
443 ha_free(&reg_flt->name);
444 LIST_DELETE(&reg_flt->l);
445 ha_free(&reg_flt);
446}
447
448/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
449static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
450{
451 if (reg_flt->fun_ref[0] == -1)
452 return tid + 1;
453 return 0;
454}
455
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100456/* Used to check an Lua function type in the stack. It creates and
457 * returns a reference of the function. This function throws an
458 * error if the rgument is not a "function".
459 */
460__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
461{
462 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100463 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100464 WILL_LJMP(luaL_argerror(L, argno, msg));
465 }
466 lua_pushvalue(L, argno);
467 return luaL_ref(L, LUA_REGISTRYINDEX);
468}
469
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100470/* Used to check an Lua table type in the stack. It creates and
471 * returns a reference of the table. This function throws an
472 * error if the rgument is not a "table".
473 */
474__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
475{
476 if (!lua_istable(L, argno)) {
477 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
478 WILL_LJMP(luaL_argerror(L, argno, msg));
479 }
480 lua_pushvalue(L, argno);
481 return luaL_ref(L, LUA_REGISTRYINDEX);
482}
483
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200484/* Return the string that is of the top of the stack. */
485const char *hlua_get_top_error_string(lua_State *L)
486{
487 if (lua_gettop(L) < 1)
488 return "unknown error";
489 if (lua_type(L, -1) != LUA_TSTRING)
490 return "unknown error";
491 return lua_tostring(L, -1);
492}
493
Christopher Fauletd09cc512021-03-24 14:48:45 +0100494__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200495{
496 lua_Debug ar;
497 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200498 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200499
500 while (lua_getstack(L, level++, &ar)) {
501
502 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100503 if (b_data(msg))
504 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200505
506 /* Fill fields:
507 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
508 * 'l': fills in the field currentline;
509 * 'n': fills in the field name and namewhat;
510 * 't': fills in the field istailcall;
511 */
512 lua_getinfo(L, "Slnt", &ar);
513
514 /* Append code localisation */
515 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100516 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200517 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100518 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200519
520 /*
521 * Get function name
522 *
523 * if namewhat is no empty, name is defined.
524 * what contains "Lua" for Lua function, "C" for C function,
525 * or "main" for main code.
526 */
527 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100528 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200529
530 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100531 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200532
533 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100534 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200535
536 else /* nothing left... */
537 chunk_appendf(msg, "?");
538
539
540 /* Display tailed call */
541 if (ar.istailcall)
542 chunk_appendf(msg, " ...");
543 }
544
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200545 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200546}
547
548
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100549/* This function check the number of arguments available in the
550 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500551 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100552 */
553__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
554{
555 if (lua_gettop(L) == nb)
556 return;
557 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
558}
559
Mark Lakes22154b42018-01-29 14:38:40 -0800560/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100561 * and the line number where the error is encountered.
562 */
563static int hlua_pusherror(lua_State *L, const char *fmt, ...)
564{
565 va_list argp;
566 va_start(argp, fmt);
567 luaL_where(L, 1);
568 lua_pushvfstring(L, fmt, argp);
569 va_end(argp);
570 lua_concat(L, 2);
571 return 1;
572}
573
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100574/* This functions is used with sample fetch and converters. It
575 * converts the HAProxy configuration argument in a lua stack
576 * values.
577 *
578 * It takes an array of "arg", and each entry of the array is
579 * converted and pushed in the LUA stack.
580 */
581static int hlua_arg2lua(lua_State *L, const struct arg *arg)
582{
583 switch (arg->type) {
584 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100585 case ARGT_TIME:
586 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100587 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100588 break;
589
590 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200591 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 break;
593
594 case ARGT_IPV4:
595 case ARGT_IPV6:
596 case ARGT_MSK4:
597 case ARGT_MSK6:
598 case ARGT_FE:
599 case ARGT_BE:
600 case ARGT_TAB:
601 case ARGT_SRV:
602 case ARGT_USR:
603 case ARGT_MAP:
604 default:
605 lua_pushnil(L);
606 break;
607 }
608 return 1;
609}
610
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500611/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100612 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500613 * with sample fetch wrappers. The input arguments are given to the
614 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100615 */
616static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
617{
618 switch (lua_type(L, ud)) {
619
620 case LUA_TNUMBER:
621 case LUA_TBOOLEAN:
622 arg->type = ARGT_SINT;
623 arg->data.sint = lua_tointeger(L, ud);
624 break;
625
626 case LUA_TSTRING:
627 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200628 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200629 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200630 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200631 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100632 break;
633
634 case LUA_TUSERDATA:
635 case LUA_TNIL:
636 case LUA_TTABLE:
637 case LUA_TFUNCTION:
638 case LUA_TTHREAD:
639 case LUA_TLIGHTUSERDATA:
640 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200641 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 break;
643 }
644 return 1;
645}
646
647/* the following functions are used to convert a struct sample
648 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500649 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100650 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100651static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200653 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100654 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100655 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200656 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100657 break;
658
659 case SMP_T_BIN:
660 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200661 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662 break;
663
664 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200665 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100666 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
667 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
668 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
669 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
670 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
671 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
672 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
673 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
674 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200675 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100676 break;
677 default:
678 lua_pushnil(L);
679 break;
680 }
681 break;
682
683 case SMP_T_IPV4:
684 case SMP_T_IPV6:
685 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200686 if (sample_casts[smp->data.type][SMP_T_STR] &&
687 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200688 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100689 else
690 lua_pushnil(L);
691 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100692 default:
693 lua_pushnil(L);
694 break;
695 }
696 return 1;
697}
698
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100699/* the following functions are used to convert a struct sample
700 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500701 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100702 */
703static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
704{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200705 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100706
707 case SMP_T_BIN:
708 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200709 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100710 break;
711
712 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200713 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100714 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
715 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
716 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
717 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
718 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
719 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
720 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
721 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
722 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200723 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100724 break;
725 default:
726 lua_pushstring(L, "");
727 break;
728 }
729 break;
730
731 case SMP_T_SINT:
732 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100733 case SMP_T_IPV4:
734 case SMP_T_IPV6:
735 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200736 if (sample_casts[smp->data.type][SMP_T_STR] &&
737 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200738 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100739 else
740 lua_pushstring(L, "");
741 break;
742 default:
743 lua_pushstring(L, "");
744 break;
745 }
746 return 1;
747}
748
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100749/* the following functions are used to convert an Lua type in a
750 * struct sample. This is useful to provide data from a converter
751 * to the LUA code.
752 */
753static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
754{
755 switch (lua_type(L, ud)) {
756
757 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200758 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200759 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100760 break;
761
762
763 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200764 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200765 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100766 break;
767
768 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200769 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100770 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200771 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200772 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200773 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200774 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100775 break;
776
777 case LUA_TUSERDATA:
778 case LUA_TNIL:
779 case LUA_TTABLE:
780 case LUA_TFUNCTION:
781 case LUA_TTHREAD:
782 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200783 case LUA_TNONE:
784 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200785 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200786 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100787 break;
788 }
789 return 1;
790}
791
Ilya Shipitsind4259502020-04-08 01:07:56 +0500792/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800793 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100794 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100795 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500796 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200797 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100798 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100799__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100800 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100801{
802 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200803 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100804 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200805 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200806 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200807 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200808 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100809
810 idx = 0;
811 min_arg = ARGM(mask);
812 mask >>= ARGM_BITS;
813
814 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200815 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100816
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100817 /* Check for mandatory arguments. */
818 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100819 if (idx < min_arg) {
820
821 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200822 if (idx > 0) {
823 msg = "Mandatory argument expected";
824 goto error;
825 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100826
827 /* If first argument have a certain type, some default values
828 * may be used. See the function smp_resolve_args().
829 */
830 switch (mask & ARGT_MASK) {
831
832 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200833 if (!(p->cap & PR_CAP_FE)) {
834 msg = "Mandatory argument expected";
835 goto error;
836 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100837 argp[idx].data.prx = p;
838 argp[idx].type = ARGT_FE;
839 argp[idx+1].type = ARGT_STOP;
840 break;
841
842 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200843 if (!(p->cap & PR_CAP_BE)) {
844 msg = "Mandatory argument expected";
845 goto error;
846 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100847 argp[idx].data.prx = p;
848 argp[idx].type = ARGT_BE;
849 argp[idx+1].type = ARGT_STOP;
850 break;
851
852 case ARGT_TAB:
853 argp[idx].data.prx = p;
854 argp[idx].type = ARGT_TAB;
855 argp[idx+1].type = ARGT_STOP;
856 break;
857
858 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200859 msg = "Mandatory argument expected";
860 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100861 break;
862 }
863 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200864 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100865 }
866
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500867 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100868 if ((mask & ARGT_MASK) == ARGT_STOP &&
869 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200870 msg = "Last argument expected";
871 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100872 }
873
874 if ((mask & ARGT_MASK) == ARGT_STOP &&
875 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200876 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100877 }
878
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200879 /* Convert some argument types. All string in argp[] are for not
880 * duplicated yet.
881 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100882 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100883 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200884 if (argp[idx].type != ARGT_SINT) {
885 msg = "integer expected";
886 goto error;
887 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100888 argp[idx].type = ARGT_SINT;
889 break;
890
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100891 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200892 if (argp[idx].type != ARGT_SINT) {
893 msg = "integer expected";
894 goto error;
895 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200896 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100897 break;
898
899 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200900 if (argp[idx].type != ARGT_SINT) {
901 msg = "integer expected";
902 goto error;
903 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200904 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100905 break;
906
907 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200908 if (argp[idx].type != ARGT_STR) {
909 msg = "string expected";
910 goto error;
911 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200912 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200913 if (!argp[idx].data.prx) {
914 msg = "frontend doesn't exist";
915 goto error;
916 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100917 argp[idx].type = ARGT_FE;
918 break;
919
920 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200921 if (argp[idx].type != ARGT_STR) {
922 msg = "string expected";
923 goto error;
924 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200925 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200926 if (!argp[idx].data.prx) {
927 msg = "backend doesn't exist";
928 goto error;
929 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100930 argp[idx].type = ARGT_BE;
931 break;
932
933 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200934 if (argp[idx].type != ARGT_STR) {
935 msg = "string expected";
936 goto error;
937 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200938 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200939 if (!argp[idx].data.t) {
940 msg = "table doesn't exist";
941 goto error;
942 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100943 argp[idx].type = ARGT_TAB;
944 break;
945
946 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200947 if (argp[idx].type != ARGT_STR) {
948 msg = "string expected";
949 goto error;
950 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200951 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100952 if (sname) {
953 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200954 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200955 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200956 if (!px) {
957 msg = "backend doesn't exist";
958 goto error;
959 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100960 }
961 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200962 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100963 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100964 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100965 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200966 if (!argp[idx].data.srv) {
967 msg = "server doesn't exist";
968 goto error;
969 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100970 argp[idx].type = ARGT_SRV;
971 break;
972
973 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200974 if (argp[idx].type != ARGT_STR) {
975 msg = "string expected";
976 goto error;
977 }
978 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
979 msg = "invalid IPv4 address";
980 goto error;
981 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100982 argp[idx].type = ARGT_IPV4;
983 break;
984
985 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200986 if (argp[idx].type == ARGT_SINT)
987 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
988 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200989 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
990 msg = "invalid IPv4 mask";
991 goto error;
992 }
993 }
994 else {
995 msg = "integer or string expected";
996 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200997 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100998 argp[idx].type = ARGT_MSK4;
999 break;
1000
1001 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001002 if (argp[idx].type != ARGT_STR) {
1003 msg = "string expected";
1004 goto error;
1005 }
1006 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1007 msg = "invalid IPv6 address";
1008 goto error;
1009 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001010 argp[idx].type = ARGT_IPV6;
1011 break;
1012
1013 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001014 if (argp[idx].type == ARGT_SINT)
1015 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1016 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001017 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1018 msg = "invalid IPv6 mask";
1019 goto error;
1020 }
1021 }
1022 else {
1023 msg = "integer or string expected";
1024 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001025 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001026 argp[idx].type = ARGT_MSK6;
1027 break;
1028
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001029 case ARGT_REG:
1030 if (argp[idx].type != ARGT_STR) {
1031 msg = "string expected";
1032 goto error;
1033 }
1034 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1035 if (!reg) {
1036 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1037 argp[idx].data.str.area, err);
1038 free(err);
1039 goto error;
1040 }
1041 argp[idx].type = ARGT_REG;
1042 argp[idx].data.reg = reg;
1043 break;
1044
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001045 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001046 if (argp[idx].type != ARGT_STR) {
1047 msg = "string expected";
1048 goto error;
1049 }
1050 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001051 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001052 ul = p->uri_auth->userlist;
1053 else
1054 ul = auth_find_userlist(argp[idx].data.str.area);
1055
1056 if (!ul) {
1057 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1058 goto error;
1059 }
1060 argp[idx].type = ARGT_USR;
1061 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001062 break;
1063
1064 case ARGT_STR:
1065 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1066 msg = "unable to duplicate string arg";
1067 goto error;
1068 }
1069 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001070 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001071
Christopher Fauletd25d9262020-08-06 11:04:46 +02001072 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001073 msg = "type not yet supported";
1074 goto error;
1075 break;
1076
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001077 }
1078
1079 /* Check for type of argument. */
1080 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001081 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1082 arg_type_names[(mask & ARGT_MASK)],
1083 arg_type_names[argp[idx].type & ARGT_MASK]);
1084 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001085 }
1086
1087 /* Next argument. */
1088 mask >>= ARGT_BITS;
1089 idx++;
1090 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001091 return 0;
1092
1093 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001094 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001095 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1096 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001097}
1098
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001099/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001100 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001101 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001102 *
1103 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001104 * - hlua_sethlua : create the association between hlua context and lua_state.
1105 */
1106static inline struct hlua *hlua_gethlua(lua_State *L)
1107{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001108 struct hlua **hlua = lua_getextraspace(L);
1109 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001110}
1111static inline void hlua_sethlua(struct hlua *hlua)
1112{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001113 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1114 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001115}
1116
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001117/* This function is used to send logs. It try to send on screen (stderr)
1118 * and on the default syslog server.
1119 */
1120static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1121{
1122 struct tm tm;
1123 char *p;
1124
1125 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001126 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001127 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001128 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001129 /* Break the message if exceed the buffer size. */
1130 *(p-4) = ' ';
1131 *(p-3) = '.';
1132 *(p-2) = '.';
1133 *(p-1) = '.';
1134 break;
1135 }
Willy Tarreau90807112020-02-25 08:16:33 +01001136 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001137 *p = *msg;
1138 else
1139 *p = '.';
1140 }
1141 *p = '\0';
1142
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001143 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001144 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001145 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1146 return;
1147
Willy Tarreaua678b432015-08-28 10:14:59 +02001148 get_localtime(date.tv_sec, &tm);
1149 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001150 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001151 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001152 fflush(stderr);
1153 }
1154}
1155
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001156/* This function just ensure that the yield will be always
1157 * returned with a timeout and permit to set some flags
1158 */
1159__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001160 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001161{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001162 struct hlua *hlua;
1163
1164 /* Get hlua struct, or NULL if we execute from main lua state */
1165 hlua = hlua_gethlua(L);
1166 if (!hlua) {
1167 return;
1168 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001169
1170 /* Set the wake timeout. If timeout is required, we set
1171 * the expiration time.
1172 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001173 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001174
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001175 hlua->flags |= flags;
1176
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001177 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001178 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001179}
1180
Willy Tarreau87b09662015-04-03 00:22:06 +02001181/* This function initialises the Lua environment stored in the stream.
1182 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001183 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001184 *
1185 * This function is particular. it initialises a new Lua thread. If the
1186 * initialisation fails (example: out of memory error), the lua function
1187 * throws an error (longjmp).
1188 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001189 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001190 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001191 * threads appear, the safe environment set a lock to ensure only one
1192 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001193 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001194 *
1195 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001196 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001197 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001198 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001199 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001200 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001201 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001202 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001203int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001204{
1205 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001206 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001207 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001208 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001209 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001210 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001211 if (!already_safe) {
1212 if (!SET_SAFE_LJMP_PARENT(lua)) {
1213 lua->Tref = LUA_REFNIL;
1214 return 0;
1215 }
1216 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001217 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001218 if (!lua->T) {
1219 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001220 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001221 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001222 return 0;
1223 }
1224 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001225 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001226 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001227 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001228 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001229 return 1;
1230}
1231
Willy Tarreau87b09662015-04-03 00:22:06 +02001232/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001233 * is destroyed. The destroy also the memory context. The struct "lua"
1234 * is not freed.
1235 */
1236void hlua_ctx_destroy(struct hlua *lua)
1237{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001238 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001239 return;
1240
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001241 if (!lua->T)
1242 goto end;
1243
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001244 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001245 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001246
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001247 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001248 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001249 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001250 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001251
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001252 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001253 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001254 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001255 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001256 /* Forces a garbage collecting process. If the Lua program is finished
1257 * without error, we run the GC on the thread pointer. Its freed all
1258 * the unused memory.
1259 * If the thread is finnish with an error or is currently yielded,
1260 * it seems that the GC applied on the thread doesn't clean anything,
1261 * so e run the GC on the main thread.
1262 * NOTE: maybe this action locks all the Lua threads untiml the en of
1263 * the garbage collection.
1264 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001265 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001266 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001267 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001268 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001269 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001270 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001271
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001272 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001273
1274end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001275 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001276}
1277
1278/* This function is used to restore the Lua context when a coroutine
1279 * fails. This function copy the common memory between old coroutine
1280 * and the new coroutine. The old coroutine is destroyed, and its
1281 * replaced by the new coroutine.
1282 * If the flag "keep_msg" is set, the last entry of the old is assumed
1283 * as string error message and it is copied in the new stack.
1284 */
1285static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1286{
1287 lua_State *T;
1288 int new_ref;
1289
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001290 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001291 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001292 if (!T)
1293 return 0;
1294
1295 /* Copy last error message. */
1296 if (keep_msg)
1297 lua_xmove(lua->T, T, 1);
1298
1299 /* Copy data between the coroutines. */
1300 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1301 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001302 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001303
1304 /* Destroy old data. */
1305 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1306
1307 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001308 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001309
1310 /* Fill the struct with the new coroutine values. */
1311 lua->Mref = new_ref;
1312 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001313 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001314
1315 /* Set context. */
1316 hlua_sethlua(lua);
1317
1318 return 1;
1319}
1320
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001321void hlua_hook(lua_State *L, lua_Debug *ar)
1322{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001323 struct hlua *hlua;
1324
1325 /* Get hlua struct, or NULL if we execute from main lua state */
1326 hlua = hlua_gethlua(L);
1327 if (!hlua)
1328 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001329
1330 /* Lua cannot yield when its returning from a function,
1331 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001332 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001333 */
1334 if (lua_gethookmask(L) & LUA_MASKRET) {
1335 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1336 return;
1337 }
1338
1339 /* restore the interrupt condition. */
1340 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1341
1342 /* If we interrupt the Lua processing in yieldable state, we yield.
1343 * If the state is not yieldable, trying yield causes an error.
1344 */
1345 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001346 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001347
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001348 /* If we cannot yield, update the clock and check the timeout. */
Willy Tarreau55542642021-10-08 09:33:24 +02001349 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001350 hlua->run_time += now_ms - hlua->start_time;
1351 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001352 lua_pushfstring(L, "execution timeout");
1353 WILL_LJMP(lua_error(L));
1354 }
1355
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001356 /* Update the start time. */
1357 hlua->start_time = now_ms;
1358
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001359 /* Try to interrupt the process at the end of the current
1360 * unyieldable function.
1361 */
1362 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001363}
1364
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001365/* This function start or resumes the Lua stack execution. If the flag
1366 * "yield_allowed" if no set and the LUA stack execution returns a yield
1367 * The function return an error.
1368 *
1369 * The function can returns 4 values:
1370 * - HLUA_E_OK : The execution is terminated without any errors.
1371 * - HLUA_E_AGAIN : The execution must continue at the next associated
1372 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001373 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001374 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001375 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001376 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001377 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001378 * LUA code.
1379 */
1380static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1381{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001382#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1383 int nres;
1384#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001385 int ret;
1386 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001387 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001388
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001389 /* Initialise run time counter. */
1390 if (!HLUA_IS_RUNNING(lua))
1391 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001392
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001393 /* Lock the whole Lua execution. This lock must be before the
1394 * label "resume_execution".
1395 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001396 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001397 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001398
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001399resume_execution:
1400
1401 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1402 * instructions. it is used for preventing infinite loops.
1403 */
1404 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1405
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001406 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001407 HLUA_SET_RUN(lua);
1408 HLUA_CLR_CTRLYIELD(lua);
1409 HLUA_CLR_WAKERESWR(lua);
1410 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001411 HLUA_CLR_NOYIELD(lua);
1412 if (!yield_allowed)
1413 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001414
Christopher Fauletbc275a92020-02-26 14:55:16 +01001415 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001416 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001417 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001418
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001419 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001420#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001421 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001422#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001423 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001424#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001425 switch (ret) {
1426
1427 case LUA_OK:
1428 ret = HLUA_E_OK;
1429 break;
1430
1431 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001432 /* Check if the execution timeout is expired. It it is the case, we
1433 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001434 */
Willy Tarreau55542642021-10-08 09:33:24 +02001435 clock_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001436 lua->run_time += now_ms - lua->start_time;
1437 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001438 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001439 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001440 break;
1441 }
1442 /* Process the forced yield. if the general yield is not allowed or
1443 * if no task were associated this the current Lua execution
1444 * coroutine, we resume the execution. Else we want to return in the
1445 * scheduler and we want to be waked up again, to continue the
1446 * current Lua execution. So we schedule our own task.
1447 */
1448 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001449 if (!yield_allowed || !lua->task)
1450 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001451 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001452 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001453 if (!yield_allowed) {
1454 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001455 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001456 break;
1457 }
1458 ret = HLUA_E_AGAIN;
1459 break;
1460
1461 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001462
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001463 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001464 * because the errors ares the only one mean to return immediately
1465 * from and lua execution.
1466 */
1467 if (lua->flags & HLUA_EXIT) {
1468 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001469 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001470 break;
1471 }
1472
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001473 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001474 if (!lua_checkstack(lua->T, 1)) {
1475 ret = HLUA_E_ERR;
1476 break;
1477 }
1478 msg = lua_tostring(lua->T, -1);
1479 lua_settop(lua->T, 0); /* Empty the stack. */
1480 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001481 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001482 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001483 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001484 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001485 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001486 ret = HLUA_E_ERRMSG;
1487 break;
1488
1489 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001490 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001491 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001492 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001493 break;
1494
1495 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001496 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001497 if (!lua_checkstack(lua->T, 1)) {
1498 ret = HLUA_E_ERR;
1499 break;
1500 }
1501 msg = lua_tostring(lua->T, -1);
1502 lua_settop(lua->T, 0); /* Empty the stack. */
1503 lua_pop(lua->T, 1);
1504 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001505 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001506 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001507 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001508 ret = HLUA_E_ERRMSG;
1509 break;
1510
1511 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001512 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001513 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001514 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001515 break;
1516 }
1517
1518 switch (ret) {
1519 case HLUA_E_AGAIN:
1520 break;
1521
1522 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001523 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001524 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001525 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001526 break;
1527
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001528 case HLUA_E_ETMOUT:
1529 case HLUA_E_NOMEM:
1530 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001531 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001532 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001533 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001534 hlua_ctx_renew(lua, 0);
1535 break;
1536
1537 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001538 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001539 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001540 break;
1541 }
1542
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001543 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001544 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001545 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001546
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001547 return ret;
1548}
1549
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001550/* This function exit the current code. */
1551__LJMP static int hlua_done(lua_State *L)
1552{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001553 struct hlua *hlua;
1554
1555 /* Get hlua struct, or NULL if we execute from main lua state */
1556 hlua = hlua_gethlua(L);
1557 if (!hlua)
1558 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001559
1560 hlua->flags |= HLUA_EXIT;
1561 WILL_LJMP(lua_error(L));
1562
1563 return 0;
1564}
1565
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001566/* This function is an LUA binding. It provides a function
1567 * for deleting ACL from a referenced ACL file.
1568 */
1569__LJMP static int hlua_del_acl(lua_State *L)
1570{
1571 const char *name;
1572 const char *key;
1573 struct pat_ref *ref;
1574
1575 MAY_LJMP(check_args(L, 2, "del_acl"));
1576
1577 name = MAY_LJMP(luaL_checkstring(L, 1));
1578 key = MAY_LJMP(luaL_checkstring(L, 2));
1579
1580 ref = pat_ref_lookup(name);
1581 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001582 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001583
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001584 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001585 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001586 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001587 return 0;
1588}
1589
1590/* This function is an LUA binding. It provides a function
1591 * for deleting map entry from a referenced map file.
1592 */
1593static int hlua_del_map(lua_State *L)
1594{
1595 const char *name;
1596 const char *key;
1597 struct pat_ref *ref;
1598
1599 MAY_LJMP(check_args(L, 2, "del_map"));
1600
1601 name = MAY_LJMP(luaL_checkstring(L, 1));
1602 key = MAY_LJMP(luaL_checkstring(L, 2));
1603
1604 ref = pat_ref_lookup(name);
1605 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001606 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001607
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001608 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001609 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001610 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001611 return 0;
1612}
1613
1614/* This function is an LUA binding. It provides a function
1615 * for adding ACL pattern from a referenced ACL file.
1616 */
1617static int hlua_add_acl(lua_State *L)
1618{
1619 const char *name;
1620 const char *key;
1621 struct pat_ref *ref;
1622
1623 MAY_LJMP(check_args(L, 2, "add_acl"));
1624
1625 name = MAY_LJMP(luaL_checkstring(L, 1));
1626 key = MAY_LJMP(luaL_checkstring(L, 2));
1627
1628 ref = pat_ref_lookup(name);
1629 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001630 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001631
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001632 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001633 if (pat_ref_find_elt(ref, key) == NULL)
1634 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001635 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001636 return 0;
1637}
1638
1639/* This function is an LUA binding. It provides a function
1640 * for setting map pattern and sample from a referenced map
1641 * file.
1642 */
1643static int hlua_set_map(lua_State *L)
1644{
1645 const char *name;
1646 const char *key;
1647 const char *value;
1648 struct pat_ref *ref;
1649
1650 MAY_LJMP(check_args(L, 3, "set_map"));
1651
1652 name = MAY_LJMP(luaL_checkstring(L, 1));
1653 key = MAY_LJMP(luaL_checkstring(L, 2));
1654 value = MAY_LJMP(luaL_checkstring(L, 3));
1655
1656 ref = pat_ref_lookup(name);
1657 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001658 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001659
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001660 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001661 if (pat_ref_find_elt(ref, key) != NULL)
1662 pat_ref_set(ref, key, value, NULL);
1663 else
1664 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001665 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001666 return 0;
1667}
1668
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001669/* A class is a lot of memory that contain data. This data can be a table,
1670 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001671 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001672 * the name of the object (_G[<name>] = <metable> ).
1673 *
1674 * A metable is a table that modify the standard behavior of a standard
1675 * access to the associated data. The entries of this new metatable are
1676 * defined as is:
1677 *
1678 * http://lua-users.org/wiki/MetatableEvents
1679 *
1680 * __index
1681 *
1682 * we access an absent field in a table, the result is nil. This is
1683 * true, but it is not the whole truth. Actually, such access triggers
1684 * the interpreter to look for an __index metamethod: If there is no
1685 * such method, as usually happens, then the access results in nil;
1686 * otherwise, the metamethod will provide the result.
1687 *
1688 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1689 * the key does not appear in the table, but the metatable has an __index
1690 * property:
1691 *
1692 * - if the value is a function, the function is called, passing in the
1693 * table and the key; the return value of that function is returned as
1694 * the result.
1695 *
1696 * - if the value is another table, the value of the key in that table is
1697 * asked for and returned (and if it doesn't exist in that table, but that
1698 * table's metatable has an __index property, then it continues on up)
1699 *
1700 * - Use "rawget(myTable,key)" to skip this metamethod.
1701 *
1702 * http://www.lua.org/pil/13.4.1.html
1703 *
1704 * __newindex
1705 *
1706 * Like __index, but control property assignment.
1707 *
1708 * __mode - Control weak references. A string value with one or both
1709 * of the characters 'k' and 'v' which specifies that the the
1710 * keys and/or values in the table are weak references.
1711 *
1712 * __call - Treat a table like a function. When a table is followed by
1713 * parenthesis such as "myTable( 'foo' )" and the metatable has
1714 * a __call key pointing to a function, that function is invoked
1715 * (passing any specified arguments) and the return value is
1716 * returned.
1717 *
1718 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1719 * called, if the metatable for myTable has a __metatable
1720 * key, the value of that key is returned instead of the
1721 * actual metatable.
1722 *
1723 * __tostring - Control string representation. When the builtin
1724 * "tostring( myTable )" function is called, if the metatable
1725 * for myTable has a __tostring property set to a function,
1726 * that function is invoked (passing myTable to it) and the
1727 * return value is used as the string representation.
1728 *
1729 * __len - Control table length. When the table length is requested using
1730 * the length operator ( '#' ), if the metatable for myTable has
1731 * a __len key pointing to a function, that function is invoked
1732 * (passing myTable to it) and the return value used as the value
1733 * of "#myTable".
1734 *
1735 * __gc - Userdata finalizer code. When userdata is set to be garbage
1736 * collected, if the metatable has a __gc field pointing to a
1737 * function, that function is first invoked, passing the userdata
1738 * to it. The __gc metamethod is not called for tables.
1739 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1740 *
1741 * Special metamethods for redefining standard operators:
1742 * http://www.lua.org/pil/13.1.html
1743 *
1744 * __add "+"
1745 * __sub "-"
1746 * __mul "*"
1747 * __div "/"
1748 * __unm "!"
1749 * __pow "^"
1750 * __concat ".."
1751 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001752 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001753 * http://www.lua.org/pil/13.2.html
1754 *
1755 * __eq "=="
1756 * __lt "<"
1757 * __le "<="
1758 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001759
1760/*
1761 *
1762 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001763 * Class Map
1764 *
1765 *
1766 */
1767
1768/* Returns a struct hlua_map if the stack entry "ud" is
1769 * a class session, otherwise it throws an error.
1770 */
1771__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1772{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001773 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001774}
1775
1776/* This function is the map constructor. It don't need
1777 * the class Map object. It creates and return a new Map
1778 * object. It must be called only during "body" or "init"
1779 * context because it process some filesystem accesses.
1780 */
1781__LJMP static int hlua_map_new(struct lua_State *L)
1782{
1783 const char *fn;
1784 int match = PAT_MATCH_STR;
1785 struct sample_conv conv;
1786 const char *file = "";
1787 int line = 0;
1788 lua_Debug ar;
1789 char *err = NULL;
1790 struct arg args[2];
1791
1792 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1793 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1794
1795 fn = MAY_LJMP(luaL_checkstring(L, 1));
1796
1797 if (lua_gettop(L) >= 2) {
1798 match = MAY_LJMP(luaL_checkinteger(L, 2));
1799 if (match < 0 || match >= PAT_MATCH_NUM)
1800 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1801 }
1802
1803 /* Get Lua filename and line number. */
1804 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1805 lua_getinfo(L, "Sl", &ar); /* get info about it */
1806 if (ar.currentline > 0) { /* is there info? */
1807 file = ar.short_src;
1808 line = ar.currentline;
1809 }
1810 }
1811
1812 /* fill fake sample_conv struct. */
1813 conv.kw = ""; /* unused. */
1814 conv.process = NULL; /* unused. */
1815 conv.arg_mask = 0; /* unused. */
1816 conv.val_args = NULL; /* unused. */
1817 conv.out_type = SMP_T_STR;
1818 conv.private = (void *)(long)match;
1819 switch (match) {
1820 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1821 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1822 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1823 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1824 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1825 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1826 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001827 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001828 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1829 default:
1830 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1831 }
1832
1833 /* fill fake args. */
1834 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001835 args[0].data.str.area = strdup(fn);
1836 args[0].data.str.data = strlen(fn);
1837 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001838 args[1].type = ARGT_STOP;
1839
1840 /* load the map. */
1841 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001842 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001843 * free the err variable.
1844 */
1845 luaL_where(L, 1);
1846 lua_pushfstring(L, "'new': %s.", err);
1847 lua_concat(L, 2);
1848 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001849 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001850 WILL_LJMP(lua_error(L));
1851 }
1852
1853 /* create the lua object. */
1854 lua_newtable(L);
1855 lua_pushlightuserdata(L, args[0].data.map);
1856 lua_rawseti(L, -2, 0);
1857
1858 /* Pop a class Map metatable and affect it to the userdata. */
1859 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1860 lua_setmetatable(L, -2);
1861
1862
1863 return 1;
1864}
1865
1866__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1867{
1868 struct map_descriptor *desc;
1869 struct pattern *pat;
1870 struct sample smp;
1871
1872 MAY_LJMP(check_args(L, 2, "lookup"));
1873 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001874 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001875 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001876 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001877 }
1878 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001879 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001880 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001881 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 +01001882 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001883 }
1884
1885 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001886 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001887 if (str)
1888 lua_pushstring(L, "");
1889 else
1890 lua_pushnil(L);
1891 return 1;
1892 }
1893
1894 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001895 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001896 return 1;
1897}
1898
1899__LJMP static int hlua_map_lookup(struct lua_State *L)
1900{
1901 return _hlua_map_lookup(L, 0);
1902}
1903
1904__LJMP static int hlua_map_slookup(struct lua_State *L)
1905{
1906 return _hlua_map_lookup(L, 1);
1907}
1908
1909/*
1910 *
1911 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912 * Class Socket
1913 *
1914 *
1915 */
1916
1917__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1918{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001919 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001920}
1921
1922/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001923 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001924 * received.
1925 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001926static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001927{
Willy Tarreau5321da92022-05-06 11:57:34 +02001928 struct hlua_csk_ctx *ctx = appctx->svcctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01001929 struct conn_stream *cs = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001930
Willy Tarreau5321da92022-05-06 11:57:34 +02001931 if (ctx->die) {
Christopher Fauletda098e62022-03-31 17:44:45 +02001932 cs_shutw(cs);
1933 cs_shutr(cs);
Christopher Faulet908628c2022-03-25 16:43:49 +01001934 cs_ic(cs)->flags |= CF_READ_NULL;
Willy Tarreau5321da92022-05-06 11:57:34 +02001935 notification_wake(&ctx->wake_on_read);
1936 notification_wake(&ctx->wake_on_write);
Christopher Faulet908628c2022-03-25 16:43:49 +01001937 stream_shutdown(__cs_strm(cs), SF_ERR_KILLED);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001938 }
1939
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001940 /* If we can't write, wakeup the pending write signals. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001941 if (channel_output_closed(cs_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001942 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001943
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001944 /* If we can't read, wakeup the pending read signals. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001945 if (channel_input_closed(cs_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001946 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001947
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001948 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001949 * to be notified whenever the connection completes.
1950 */
Christopher Faulet62e75742022-03-31 09:16:34 +02001951 if (cs_opposite(cs)->state < CS_ST_EST) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001952 cs_cant_get(cs);
1953 cs_rx_conn_blk(cs);
1954 cs_rx_endp_more(cs);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001955 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001956 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957
1958 /* This function is called after the connect. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001959 ctx->connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001960
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001961 /* Wake the tasks which wants to write if the buffer have available space. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001962 if (channel_may_recv(cs_ic(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001963 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964
1965 /* Wake the tasks which wants to read if the buffer contains data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01001966 if (!channel_is_empty(cs_oc(cs)))
Willy Tarreau5321da92022-05-06 11:57:34 +02001967 notification_wake(&ctx->wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001968
1969 /* Some data were injected in the buffer, notify the stream
1970 * interface.
1971 */
Christopher Faulet908628c2022-03-25 16:43:49 +01001972 if (!channel_is_empty(cs_ic(cs)))
Christopher Faulet13045f02022-04-01 14:23:38 +02001973 cs_update(cs);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001974
1975 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001976 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001977 */
Willy Tarreau5321da92022-05-06 11:57:34 +02001978 if (notification_registered(&ctx->wake_on_write))
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001979 cs_rx_endp_more(cs);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001980}
1981
Willy Tarreau87b09662015-04-03 00:22:06 +02001982/* This function is called when the "struct stream" is destroyed.
1983 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984 * Wake all the pending signals.
1985 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001986static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001987{
Willy Tarreau5321da92022-05-06 11:57:34 +02001988 struct hlua_csk_ctx *ctx = appctx->svcctx;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001989 struct xref *peer;
1990
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001991 /* Remove my link in the original object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001992 peer = xref_get_peer_and_lock(&ctx->xref);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001993 if (peer)
Willy Tarreau5321da92022-05-06 11:57:34 +02001994 xref_disconnect(&ctx->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995
1996 /* Wake all the task waiting for me. */
Willy Tarreau5321da92022-05-06 11:57:34 +02001997 notification_wake(&ctx->wake_on_read);
1998 notification_wake(&ctx->wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001999}
2000
2001/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002002 * uses this object. If the stream does not exists, just quit.
2003 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002004 * pending signal can rest in the read and write lists. destroy
2005 * it.
2006 */
2007__LJMP static int hlua_socket_gc(lua_State *L)
2008{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002009 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002010 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002011 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002013 MAY_LJMP(check_args(L, 1, "__gc"));
2014
2015 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002016 peer = xref_get_peer_and_lock(&socket->xref);
2017 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018 return 0;
Willy Tarreau5321da92022-05-06 11:57:34 +02002019
2020 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002021
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002022 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002023 ctx->die = 1;
2024 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002025
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002026 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002027 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002028 return 0;
2029}
2030
2031/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002032 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002033 */
sada05ed3302018-05-11 11:48:18 -07002034__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002036 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002037 struct hlua_csk_ctx *ctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002038 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002039 struct hlua *hlua;
2040
2041 /* Get hlua struct, or NULL if we execute from main lua state */
2042 hlua = hlua_gethlua(L);
2043 if (!hlua)
2044 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002046 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002047
2048 /* Check if we run on the same thread than the xreator thread.
2049 * We cannot access to the socket if the thread is different.
2050 */
2051 if (socket->tid != tid)
2052 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2053
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002054 peer = xref_get_peer_and_lock(&socket->xref);
2055 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002056 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002057
2058 hlua->gc_count--;
Willy Tarreau5321da92022-05-06 11:57:34 +02002059 ctx = container_of(peer, struct hlua_csk_ctx, xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002060
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002061 /* Set the flag which destroy the session. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002062 ctx->die = 1;
2063 appctx_wakeup(ctx->appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002064
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002065 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002066 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067 return 0;
2068}
2069
sada05ed3302018-05-11 11:48:18 -07002070/* The close function calls close_helper.
2071 */
2072__LJMP static int hlua_socket_close(lua_State *L)
2073{
2074 MAY_LJMP(check_args(L, 1, "close"));
2075 return hlua_socket_close_helper(L);
2076}
2077
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078/* This Lua function assumes that the stack contain three parameters.
2079 * 1 - USERDATA containing a struct socket
2080 * 2 - INTEGER with values of the macro defined below
2081 * If the integer is -1, we must read at most one line.
2082 * If the integer is -2, we ust read all the data until the
2083 * end of the stream.
2084 * If the integer is positive value, we must read a number of
2085 * bytes corresponding to this value.
2086 */
2087#define HLSR_READ_LINE (-1)
2088#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002089__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090{
2091 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2092 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002093 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002094 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002096 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002098 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002099 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002100 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002101 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002102 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002103 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002104 struct stream *s;
2105 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002106 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002108 /* Get hlua struct, or NULL if we execute from main lua state */
2109 hlua = hlua_gethlua(L);
2110
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111 /* Check if this lua stack is schedulable. */
2112 if (!hlua || !hlua->task)
2113 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2114 "'frontend', 'backend' or 'task'"));
2115
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002116 /* Check if we run on the same thread than the xreator thread.
2117 * We cannot access to the socket if the thread is different.
2118 */
2119 if (socket->tid != tid)
2120 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2121
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002122 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002123 peer = xref_get_peer_and_lock(&socket->xref);
2124 if (!peer)
2125 goto no_peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002126
2127 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2128 appctx = csk_ctx->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002129 s = __cs_strm(appctx->owner);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002130
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002131 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002132 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002133 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002134 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002135 if (nblk < 0) /* Connection close. */
2136 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002137 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002138 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002139
2140 /* remove final \r\n. */
2141 if (nblk == 1) {
2142 if (blk1[len1-1] == '\n') {
2143 len1--;
2144 skip_at_end++;
2145 if (blk1[len1-1] == '\r') {
2146 len1--;
2147 skip_at_end++;
2148 }
2149 }
2150 }
2151 else {
2152 if (blk2[len2-1] == '\n') {
2153 len2--;
2154 skip_at_end++;
2155 if (blk2[len2-1] == '\r') {
2156 len2--;
2157 skip_at_end++;
2158 }
2159 }
2160 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 }
2162
2163 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002165 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002166 if (nblk < 0) /* Connection close. */
2167 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002168 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169 goto connection_empty;
2170 }
2171
2172 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002174 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175 if (nblk < 0) /* Connection close. */
2176 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002177 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178 goto connection_empty;
2179
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002180 missing_bytes = wanted - socket->b.n;
2181 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002183 len1 = missing_bytes;
2184 } if (nblk == 2 && len1 + len2 > missing_bytes)
2185 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 }
2187
2188 len = len1;
2189
2190 luaL_addlstring(&socket->b, blk1, len1);
2191 if (nblk == 2) {
2192 len += len2;
2193 luaL_addlstring(&socket->b, blk2, len2);
2194 }
2195
2196 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002197 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002198
2199 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002200 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002201
2202 /* If the pattern reclaim to read all the data
2203 * in the connection, got out.
2204 */
2205 if (wanted == HLSR_READ_ALL)
2206 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002207 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208 goto connection_empty;
2209
2210 /* Return result. */
2211 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002212 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002213 return 1;
2214
2215connection_closed:
2216
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002217 xref_unlock(&socket->xref, peer);
2218
2219no_peer:
2220
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221 /* If the buffer containds data. */
2222 if (socket->b.n > 0) {
2223 luaL_pushresult(&socket->b);
2224 return 1;
2225 }
2226 lua_pushnil(L);
2227 lua_pushstring(L, "connection closed.");
2228 return 2;
2229
2230connection_empty:
2231
Willy Tarreau5321da92022-05-06 11:57:34 +02002232 if (!notification_new(&hlua->com, &csk_ctx->wake_on_read, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002233 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002234 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002235 }
2236 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002237 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 return 0;
2239}
2240
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002241/* This Lua function gets two parameters. The first one can be string
2242 * or a number. If the string is "*l", the user requires one line. If
2243 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244 * If the value is a number, the user require a number of bytes equal
2245 * to the value. The default value is "*l" (a line).
2246 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002247 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002248 * integer takes this values:
2249 * -1 : read a line
2250 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002251 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002253 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002254 * concatenated with the read data.
2255 */
2256__LJMP static int hlua_socket_receive(struct lua_State *L)
2257{
2258 int wanted = HLSR_READ_LINE;
2259 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002260 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261 char *error;
2262 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002263 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002264
2265 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2266 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2267
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002268 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002269
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002270 /* Check if we run on the same thread than the xreator thread.
2271 * We cannot access to the socket if the thread is different.
2272 */
2273 if (socket->tid != tid)
2274 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2275
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276 /* check for pattern. */
2277 if (lua_gettop(L) >= 2) {
2278 type = lua_type(L, 2);
2279 if (type == LUA_TSTRING) {
2280 pattern = lua_tostring(L, 2);
2281 if (strcmp(pattern, "*a") == 0)
2282 wanted = HLSR_READ_ALL;
2283 else if (strcmp(pattern, "*l") == 0)
2284 wanted = HLSR_READ_LINE;
2285 else {
2286 wanted = strtoll(pattern, &error, 10);
2287 if (*error != '\0')
2288 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2289 }
2290 }
2291 else if (type == LUA_TNUMBER) {
2292 wanted = lua_tointeger(L, 2);
2293 if (wanted < 0)
2294 WILL_LJMP(luaL_error(L, "Unsupported size."));
2295 }
2296 }
2297
2298 /* Set pattern. */
2299 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002300
2301 /* Check if we would replace the top by itself. */
2302 if (lua_gettop(L) != 2)
2303 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304
Christopher Fauletc31b2002021-05-03 10:11:13 +02002305 /* Save index of the top of the stack because since buffers are used, it
2306 * may change
2307 */
2308 lastarg = lua_gettop(L);
2309
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002310 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 luaL_buffinit(L, &socket->b);
2312
2313 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002314 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 if (lua_type(L, 3) != LUA_TSTRING)
2316 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2317 pattern = lua_tolstring(L, 3, &len);
2318 luaL_addlstring(&socket->b, pattern, len);
2319 }
2320
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002321 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322}
2323
2324/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002325 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002327static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328{
2329 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002330 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002331 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332 struct appctx *appctx;
2333 size_t buf_len;
2334 const char *buf;
2335 int len;
2336 int send_len;
2337 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002338 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002339 struct stream *s;
Christopher Faulet908628c2022-03-25 16:43:49 +01002340 struct conn_stream *cs;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002342 /* Get hlua struct, or NULL if we execute from main lua state */
2343 hlua = hlua_gethlua(L);
2344
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345 /* Check if this lua stack is schedulable. */
2346 if (!hlua || !hlua->task)
2347 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2348 "'frontend', 'backend' or 'task'"));
2349
2350 /* Get object */
2351 socket = MAY_LJMP(hlua_checksocket(L, 1));
2352 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002353 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002354
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002355 /* Check if we run on the same thread than the xreator thread.
2356 * We cannot access to the socket if the thread is different.
2357 */
2358 if (socket->tid != tid)
2359 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2360
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002361 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002362 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002363 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002364 lua_pushinteger(L, -1);
2365 return 1;
2366 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002367
2368 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2369 appctx = csk_ctx->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002370 cs = appctx->owner;
2371 s = __cs_strm(cs);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002372
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002374 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002375 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376 lua_pushinteger(L, -1);
2377 return 1;
2378 }
2379
2380 /* Update the input buffer data. */
2381 buf += sent;
2382 send_len = buf_len - sent;
2383
2384 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002385 if (sent >= buf_len) {
2386 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002387 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002388 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002390 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002391 * the request buffer if its not required.
2392 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002393 if (s->req.buf.size == 0) {
Christopher Faulet8f45eec2022-04-01 17:19:36 +02002394 if (!cs_alloc_ibuf(cs, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002395 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002396 }
2397
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002398 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002399 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002400 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002401 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002402 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002403
2404 /* send data */
2405 if (len < send_len)
2406 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002407 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002408
2409 /* "Not enough space" (-1), "Buffer too little to contain
2410 * the data" (-2) are not expected because the available length
2411 * is tested.
2412 * Other unknown error are also not expected.
2413 */
2414 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002415 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002416 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002417
sada05ed3302018-05-11 11:48:18 -07002418 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002419 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002420 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002421 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002422 return 1;
2423 }
2424
2425 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002426 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002427
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002428 s->req.rex = TICK_ETERNITY;
2429 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002430
2431 /* Update length sent. */
2432 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002433 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002434
2435 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002436 if (sent + len >= buf_len) {
2437 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002439 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002440
2441hlua_socket_write_yield_return:
Willy Tarreau5321da92022-05-06 11:57:34 +02002442 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002443 xref_unlock(&socket->xref, peer);
2444 WILL_LJMP(luaL_error(L, "out of memory"));
2445 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002446 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002447 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002448 return 0;
2449}
2450
2451/* This function initiate the send of data. It just check the input
2452 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002453 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002454 * "hlua_socket_write_yield" that can yield.
2455 *
2456 * The Lua function gets between 3 and 4 parameters. The first one is
2457 * the associated object. The second is a string buffer. The third is
2458 * a facultative integer that represents where is the buffer position
2459 * of the start of the data that can send. The first byte is the
2460 * position "1". The default value is "1". The fourth argument is a
2461 * facultative integer that represents where is the buffer position
2462 * of the end of the data that can send. The default is the last byte.
2463 */
2464static int hlua_socket_send(struct lua_State *L)
2465{
2466 int i;
2467 int j;
2468 const char *buf;
2469 size_t buf_len;
2470
2471 /* Check number of arguments. */
2472 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2473 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2474
2475 /* Get the string. */
2476 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2477
2478 /* Get and check j. */
2479 if (lua_gettop(L) == 4) {
2480 j = MAY_LJMP(luaL_checkinteger(L, 4));
2481 if (j < 0)
2482 j = buf_len + j + 1;
2483 if (j > buf_len)
2484 j = buf_len + 1;
2485 lua_pop(L, 1);
2486 }
2487 else
2488 j = buf_len;
2489
2490 /* Get and check i. */
2491 if (lua_gettop(L) == 3) {
2492 i = MAY_LJMP(luaL_checkinteger(L, 3));
2493 if (i < 0)
2494 i = buf_len + i + 1;
2495 if (i > buf_len)
2496 i = buf_len + 1;
2497 lua_pop(L, 1);
2498 } else
2499 i = 1;
2500
2501 /* Check bth i and j. */
2502 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002503 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002504 return 1;
2505 }
2506 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002507 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002508 return 1;
2509 }
2510 if (i == 0)
2511 i = 1;
2512 if (j == 0)
2513 j = 1;
2514
2515 /* Pop the string. */
2516 lua_pop(L, 1);
2517
2518 /* Update the buffer length. */
2519 buf += i - 1;
2520 buf_len = j - i + 1;
2521 lua_pushlstring(L, buf, buf_len);
2522
2523 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002524 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002526 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002527}
2528
Willy Tarreau22b0a682015-06-17 19:43:49 +02002529#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Christopher Faulete6465b32021-10-22 15:36:08 +02002530__LJMP static inline int hlua_socket_info(struct lua_State *L, const struct sockaddr_storage *addr)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002531{
2532 static char buffer[SOCKET_INFO_MAX_LEN];
2533 int ret;
2534 int len;
2535 char *p;
2536
2537 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2538 if (ret <= 0) {
2539 lua_pushnil(L);
2540 return 1;
2541 }
2542
2543 if (ret == AF_UNIX) {
2544 lua_pushstring(L, buffer+1);
2545 return 1;
2546 }
2547 else if (ret == AF_INET6) {
2548 buffer[0] = '[';
2549 len = strlen(buffer);
2550 buffer[len] = ']';
2551 len++;
2552 buffer[len] = ':';
2553 len++;
2554 p = buffer;
2555 }
2556 else if (ret == AF_INET) {
2557 p = buffer + 1;
2558 len = strlen(p);
2559 p[len] = ':';
2560 len++;
2561 }
2562 else {
2563 lua_pushnil(L);
2564 return 1;
2565 }
2566
2567 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2568 lua_pushnil(L);
2569 return 1;
2570 }
2571
2572 lua_pushstring(L, p);
2573 return 1;
2574}
2575
2576/* Returns information about the peer of the connection. */
2577__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2578{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002579 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002580 struct xref *peer;
2581 struct appctx *appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002582 struct conn_stream *cs;
Christopher Faulet16f16af2021-10-27 09:34:56 +02002583 const struct sockaddr_storage *dst;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002584 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002585
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002586 MAY_LJMP(check_args(L, 1, "getpeername"));
2587
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002588 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002590 /* Check if we run on the same thread than the xreator thread.
2591 * We cannot access to the socket if the thread is different.
2592 */
2593 if (socket->tid != tid)
2594 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2595
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002596 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002597 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002598 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002599 lua_pushnil(L);
2600 return 1;
2601 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002602
2603 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002604 cs = appctx->owner;
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002605 dst = cs_dst(cs_opposite(cs));
Christopher Faulet16f16af2021-10-27 09:34:56 +02002606 if (!dst) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002607 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002608 lua_pushnil(L);
2609 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002610 }
2611
Christopher Faulet16f16af2021-10-27 09:34:56 +02002612 ret = MAY_LJMP(hlua_socket_info(L, dst));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002613 xref_unlock(&socket->xref, peer);
2614 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002615}
2616
2617/* Returns information about my connection side. */
2618static int hlua_socket_getsockname(struct lua_State *L)
2619{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002620 struct hlua_socket *socket;
2621 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002622 struct appctx *appctx;
2623 struct xref *peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002624 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002625 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002626
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002627 MAY_LJMP(check_args(L, 1, "getsockname"));
2628
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002629 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002630
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002631 /* Check if we run on the same thread than the xreator thread.
2632 * We cannot access to the socket if the thread is different.
2633 */
2634 if (socket->tid != tid)
2635 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2636
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002637 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002638 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002639 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002640 lua_pushnil(L);
2641 return 1;
2642 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002643
2644 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002645 s = __cs_strm(appctx->owner);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002646
Christopher Faulet95a61e82021-12-22 14:22:03 +01002647 conn = cs_conn(s->csb);
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002648 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002649 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002650 lua_pushnil(L);
2651 return 1;
2652 }
2653
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002654 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002655 xref_unlock(&socket->xref, peer);
2656 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002657}
2658
2659/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002660static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661 .obj_type = OBJ_TYPE_APPLET,
2662 .name = "<LUA_TCP>",
2663 .fct = hlua_socket_handler,
2664 .release = hlua_socket_release,
2665};
2666
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002667__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002668{
2669 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002670 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002671 struct xref *peer;
Willy Tarreau5321da92022-05-06 11:57:34 +02002672 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002673 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002674 struct stream *s;
2675
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002676 /* Get hlua struct, or NULL if we execute from main lua state */
2677 hlua = hlua_gethlua(L);
2678 if (!hlua)
2679 return 0;
2680
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002681 /* Check if we run on the same thread than the xreator thread.
2682 * We cannot access to the socket if the thread is different.
2683 */
2684 if (socket->tid != tid)
2685 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2686
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002687 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002688 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002689 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002690 lua_pushnil(L);
2691 lua_pushstring(L, "Can't connect");
2692 return 2;
2693 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002694
2695 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2696 appctx = csk_ctx->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002697 s = __cs_strm(appctx->owner);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002698
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002699 /* Check if we run on the same thread than the xreator thread.
2700 * We cannot access to the socket if the thread is different.
2701 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002702 if (socket->tid != tid) {
2703 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002704 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002705 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002706
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002707 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002708 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002709 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002710 lua_pushnil(L);
2711 lua_pushstring(L, "Can't connect");
2712 return 2;
2713 }
2714
Christopher Faulet693b23b2022-02-28 09:09:05 +01002715 appctx = __cs_appctx(s->csf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002716
2717 /* Check for connection established. */
Willy Tarreau5321da92022-05-06 11:57:34 +02002718 if (csk_ctx->connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002719 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002720 lua_pushinteger(L, 1);
2721 return 1;
2722 }
2723
Willy Tarreau5321da92022-05-06 11:57:34 +02002724 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002725 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002726 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002727 }
2728 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002729 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002730 return 0;
2731}
2732
2733/* This function fail or initite the connection. */
2734__LJMP static int hlua_socket_connect(struct lua_State *L)
2735{
2736 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002737 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002738 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002739 struct hlua *hlua;
Willy Tarreau5321da92022-05-06 11:57:34 +02002740 struct hlua_csk_ctx *csk_ctx;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002741 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002742 int low, high;
2743 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002744 struct xref *peer;
Christopher Faulet908628c2022-03-25 16:43:49 +01002745 struct conn_stream *cs;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002746 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002747
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002748 if (lua_gettop(L) < 2)
2749 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002750
2751 /* Get args. */
2752 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002753
2754 /* Check if we run on the same thread than the xreator thread.
2755 * We cannot access to the socket if the thread is different.
2756 */
2757 if (socket->tid != tid)
2758 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2759
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002760 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002761 if (lua_gettop(L) >= 3) {
2762 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002763 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002764
Tim Duesterhus6edab862018-01-06 19:04:45 +01002765 /* Force the ip to end with a colon, to support IPv6 addresses
2766 * that are not enclosed within square brackets.
2767 */
2768 if (port > 0) {
2769 luaL_buffinit(L, &b);
2770 luaL_addstring(&b, ip);
2771 luaL_addchar(&b, ':');
2772 luaL_pushresult(&b);
2773 ip = lua_tolstring(L, lua_gettop(L), NULL);
2774 }
2775 }
2776
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002777 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002778 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002779 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002780 lua_pushnil(L);
2781 return 1;
2782 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002783
2784 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002785 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 +02002786 if (!addr) {
2787 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002788 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002789 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002790
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002791 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002792 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002793 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002794 if (port == -1) {
2795 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002796 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002797 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002798 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2799 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002800 if (port == -1) {
2801 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002802 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002803 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002804 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002805 }
2806 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002807
Willy Tarreau5321da92022-05-06 11:57:34 +02002808 csk_ctx = container_of(peer, struct hlua_csk_ctx, xref);
2809 appctx = csk_ctx->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002810 cs = appctx->owner;
2811 s = __cs_strm(cs);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002812
Christopher Faulet8da67aa2022-03-29 17:53:09 +02002813 if (!sockaddr_alloc(&cs_opposite(cs)->dst, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002814 xref_unlock(&socket->xref, peer);
2815 WILL_LJMP(luaL_error(L, "connect: internal error"));
2816 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002817
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002818 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002819 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002820 if (!hlua)
2821 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002822
2823 /* inform the stream that we want to be notified whenever the
2824 * connection completes.
2825 */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002826 cs_cant_get(s->csf);
2827 cs_rx_endp_more(s->csf);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002828 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002829
Willy Tarreauf31af932020-01-14 09:59:38 +01002830 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002831
Willy Tarreau5321da92022-05-06 11:57:34 +02002832 if (!notification_new(&hlua->com, &csk_ctx->wake_on_write, hlua->task)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002833 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002834 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002835 }
2836 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002837
2838 task_wakeup(s->task, TASK_WOKEN_INIT);
2839 /* Return yield waiting for connection. */
2840
Willy Tarreau9635e032018-10-16 17:52:55 +02002841 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002842
2843 return 0;
2844}
2845
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002846#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002847__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2848{
2849 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002850 struct xref *peer;
2851 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002852 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002853
2854 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2855 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002856
2857 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002858 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002859 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002860 lua_pushnil(L);
2861 return 1;
2862 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002863
2864 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002865 s = __cs_strm(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002866
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002867 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002868 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002869 return MAY_LJMP(hlua_socket_connect(L));
2870}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002871#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002872
2873__LJMP static int hlua_socket_setoption(struct lua_State *L)
2874{
2875 return 0;
2876}
2877
2878__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2879{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002880 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002881 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002882 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002883 struct xref *peer;
2884 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002885 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002886
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002887 MAY_LJMP(check_args(L, 2, "settimeout"));
2888
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002889 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002890
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002891 /* convert the timeout to millis */
2892 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002893
Thierry Fournier17a921b2018-03-08 09:59:02 +01002894 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002895 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002896 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2897
Mark Lakes56cc1252018-03-27 09:48:06 +02002898 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002899 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002900
2901 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002902 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002903 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002904
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002905 /* Check if we run on the same thread than the xreator thread.
2906 * We cannot access to the socket if the thread is different.
2907 */
2908 if (socket->tid != tid)
2909 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2910
Mark Lakes56cc1252018-03-27 09:48:06 +02002911 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002912 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002913 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002914 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2915 WILL_LJMP(lua_error(L));
2916 return 0;
2917 }
Willy Tarreau5321da92022-05-06 11:57:34 +02002918
2919 appctx = container_of(peer, struct hlua_csk_ctx, xref)->appctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002920 s = __cs_strm(appctx->owner);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002921
Cyril Bonté7bb63452018-08-17 23:51:02 +02002922 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002923 s->req.rto = tmout;
2924 s->req.wto = tmout;
2925 s->res.rto = tmout;
2926 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002927 s->req.rex = tick_add_ifset(now_ms, tmout);
2928 s->req.wex = tick_add_ifset(now_ms, tmout);
2929 s->res.rex = tick_add_ifset(now_ms, tmout);
2930 s->res.wex = tick_add_ifset(now_ms, tmout);
2931
2932 s->task->expire = tick_add_ifset(now_ms, tmout);
2933 task_queue(s->task);
2934
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002935 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002936
Thierry Fourniere9636f12018-03-08 09:54:32 +01002937 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002938 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002939}
2940
2941__LJMP static int hlua_socket_new(lua_State *L)
2942{
2943 struct hlua_socket *socket;
Willy Tarreau5321da92022-05-06 11:57:34 +02002944 struct hlua_csk_ctx *ctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002945 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002946 struct session *sess;
Christopher Faulet13a35e52021-12-20 15:34:16 +01002947 struct conn_stream *cs;
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002948 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002949
2950 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002951 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002952 hlua_pusherror(L, "socket: full stack");
2953 goto out_fail_conf;
2954 }
2955
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002956 /* Create the object: obj[0] = userdata. */
2957 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002958 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002959 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002960 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002961 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002962
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002963 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002964 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002965 hlua_pusherror(L, "socket: uninitialized pools.");
2966 goto out_fail_conf;
2967 }
2968
Willy Tarreau87b09662015-04-03 00:22:06 +02002969 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002970 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2971 lua_setmetatable(L, -2);
2972
Willy Tarreaud420a972015-04-06 00:39:18 +02002973 /* Create the applet context */
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +01002974 appctx = appctx_new(&update_applet, NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002975 if (!appctx) {
2976 hlua_pusherror(L, "socket: out of memory");
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002977 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002978 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002979
Willy Tarreau5321da92022-05-06 11:57:34 +02002980 ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
2981 ctx->connected = 0;
2982 ctx->appctx = appctx;
2983 ctx->die = 0;
2984 LIST_INIT(&ctx->wake_on_write);
2985 LIST_INIT(&ctx->wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002986
Willy Tarreaud420a972015-04-06 00:39:18 +02002987 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002988 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002989 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002990 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet13a35e52021-12-20 15:34:16 +01002991 goto out_fail_appctx;
2992 }
2993
Christopher Faulet9ec2f4d2022-03-23 15:15:29 +01002994 cs = cs_new_from_applet(appctx->endp, sess, &BUF_NULL);
Christopher Fauleta9e8b392022-03-23 11:01:09 +01002995 if (!cs) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002996 hlua_pusherror(L, "socket: out of memory");
Christopher Faulet2479e5f2022-01-19 14:50:11 +01002997 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002998 }
2999
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003000 s = DISGUISE(cs_strm(cs));
Christopher Faulet2479e5f2022-01-19 14:50:11 +01003001
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003002 /* Initialise cross reference between stream and Lua socket object. */
Willy Tarreau5321da92022-05-06 11:57:34 +02003003 xref_create(&socket->xref, &ctx->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003004
Christopher Faulet6b0a0fb2022-04-04 11:29:28 +02003005 /* Configure "right" conn-stream. this "si" is used to connect
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003006 * and retrieve data from the server. The connection is initialized
3007 * with the "struct server".
3008 */
Christopher Faulet62e75742022-03-31 09:16:34 +02003009 cs_set_state(s->csb, CS_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003010
3011 /* Force destination server. */
Christopher Fauleta9e8b392022-03-23 11:01:09 +01003012 s->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
3013 s->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003014
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003015 return 1;
3016
Willy Tarreaud420a972015-04-06 00:39:18 +02003017 out_fail_sess:
Christopher Faulet13a35e52021-12-20 15:34:16 +01003018 session_free(sess);
3019 out_fail_appctx:
Willy Tarreaud420a972015-04-06 00:39:18 +02003020 appctx_free(appctx);
3021 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003022 WILL_LJMP(lua_error(L));
3023 return 0;
3024}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003025
3026/*
3027 *
3028 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003029 * Class Channel
3030 *
3031 *
3032 */
3033
3034/* Returns the struct hlua_channel join to the class channel in the
3035 * stack entry "ud" or throws an argument error.
3036 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003037__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003038{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003039 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003040}
3041
Willy Tarreau47860ed2015-03-10 14:07:50 +01003042/* Pushes the channel onto the top of the stack. If the stask does not have a
3043 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003044 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003045static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003047 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003048 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003049 return 0;
3050
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003051 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003052 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003053 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003054
3055 /* Pop a class sesison metatable and affect it to the userdata. */
3056 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3057 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003058 return 1;
3059}
3060
Christopher Faulet9f55a502020-02-25 15:21:02 +01003061/* Helper function returning a filter attached to a channel at the position <ud>
3062 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003063 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003064 * initialized.
3065 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003066static 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 +01003067{
3068 struct filter *filter = NULL;
3069
3070 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3071 struct hlua_flt_ctx *flt_ctx;
3072
3073 filter = lua_touserdata (L, -1);
3074 flt_ctx = filter->ctx;
3075 if (hlua_filter_from_payload(filter)) {
3076 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3077 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3078 }
3079 }
3080
3081 lua_pop(L, 1);
3082 return filter;
3083}
3084
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003085/* Copies <len> bytes of data present in the channel's buffer, starting at the
3086* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003087* responsibility to ensure <len> and <offset> are valid. It always return the
3088* length of the built string. <len> may be 0, in this case, an empty string is
3089* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003090*/
3091static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003092{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003093 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003094 luaL_Buffer b;
3095
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003096 block1 = len;
3097 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3098 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3099 block2 = len - block1;
3100
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003101 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003102 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3103 if (block2)
3104 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003105 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003106 return len;
3107}
3108
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003109/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3110 * function returns -1 if data cannot be copied. Otherwise, it returns the
3111 * number of bytes copied.
3112 */
3113static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3114{
3115 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003116
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003117 /* Nothing to do, just return */
3118 if (unlikely(istlen(str) == 0))
3119 goto end;
3120
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003121 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003122 ret = -1;
3123 goto end;
3124 }
3125 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3126
3127 end:
3128 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003129}
3130
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003131/* Removes <len> bytes of data at the absolute position <offset>.
3132 */
3133static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3134{
3135 size_t end = offset + len;
3136
3137 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3138 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3139 b_data(&chn->buf) - end, -len);
3140 b_sub(&chn->buf, len);
3141}
3142
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003143/* Copies input data in the channel's buffer. It is possible to set a specific
3144 * offset (0 by default) and a length (all remaining input data starting for the
3145 * offset by default). If there is not enough input data and more data can be
3146 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003147 *
3148 * From an action, All input data are considered. For a filter, the offset and
3149 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003150 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003151__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003152{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003153 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003154 struct filter *filter;
3155 size_t input, output;
3156 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003157
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003158 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003159
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003160 output = co_data(chn);
3161 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003162
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003163 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3164 if (filter && !hlua_filter_from_payload(filter))
3165 WILL_LJMP(lua_error(L));
3166
3167 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003168 if (lua_gettop(L) > 1) {
3169 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3170 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003171 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003172 offset += output;
3173 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003174 lua_pushfstring(L, "offset out of range.");
3175 WILL_LJMP(lua_error(L));
3176 }
3177 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003178 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003179 if (lua_gettop(L) == 3) {
3180 len = MAY_LJMP(luaL_checkinteger(L, 3));
3181 if (!len)
3182 goto dup;
3183 if (len == -1)
3184 len = global.tune.bufsize;
3185 if (len < 0) {
3186 lua_pushfstring(L, "length out of range.");
3187 WILL_LJMP(lua_error(L));
3188 }
3189 }
3190
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003191 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003192 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3193 /* Yield waiting for more data, as requested */
3194 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3195 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003196 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003197 }
3198
3199 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003200 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003201 return 1;
3202}
3203
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003204/* Copies the first line (including the trailing LF) of input data in the
3205 * channel's buffer. It is possible to set a specific offset (0 by default) and
3206 * a length (all remaining input data starting for the offset by default). If
3207 * there is not enough input data and more data can be received, the function
3208 * yields. If a length is explicitly specified, no more data are
3209 * copied. Otherwise, if no LF is found and more data can be received, this
3210 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003211 *
3212 * From an action, All input data are considered. For a filter, the offset and
3213 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003214 */
3215__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003216{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003217 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003218 struct filter *filter;
3219 size_t l, input, output;
3220 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003221
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003222 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003223 output = co_data(chn);
3224 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003225
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003226 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3227 if (filter && !hlua_filter_from_payload(filter))
3228 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003229
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003230 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003231 if (lua_gettop(L) > 1) {
3232 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3233 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003234 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003235 offset += output;
3236 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003237 lua_pushfstring(L, "offset out of range.");
3238 WILL_LJMP(lua_error(L));
3239 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003240 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003241
3242 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003243 if (lua_gettop(L) == 3) {
3244 len = MAY_LJMP(luaL_checkinteger(L, 3));
3245 if (!len)
3246 goto dup;
3247 if (len == -1)
3248 len = global.tune.bufsize;
3249 if (len < 0) {
3250 lua_pushfstring(L, "length out of range.");
3251 WILL_LJMP(lua_error(L));
3252 }
3253 }
3254
3255 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003256 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003257 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003258 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003259 len = l+1;
3260 goto dup;
3261 }
3262 }
3263
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003264 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003265 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3266 /* Yield waiting for more data */
3267 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3268 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003269 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003270 }
3271
3272 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003273 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003274 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003275}
3276
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003277/* [ DEPRECATED ]
3278 *
3279 * Duplicate all input data foud in the channel's buffer. The data are not
3280 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003281 *
3282 * From an action, All input data are considered. For a filter, the offset and
3283 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003284 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003285__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003286{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003287 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003288 struct filter *filter;
3289 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003290
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003291 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003292 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003293 if (IS_HTX_STRM(chn_strm(chn))) {
3294 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3295 WILL_LJMP(lua_error(L));
3296 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003297
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003298 offset = co_data(chn);
3299 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003300
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003301 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3302 if (filter && !hlua_filter_from_payload(filter))
3303 WILL_LJMP(lua_error(L));
3304
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003305 if (!ci_data(chn) && channel_input_closed(chn)) {
3306 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003307 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003308 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003309
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003310 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003311 return 1;
3312}
3313
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003314/* [ DEPRECATED ]
3315 *
3316 * Get all input data foud in the channel's buffer. The data are removed from
3317 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3318 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003319 *
3320 * From an action, All input data are considered. For a filter, the offset and
3321 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003322 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003323__LJMP static int hlua_channel_get(lua_State *L)
3324{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003325 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003326 struct filter *filter;
3327 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003328 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003329
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003330 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003331 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3332 if (IS_HTX_STRM(chn_strm(chn))) {
3333 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3334 WILL_LJMP(lua_error(L));
3335 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003336
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003337 offset = co_data(chn);
3338 len = ci_data(chn);
3339
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003340 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3341 if (filter && !hlua_filter_from_payload(filter))
3342 WILL_LJMP(lua_error(L));
3343
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003344 if (!ci_data(chn) && channel_input_closed(chn)) {
3345 lua_pushnil(L);
3346 return 1;
3347 }
3348
3349 ret = _hlua_channel_dup(chn, L, offset, len);
3350 _hlua_channel_delete(chn, offset, ret);
3351 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003352}
3353
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003354/* This functions consumes and returns one line. If the channel is closed,
3355 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003356 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003357 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003358 *
3359 * From an action, All input data are considered. For a filter, the offset and
3360 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003361 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003362__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003363{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003364 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003365 struct filter *filter;
3366 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003367 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003368
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003369 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003370
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003371 offset = co_data(chn);
3372 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003373
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003374 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3375 if (filter && !hlua_filter_from_payload(filter))
3376 WILL_LJMP(lua_error(L));
3377
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003378 if (!ci_data(chn) && channel_input_closed(chn)) {
3379 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003380 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003381 }
3382
3383 for (l = 0; l < len; l++) {
3384 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3385 len = l+1;
3386 goto dup;
3387 }
3388 }
3389
3390 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3391 /* Yield waiting for more data */
3392 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3393 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003394
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003395 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003396 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003397 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003398 return 1;
3399}
3400
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003401/* [ DEPRECATED ]
3402 *
3403 * Check arguments for the function "hlua_channel_getline_yield".
3404 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003405__LJMP static int hlua_channel_getline(lua_State *L)
3406{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003407 struct channel *chn;
3408
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003409 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003410 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 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003415 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3416}
3417
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003418/* 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_data(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, "'data' 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_data_yield(L, 0, 0));
3435}
3436
3437/* Retrieves a given amount of input data at the given offset. By default all
3438 * available input data are returned. The offset may be negactive to start from
3439 * the end of input data. The length may be -1 to set it to the maximum buffer
3440 * size.
3441 */
3442__LJMP static int hlua_channel_get_line(lua_State *L)
3443{
3444 struct channel *chn;
3445
3446 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3447 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3448 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3449 if (IS_HTX_STRM(chn_strm(chn))) {
3450 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3451 WILL_LJMP(lua_error(L));
3452 }
3453 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3454}
3455
3456/* Appends a string into the input side of channel. It returns the length of the
3457 * written string, or -1 if the channel is closed or if the buffer size is too
3458 * little for the data. 0 may be returned if nothing is copied. This function
3459 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003460 *
3461 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003462 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003463__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003464{
Christopher Faulet23976d92021-08-06 09:59:49 +02003465 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003466 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003467 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003468 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003469 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003470
3471 MAY_LJMP(check_args(L, 2, "append"));
3472 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003473 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003474 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003475 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003476 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003477 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003478
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003479 offset = co_data(chn);
3480 len = ci_data(chn);
3481
3482 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3483 if (filter && !hlua_filter_from_payload(filter))
3484 WILL_LJMP(lua_error(L));
3485
3486 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3487 if (ret > 0 && filter) {
3488 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3489
3490 flt_update_offsets(filter, chn, ret);
3491 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3492 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003493 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003494 return 1;
3495}
3496
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003497/* Prepends a string into the input side of channel. It returns the length of the
3498 * written string, or -1 if the channel is closed or if the buffer size is too
3499 * little for the data. 0 may be returned if nothing is copied. This function
3500 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003501 *
3502 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003503 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003504__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003505{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003506 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003507 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003508 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003509 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003510 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003511
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003512 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003513 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003514 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3515 if (IS_HTX_STRM(chn_strm(chn))) {
3516 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3517 WILL_LJMP(lua_error(L));
3518 }
3519
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003520 offset = co_data(chn);
3521 len = ci_data(chn);
3522
3523 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3524 if (filter && !hlua_filter_from_payload(filter))
3525 WILL_LJMP(lua_error(L));
3526
3527 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3528 if (ret > 0 && filter) {
3529 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3530
3531 flt_update_offsets(filter, chn, ret);
3532 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3533 }
3534
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003535 lua_pushinteger(L, ret);
3536 return 1;
3537}
3538
3539/* Inserts a given amount of input data at the given offset by a string
3540 * content. By default the string is appended at the end of input data. It
3541 * returns the length of the written string, or -1 if the channel is closed or
3542 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003543 *
3544 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003545 */
3546__LJMP static int hlua_channel_insert_data(lua_State *L)
3547{
3548 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003549 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003550 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003551 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003552 int ret, offset;
3553
3554 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3555 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3556 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3557 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003558
3559 output = co_data(chn);
3560 input = ci_data(chn);
3561
3562 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3563 if (filter && !hlua_filter_from_payload(filter))
3564 WILL_LJMP(lua_error(L));
3565
3566 offset = input + output;
3567 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003568 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003569 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003570 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003571 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003572 if (offset < output || offset > output + input) {
3573 lua_pushfstring(L, "offset out of range.");
3574 WILL_LJMP(lua_error(L));
3575 }
3576 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003577 if (IS_HTX_STRM(chn_strm(chn))) {
3578 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3579 WILL_LJMP(lua_error(L));
3580 }
3581
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003582 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3583 if (ret > 0 && filter) {
3584 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003585
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003586 flt_update_offsets(filter, chn, ret);
3587 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003588 }
3589
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003590 lua_pushinteger(L, ret);
3591 return 1;
3592}
3593/* Replaces a given amount of input data at the given offset by a string
3594 * content. By default all remaining data are removed (offset = 0 and len =
3595 * -1). It returns the length of the written string, or -1 if the channel is
3596 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003597 *
3598 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003599 */
3600__LJMP static int hlua_channel_set_data(lua_State *L)
3601{
3602 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003603 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003604 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003605 size_t sz, input, output;
3606 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003607
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003608 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3609 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3610 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3611 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003612
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003613 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003614 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003615 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003616 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003617
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003618 output = co_data(chn);
3619 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003620
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003621 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3622 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003623 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003624
3625 offset = output;
3626 if (lua_gettop(L) > 2) {
3627 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3628 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003629 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003630 offset += output;
3631 if (offset < output || offset > input + output) {
3632 lua_pushfstring(L, "offset out of range.");
3633 WILL_LJMP(lua_error(L));
3634 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003635 }
3636
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003637 len = output + input - offset;
3638 if (lua_gettop(L) == 4) {
3639 len = MAY_LJMP(luaL_checkinteger(L, 4));
3640 if (!len)
3641 goto set;
3642 if (len == -1)
3643 len = output + input - offset;
3644 if (len < 0 || offset + len > output + input) {
3645 lua_pushfstring(L, "length out of range.");
3646 WILL_LJMP(lua_error(L));
3647 }
3648 }
3649
3650 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003651 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003652 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003653 lua_pushinteger(L, -1);
3654 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003655 _hlua_channel_delete(chn, offset, len);
3656 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3657 if (filter) {
3658 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3659
3660 len -= (ret > 0 ? ret : 0);
3661 flt_update_offsets(filter, chn, -len);
3662 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3663 }
3664
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003665 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003666 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003667 return 1;
3668}
3669
3670/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003671 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003672 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003673 *
3674 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003675 */
3676__LJMP static int hlua_channel_del_data(lua_State *L)
3677{
3678 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003679 struct filter *filter;
3680 size_t input, output;
3681 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003682
3683 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3684 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3685 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003686
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003687 if (IS_HTX_STRM(chn_strm(chn))) {
3688 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3689 WILL_LJMP(lua_error(L));
3690 }
3691
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003692 output = co_data(chn);
3693 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003694
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003695 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3696 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003697 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003698
3699 offset = output;
3700 if (lua_gettop(L) > 2) {
3701 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3702 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003703 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003704 offset += output;
3705 if (offset < output || offset > input + output) {
3706 lua_pushfstring(L, "offset out of range.");
3707 WILL_LJMP(lua_error(L));
3708 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003709 }
3710
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003711 len = output + input - offset;
3712 if (lua_gettop(L) == 4) {
3713 len = MAY_LJMP(luaL_checkinteger(L, 4));
3714 if (!len)
3715 goto end;
3716 if (len == -1)
3717 len = output + input - offset;
3718 if (len < 0 || offset + len > output + input) {
3719 lua_pushfstring(L, "length out of range.");
3720 WILL_LJMP(lua_error(L));
3721 }
3722 }
3723
3724 _hlua_channel_delete(chn, offset, len);
3725 if (filter) {
3726 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3727
3728 flt_update_offsets(filter, chn, -len);
3729 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3730 }
3731
3732 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003733 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003734 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003735}
3736
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003737/* Append data in the output side of the buffer. This data is immediately
3738 * sent. The function returns the amount of data written. If the buffer
3739 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003740 * if the channel is closed.
3741 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003742__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003743{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003744 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003745 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003746 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003747 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003748 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003749 struct hlua *hlua;
3750
3751 /* Get hlua struct, or NULL if we execute from main lua state */
3752 hlua = hlua_gethlua(L);
3753 if (!hlua) {
3754 lua_pushnil(L);
3755 return 1;
3756 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003757
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003758 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3759 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3760 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003761
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003762 offset = co_data(chn);
3763 len = ci_data(chn);
3764
3765 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3766 if (filter && !hlua_filter_from_payload(filter))
3767 WILL_LJMP(lua_error(L));
3768
3769
Willy Tarreau47860ed2015-03-10 14:07:50 +01003770 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003771 lua_pushinteger(L, -1);
3772 return 1;
3773 }
3774
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003775 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003776 if (len > sz -l) {
3777 if (filter) {
3778 lua_pushinteger(L, -1);
3779 return 1;
3780 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003781 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003782 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003783
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003784 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003785 if (ret == -1) {
3786 lua_pop(L, 1);
3787 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003788 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003789 }
3790 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003791 if (filter) {
3792 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3793
3794
3795 flt_update_offsets(filter, chn, ret);
3796 FLT_OFF(filter, chn) += ret;
3797 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3798 }
3799 else
3800 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003801
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003802 l += ret;
3803 lua_pop(L, 1);
3804 lua_pushinteger(L, l);
3805 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003806
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003807 if (l < sz) {
3808 /* Yield only if the channel's output is not empty.
3809 * Otherwise it means we cannot add more data. */
3810 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003811 return 1;
3812
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003813 /* If we are waiting for space in the response buffer, we
3814 * must set the flag WAKERESWR. This flag required the task
3815 * wake up if any activity is detected on the response buffer.
3816 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003817 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003818 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003819 else
3820 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003821 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003822 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003823
3824 return 1;
3825}
3826
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003827/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003828 * yield the LUA process, and resume it without checking the
3829 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003830 *
3831 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003832 */
3833__LJMP static int hlua_channel_send(lua_State *L)
3834{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003835 struct channel *chn;
3836
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003837 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003838 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3839 if (IS_HTX_STRM(chn_strm(chn))) {
3840 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3841 WILL_LJMP(lua_error(L));
3842 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003843 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003844 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003845}
3846
3847/* This function forward and amount of butes. The data pass from
3848 * the input side of the buffer to the output side, and can be
3849 * forwarded. This function never fails.
3850 *
3851 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003852 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003853 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003854__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003855{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003856 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003857 struct filter *filter;
3858 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003859 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003860 struct hlua *hlua;
3861
3862 /* Get hlua struct, or NULL if we execute from main lua state */
3863 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003864 if (!hlua) {
3865 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003866 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003867 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003868
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003869 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003870 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003871 l = MAY_LJMP(luaL_checkinteger(L, -1));
3872
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003873 offset = co_data(chn);
3874 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003875
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003876 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3877 if (filter && !hlua_filter_from_payload(filter))
3878 WILL_LJMP(lua_error(L));
3879
3880 max = fwd - l;
3881 if (max > len)
3882 max = len;
3883
3884 if (filter) {
3885 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3886
3887 FLT_OFF(filter, chn) += max;
3888 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3889 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3890 }
3891 else
3892 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003893
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003894 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003895 lua_pop(L, 1);
3896 lua_pushinteger(L, l);
3897
3898 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003899 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003900 /* The the input channel or the output channel are closed, we
3901 * must return the amount of data forwarded.
3902 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003903 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003904 return 1;
3905
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003906 /* If we are waiting for space data in the response buffer, we
3907 * must set the flag WAKERESWR. This flag required the task
3908 * wake up if any activity is detected on the response buffer.
3909 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003910 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003911 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003912 else
3913 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003914
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003915 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003916 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003917 }
3918
3919 return 1;
3920}
3921
3922/* Just check the input and prepare the stack for the previous
3923 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003924 *
3925 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003926 */
3927__LJMP static int hlua_channel_forward(lua_State *L)
3928{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003929 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003930
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003931 MAY_LJMP(check_args(L, 2, "forward"));
3932 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3933 if (IS_HTX_STRM(chn_strm(chn))) {
3934 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3935 WILL_LJMP(lua_error(L));
3936 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003937 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003938 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003939}
3940
3941/* Just returns the number of bytes available in the input
3942 * side of the buffer. This function never fails.
3943 */
3944__LJMP static int hlua_channel_get_in_len(lua_State *L)
3945{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003946 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003947 struct filter *filter;
3948 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003949
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003950 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003951 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003952
3953 output = co_data(chn);
3954 input = ci_data(chn);
3955 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3956 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3957 lua_pushinteger(L, input);
3958 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003959 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003960
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003961 lua_pushinteger(L, htx->data - co_data(chn));
3962 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003963 return 1;
3964}
3965
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003966/* Returns true if the channel is full. */
3967__LJMP static int hlua_channel_is_full(lua_State *L)
3968{
3969 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003970
3971 MAY_LJMP(check_args(L, 1, "is_full"));
3972 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003973 /* ignore the reserve, we are not on a producer side (ie in an
3974 * applet).
3975 */
3976 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003977 return 1;
3978}
3979
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003980/* Returns true if the channel may still receive data. */
3981__LJMP static int hlua_channel_may_recv(lua_State *L)
3982{
3983 struct channel *chn;
3984
3985 MAY_LJMP(check_args(L, 1, "may_recv"));
3986 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3987 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3988 return 1;
3989}
3990
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003991/* Returns true if the channel is the response channel. */
3992__LJMP static int hlua_channel_is_resp(lua_State *L)
3993{
3994 struct channel *chn;
3995
3996 MAY_LJMP(check_args(L, 1, "is_resp"));
3997 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3998
3999 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
4000 return 1;
4001}
4002
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004003/* Just returns the number of bytes available in the output
4004 * side of the buffer. This function never fails.
4005 */
4006__LJMP static int hlua_channel_get_out_len(lua_State *L)
4007{
Willy Tarreau47860ed2015-03-10 14:07:50 +01004008 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004009 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004010
Christopher Faulet6a79fc12021-08-06 16:02:36 +02004011 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004012 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02004013
4014 output = co_data(chn);
4015 input = ci_data(chn);
4016 hlua_channel_filter(L, 1, chn, &output, &input);
4017
4018 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004019 return 1;
4020}
4021
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004022/*
4023 *
4024 *
4025 * Class Fetches
4026 *
4027 *
4028 */
4029
4030/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004031 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004032 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004033__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004034{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004035 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004036}
4037
4038/* This function creates and push in the stack a fetch object according
4039 * with a current TXN.
4040 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004041static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004042{
Willy Tarreau7073c472015-04-06 11:15:40 +02004043 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004044
4045 /* Check stack size. */
4046 if (!lua_checkstack(L, 3))
4047 return 0;
4048
4049 /* Create the object: obj[0] = userdata.
4050 * Note that the base of the Fetches object is the
4051 * transaction object.
4052 */
4053 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004054 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004055 lua_rawseti(L, -2, 0);
4056
Willy Tarreau7073c472015-04-06 11:15:40 +02004057 hsmp->s = txn->s;
4058 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004059 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004060 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004061
4062 /* Pop a class sesison metatable and affect it to the userdata. */
4063 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4064 lua_setmetatable(L, -2);
4065
4066 return 1;
4067}
4068
4069/* This function is an LUA binding. It is called with each sample-fetch.
4070 * It uses closure argument to store the associated sample-fetch. It
4071 * returns only one argument or throws an error. An error is thrown
4072 * only if an error is encountered during the argument parsing. If
4073 * the "sample-fetch" function fails, nil is returned.
4074 */
4075__LJMP static int hlua_run_sample_fetch(lua_State *L)
4076{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004077 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004078 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004079 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004080 int i;
4081 struct sample smp;
4082
4083 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004084 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004085
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004086 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004087 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004088
Thierry FOURNIERca988662015-12-20 18:43:03 +01004089 /* Check execution authorization. */
4090 if (f->use & SMP_USE_HTTP_ANY &&
4091 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4092 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4093 "is not available in Lua services", f->kw);
4094 WILL_LJMP(lua_error(L));
4095 }
4096
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004097 /* Get extra arguments. */
4098 for (i = 0; i < lua_gettop(L) - 1; i++) {
4099 if (i >= ARGM_NBARGS)
4100 break;
4101 hlua_lua2arg(L, i + 2, &args[i]);
4102 }
4103 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004104 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004105
4106 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004107 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004108
4109 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004110 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004111 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004112 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004113 }
4114
4115 /* Initialise the sample. */
4116 memset(&smp, 0, sizeof(smp));
4117
4118 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004119 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004120 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004121 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004122 lua_pushstring(L, "");
4123 else
4124 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004125 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004126 }
4127
4128 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004129 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004130 hlua_smp2lua_str(L, &smp);
4131 else
4132 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004133
4134 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004135 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004136 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004137
4138 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004139 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004140 WILL_LJMP(lua_error(L));
4141 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004142}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004143
4144/*
4145 *
4146 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004147 * Class Converters
4148 *
4149 *
4150 */
4151
4152/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004153 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004154 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004155__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004156{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004157 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004158}
4159
4160/* This function creates and push in the stack a Converters object
4161 * according with a current TXN.
4162 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004163static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004164{
Willy Tarreau7073c472015-04-06 11:15:40 +02004165 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004166
4167 /* Check stack size. */
4168 if (!lua_checkstack(L, 3))
4169 return 0;
4170
4171 /* Create the object: obj[0] = userdata.
4172 * Note that the base of the Converters object is the
4173 * same than the TXN object.
4174 */
4175 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004176 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004177 lua_rawseti(L, -2, 0);
4178
Willy Tarreau7073c472015-04-06 11:15:40 +02004179 hsmp->s = txn->s;
4180 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004181 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004182 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004183
Willy Tarreau87b09662015-04-03 00:22:06 +02004184 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004185 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4186 lua_setmetatable(L, -2);
4187
4188 return 1;
4189}
4190
4191/* This function is an LUA binding. It is called with each converter.
4192 * It uses closure argument to store the associated converter. It
4193 * returns only one argument or throws an error. An error is thrown
4194 * only if an error is encountered during the argument parsing. If
4195 * the converter function function fails, nil is returned.
4196 */
4197__LJMP static int hlua_run_sample_conv(lua_State *L)
4198{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004199 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004200 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004201 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004202 int i;
4203 struct sample smp;
4204
4205 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004206 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004207
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004208 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004209 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210
4211 /* Get extra arguments. */
4212 for (i = 0; i < lua_gettop(L) - 2; i++) {
4213 if (i >= ARGM_NBARGS)
4214 break;
4215 hlua_lua2arg(L, i + 3, &args[i]);
4216 }
4217 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004218 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004219
4220 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004221 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004222
4223 /* Run the special args checker. */
4224 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4225 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004226 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004227 }
4228
4229 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004230 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004231 if (!hlua_lua2smp(L, 2, &smp)) {
4232 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004233 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004234 }
4235
Willy Tarreau1777ea62016-03-10 16:15:46 +01004236 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4237
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004238 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004239 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004240 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004241 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004242 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004243 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004244 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4245 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004246 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004247 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004248 }
4249
4250 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004251 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004252 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004253 lua_pushstring(L, "");
4254 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004255 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004256 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004257 }
4258
4259 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004260 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004261 hlua_smp2lua_str(L, &smp);
4262 else
4263 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004264 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004265 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004266 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004267
4268 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004269 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004270 WILL_LJMP(lua_error(L));
4271 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004272}
4273
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004274/*
4275 *
4276 *
4277 * Class AppletTCP
4278 *
4279 *
4280 */
4281
4282/* Returns a struct hlua_txn if the stack entry "ud" is
4283 * a class stream, otherwise it throws an error.
4284 */
4285__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4286{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004287 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004288}
4289
4290/* This function creates and push in the stack an Applet object
4291 * according with a current TXN.
4292 */
4293static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4294{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004295 struct hlua_appctx *luactx;
Christopher Faulet908628c2022-03-25 16:43:49 +01004296 struct stream *s = __cs_strm(ctx->owner);
Christopher Faulet2da02ae2022-02-24 13:45:27 +01004297 struct proxy *p;
4298
4299 ALREADY_CHECKED(s);
4300 p = s->be;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004301
4302 /* Check stack size. */
4303 if (!lua_checkstack(L, 3))
4304 return 0;
4305
4306 /* Create the object: obj[0] = userdata.
4307 * Note that the base of the Converters object is the
4308 * same than the TXN object.
4309 */
4310 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004311 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004312 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004313 luactx->appctx = ctx;
4314 luactx->htxn.s = s;
4315 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004316
4317 /* Create the "f" field that contains a list of fetches. */
4318 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004319 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004320 return 0;
4321 lua_settable(L, -3);
4322
4323 /* Create the "sf" field that contains a list of stringsafe fetches. */
4324 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004325 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004326 return 0;
4327 lua_settable(L, -3);
4328
4329 /* Create the "c" field that contains a list of converters. */
4330 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004331 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004332 return 0;
4333 lua_settable(L, -3);
4334
4335 /* Create the "sc" field that contains a list of stringsafe converters. */
4336 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004337 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004338 return 0;
4339 lua_settable(L, -3);
4340
4341 /* Pop a class stream metatable and affect it to the table. */
4342 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4343 lua_setmetatable(L, -2);
4344
4345 return 1;
4346}
4347
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004348__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4349{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004350 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004351 struct stream *s;
4352 const char *name;
4353 size_t len;
4354 struct sample smp;
4355
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004356 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4357 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004358
4359 /* It is useles to retrieve the stream, but this function
4360 * runs only in a stream context.
4361 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004362 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004363 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004364 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004365
4366 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004367 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004368 hlua_lua2smp(L, 3, &smp);
4369
4370 /* Store the sample in a variable. */
4371 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004372
4373 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4374 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4375 else
4376 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4377
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004378 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004379}
4380
4381__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4382{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004383 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004384 struct stream *s;
4385 const char *name;
4386 size_t len;
4387 struct sample smp;
4388
4389 MAY_LJMP(check_args(L, 2, "unset_var"));
4390
4391 /* It is useles to retrieve the stream, but this function
4392 * runs only in a stream context.
4393 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004394 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004395 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004396 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004397
4398 /* Unset the variable. */
4399 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004400 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4401 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004402}
4403
4404__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4405{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004406 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004407 struct stream *s;
4408 const char *name;
4409 size_t len;
4410 struct sample smp;
4411
4412 MAY_LJMP(check_args(L, 2, "get_var"));
4413
4414 /* It is useles to retrieve the stream, but this function
4415 * runs only in a stream context.
4416 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004417 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004418 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004419 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004420
4421 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004422 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004423 lua_pushnil(L);
4424 return 1;
4425 }
4426
4427 return hlua_smp2lua(L, &smp);
4428}
4429
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004430__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4431{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004432 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4433 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004434 struct hlua *hlua;
4435
4436 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004437 if (!s->hlua)
4438 return 0;
4439 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004440
4441 MAY_LJMP(check_args(L, 2, "set_priv"));
4442
4443 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004444 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004445
4446 /* Get and store new value. */
4447 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4448 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4449
4450 return 0;
4451}
4452
4453__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4454{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004455 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4456 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004457 struct hlua *hlua;
4458
4459 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004460 if (!s->hlua) {
4461 lua_pushnil(L);
4462 return 1;
4463 }
4464 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004465
4466 /* Push configuration index in the stack. */
4467 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4468
4469 return 1;
4470}
4471
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004472/* If expected data not yet available, it returns a yield. This function
4473 * consumes the data in the buffer. It returns a string containing the
4474 * data. This string can be empty.
4475 */
4476__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4477{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004478 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01004479 struct conn_stream *cs = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004480 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004481 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004482 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004483 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004484 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004485
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004486 /* Read the maximum amount of data available. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004487 ret = co_getline_nc(cs_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004488
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004489 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004490 if (ret == 0) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004491 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004492 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004493 }
4494
4495 /* End of data: commit the total strings and return. */
4496 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004497 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004498 return 1;
4499 }
4500
4501 /* Ensure that the block 2 length is usable. */
4502 if (ret == 1)
4503 len2 = 0;
4504
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004505 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004506 luaL_addlstring(&luactx->b, blk1, len1);
4507 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004508
4509 /* Consume input channel output buffer data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004510 co_skip(cs_oc(cs), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004511 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004512 return 1;
4513}
4514
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004515/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004516__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4517{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004518 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004519
4520 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004521 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004522
4523 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4524}
4525
4526/* If expected data not yet available, it returns a yield. This function
4527 * consumes the data in the buffer. It returns a string containing the
4528 * data. This string can be empty.
4529 */
4530__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4531{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004532 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01004533 struct conn_stream *cs = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004534 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004535 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004536 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004537 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004538 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004539 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004540
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004541 /* Read the maximum amount of data available. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004542 ret = co_getblk_nc(cs_oc(cs), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004543
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004544 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004545 if (ret == 0) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004546 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004547 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004548 }
4549
4550 /* End of data: commit the total strings and return. */
4551 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004552 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553 return 1;
4554 }
4555
4556 /* Ensure that the block 2 length is usable. */
4557 if (ret == 1)
4558 len2 = 0;
4559
4560 if (len == -1) {
4561
4562 /* If len == -1, catenate all the data avalaile and
4563 * yield because we want to get all the data until
4564 * the end of data stream.
4565 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004566 luaL_addlstring(&luactx->b, blk1, len1);
4567 luaL_addlstring(&luactx->b, blk2, len2);
Christopher Faulet908628c2022-03-25 16:43:49 +01004568 co_skip(cs_oc(cs), len1 + len2);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004569 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004570 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004571
4572 } else {
4573
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004574 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004575 if (len1 > len)
4576 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004577 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004578 len -= len1;
4579
4580 /* Copy the second block. */
4581 if (len2 > len)
4582 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004583 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004584 len -= len2;
4585
4586 /* Consume input channel output buffer data. */
Christopher Faulet908628c2022-03-25 16:43:49 +01004587 co_skip(cs_oc(cs), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004588
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004589 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004590 if (len > 0) {
4591 lua_pushinteger(L, len);
4592 lua_replace(L, 2);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004593 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004594 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004595 }
4596
4597 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004598 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004599 return 1;
4600 }
4601
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004602 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004603 hlua_pusherror(L, "Lua: internal error");
4604 WILL_LJMP(lua_error(L));
4605 return 0;
4606}
4607
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004608/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004609__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4610{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004611 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004612 int len = -1;
4613
4614 if (lua_gettop(L) > 2)
4615 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4616 if (lua_gettop(L) >= 2) {
4617 len = MAY_LJMP(luaL_checkinteger(L, 2));
4618 lua_pop(L, 1);
4619 }
4620
4621 /* Confirm or set the required length */
4622 lua_pushinteger(L, len);
4623
4624 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004625 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004626
4627 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4628}
4629
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004630/* Append data in the output side of the buffer. This data is immediately
4631 * sent. The function returns the amount of data written. If the buffer
4632 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004633 * if the channel is closed.
4634 */
4635__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4636{
4637 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004638 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004639 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4640 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet908628c2022-03-25 16:43:49 +01004641 struct conn_stream *cs = luactx->appctx->owner;
4642 struct channel *chn = cs_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004643 int max;
4644
4645 /* Get the max amount of data which can write as input in the channel. */
4646 max = channel_recv_max(chn);
4647 if (max > (len - l))
4648 max = len - l;
4649
4650 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004651 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004652
4653 /* update counters. */
4654 l += max;
4655 lua_pop(L, 1);
4656 lua_pushinteger(L, l);
4657
4658 /* If some data is not send, declares the situation to the
4659 * applet, and returns a yield.
4660 */
4661 if (l < len) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02004662 cs_rx_room_blk(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02004663 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004664 }
4665
4666 return 1;
4667}
4668
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004669/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004670 * yield the LUA process, and resume it without checking the
4671 * input arguments.
4672 */
4673__LJMP static int hlua_applet_tcp_send(lua_State *L)
4674{
4675 MAY_LJMP(check_args(L, 2, "send"));
4676 lua_pushinteger(L, 0);
4677
4678 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4679}
4680
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004681/*
4682 *
4683 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004684 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004685 *
4686 *
4687 */
4688
4689/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004690 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004691 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004692__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004693{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004694 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004695}
4696
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004697/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004698 * according with a current TXN.
4699 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004700static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004701{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004702 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004703 struct hlua_txn htxn;
Christopher Faulet908628c2022-03-25 16:43:49 +01004704 struct stream *s = __cs_strm(ctx->owner);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004705 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004706 struct htx *htx;
4707 struct htx_blk *blk;
4708 struct htx_sl *sl;
4709 struct ist path;
4710 unsigned long long len = 0;
4711 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004712 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004713
4714 /* Check stack size. */
4715 if (!lua_checkstack(L, 3))
4716 return 0;
4717
4718 /* Create the object: obj[0] = userdata.
4719 * Note that the base of the Converters object is the
4720 * same than the TXN object.
4721 */
4722 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004723 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004724 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004725 luactx->appctx = ctx;
4726 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4727 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4728 luactx->htxn.s = s;
4729 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004730
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004731 /* Create the "f" field that contains a list of fetches. */
4732 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004733 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004734 return 0;
4735 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004736
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004737 /* Create the "sf" field that contains a list of stringsafe fetches. */
4738 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004739 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004740 return 0;
4741 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004742
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004743 /* Create the "c" field that contains a list of converters. */
4744 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004745 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004746 return 0;
4747 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004748
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004749 /* Create the "sc" field that contains a list of stringsafe converters. */
4750 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004751 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004752 return 0;
4753 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004754
Christopher Fauleta2097962019-07-15 16:25:33 +02004755 htx = htxbuf(&s->req.buf);
4756 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004757 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004758 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004759
Christopher Fauleta2097962019-07-15 16:25:33 +02004760 /* Stores the request method. */
4761 lua_pushstring(L, "method");
4762 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4763 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004764
Christopher Fauleta2097962019-07-15 16:25:33 +02004765 /* Stores the http version. */
4766 lua_pushstring(L, "version");
4767 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4768 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004769
Christopher Fauleta2097962019-07-15 16:25:33 +02004770 /* creates an array of headers. hlua_http_get_headers() crates and push
4771 * the array on the top of the stack.
4772 */
4773 lua_pushstring(L, "headers");
4774 htxn.s = s;
4775 htxn.p = px;
4776 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004777 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004778 return 0;
4779 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004780
Amaury Denoyellec453f952021-07-06 11:40:12 +02004781 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4782 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004783 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004784 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004785
Christopher Fauleta2097962019-07-15 16:25:33 +02004786 p = path.ptr;
Tim Duesterhus4c8f75f2021-11-06 15:14:44 +01004787 end = istend(path);
Christopher Fauleta2097962019-07-15 16:25:33 +02004788 q = p;
4789 while (q < end && *q != '?')
4790 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004791
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004792 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004793 lua_pushstring(L, "path");
4794 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004795 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004796
Christopher Fauleta2097962019-07-15 16:25:33 +02004797 /* Stores the query string. */
4798 lua_pushstring(L, "qs");
4799 if (*q == '?')
4800 q++;
4801 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004802 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004803 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004804
Christopher Fauleta2097962019-07-15 16:25:33 +02004805 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4806 struct htx_blk *blk = htx_get_blk(htx, pos);
4807 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004808
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004809 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004810 break;
4811 if (type == HTX_BLK_DATA)
4812 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004813 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004814 if (htx->extra != ULLONG_MAX)
4815 len += htx->extra;
4816
4817 /* Stores the request path. */
4818 lua_pushstring(L, "length");
4819 lua_pushinteger(L, len);
4820 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004822 /* Create an empty array of HTTP request headers. */
4823 lua_pushstring(L, "response");
4824 lua_newtable(L);
4825 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004826
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004827 /* Pop a class stream metatable and affect it to the table. */
4828 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4829 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004830
4831 return 1;
4832}
4833
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004834__LJMP static int hlua_applet_http_set_var(lua_State *L)
4835{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004836 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004837 struct stream *s;
4838 const char *name;
4839 size_t len;
4840 struct sample smp;
4841
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004842 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4843 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004844
4845 /* It is useles to retrieve the stream, but this function
4846 * runs only in a stream context.
4847 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004848 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004849 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004850 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004851
4852 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004853 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004854 hlua_lua2smp(L, 3, &smp);
4855
4856 /* Store the sample in a variable. */
4857 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004858
4859 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4860 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4861 else
4862 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4863
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004864 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004865}
4866
4867__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4868{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004869 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004870 struct stream *s;
4871 const char *name;
4872 size_t len;
4873 struct sample smp;
4874
4875 MAY_LJMP(check_args(L, 2, "unset_var"));
4876
4877 /* It is useles to retrieve the stream, but this function
4878 * runs only in a stream context.
4879 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004880 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004881 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004882 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004883
4884 /* Unset the variable. */
4885 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004886 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4887 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004888}
4889
4890__LJMP static int hlua_applet_http_get_var(lua_State *L)
4891{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004892 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004893 struct stream *s;
4894 const char *name;
4895 size_t len;
4896 struct sample smp;
4897
4898 MAY_LJMP(check_args(L, 2, "get_var"));
4899
4900 /* It is useles to retrieve the stream, but this function
4901 * runs only in a stream context.
4902 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004903 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004904 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004905 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004906
4907 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004908 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004909 lua_pushnil(L);
4910 return 1;
4911 }
4912
4913 return hlua_smp2lua(L, &smp);
4914}
4915
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004916__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4917{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004918 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4919 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004920 struct hlua *hlua;
4921
4922 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004923 if (!s->hlua)
4924 return 0;
4925 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004926
4927 MAY_LJMP(check_args(L, 2, "set_priv"));
4928
4929 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004930 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004931
4932 /* Get and store new value. */
4933 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4934 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4935
4936 return 0;
4937}
4938
4939__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4940{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004941 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4942 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004943 struct hlua *hlua;
4944
4945 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004946 if (!s->hlua) {
4947 lua_pushnil(L);
4948 return 1;
4949 }
4950 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004951
4952 /* Push configuration index in the stack. */
4953 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4954
4955 return 1;
4956}
4957
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004958/* If expected data not yet available, it returns a yield. This function
4959 * consumes the data in the buffer. It returns a string containing the
4960 * data. This string can be empty.
4961 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004962__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004963{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004964 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01004965 struct conn_stream *cs = luactx->appctx->owner;
4966 struct channel *req = cs_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004967 struct htx *htx;
4968 struct htx_blk *blk;
4969 size_t count;
4970 int stop = 0;
4971
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004972 htx = htx_from_buf(&req->buf);
4973 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004974 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004975
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004976 while (count && !stop && blk) {
4977 enum htx_blk_type type = htx_get_blk_type(blk);
4978 uint32_t sz = htx_get_blksz(blk);
4979 struct ist v;
4980 uint32_t vlen;
4981 char *nl;
4982
4983 vlen = sz;
4984 if (vlen > count) {
4985 if (type != HTX_BLK_DATA)
4986 break;
4987 vlen = count;
4988 }
4989
4990 switch (type) {
4991 case HTX_BLK_UNUSED:
4992 break;
4993
4994 case HTX_BLK_DATA:
4995 v = htx_get_blk_value(htx, blk);
4996 v.len = vlen;
4997 nl = istchr(v, '\n');
4998 if (nl != NULL) {
4999 stop = 1;
5000 vlen = nl - v.ptr + 1;
5001 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005002 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005003 break;
5004
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005005 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005006 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005007 stop = 1;
5008 break;
5009
5010 default:
5011 break;
5012 }
5013
Willy Tarreau84240042022-02-28 16:51:23 +01005014 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005015 count -= vlen;
5016 if (sz == vlen)
5017 blk = htx_remove_blk(htx, blk);
5018 else {
5019 htx_cut_data_blk(htx, blk, vlen);
5020 break;
5021 }
5022 }
5023
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005024 /* The message was fully consumed and no more data are expected
5025 * (EOM flag set).
5026 */
5027 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5028 stop = 1;
5029
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005030 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005031 if (!stop) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005032 cs_cant_get(cs);
Christopher Fauleta2097962019-07-15 16:25:33 +02005033 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005034 }
5035
5036 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005037 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005038 return 1;
5039}
5040
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005041
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005042/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005043__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005044{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005045 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005046
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005047 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005048 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005049
Christopher Fauleta2097962019-07-15 16:25:33 +02005050 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005051}
5052
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005053/* If expected data not yet available, it returns a yield. This function
5054 * consumes the data in the buffer. It returns a string containing the
5055 * data. This string can be empty.
5056 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005057__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005058{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005059 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01005060 struct conn_stream *cs = luactx->appctx->owner;
5061 struct channel *req = cs_oc(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005062 struct htx *htx;
5063 struct htx_blk *blk;
5064 size_t count;
5065 int len;
5066
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005067 htx = htx_from_buf(&req->buf);
5068 len = MAY_LJMP(luaL_checkinteger(L, 2));
5069 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005070 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005071 while (count && len && blk) {
5072 enum htx_blk_type type = htx_get_blk_type(blk);
5073 uint32_t sz = htx_get_blksz(blk);
5074 struct ist v;
5075 uint32_t vlen;
5076
5077 vlen = sz;
5078 if (len > 0 && vlen > len)
5079 vlen = len;
5080 if (vlen > count) {
5081 if (type != HTX_BLK_DATA)
5082 break;
5083 vlen = count;
5084 }
5085
5086 switch (type) {
5087 case HTX_BLK_UNUSED:
5088 break;
5089
5090 case HTX_BLK_DATA:
5091 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005092 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005093 break;
5094
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005095 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005096 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005097 len = 0;
5098 break;
5099
5100 default:
5101 break;
5102 }
5103
Willy Tarreau84240042022-02-28 16:51:23 +01005104 c_rew(req, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005105 count -= vlen;
5106 if (len > 0)
5107 len -= vlen;
5108 if (sz == vlen)
5109 blk = htx_remove_blk(htx, blk);
5110 else {
5111 htx_cut_data_blk(htx, blk, vlen);
5112 break;
5113 }
5114 }
5115
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005116 /* The message was fully consumed and no more data are expected
5117 * (EOM flag set).
5118 */
5119 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5120 len = 0;
5121
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005122 htx_to_buf(htx, &req->buf);
5123
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005124 /* If we are no other data available, yield waiting for new data. */
5125 if (len) {
5126 if (len > 0) {
5127 lua_pushinteger(L, len);
5128 lua_replace(L, 2);
5129 }
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005130 cs_cant_get(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02005131 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005132 }
5133
5134 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005135 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005136 return 1;
5137}
5138
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005139/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005140__LJMP static int hlua_applet_http_recv(lua_State *L)
5141{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005142 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005143 int len = -1;
5144
5145 /* Check arguments. */
5146 if (lua_gettop(L) > 2)
5147 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5148 if (lua_gettop(L) >= 2) {
5149 len = MAY_LJMP(luaL_checkinteger(L, 2));
5150 lua_pop(L, 1);
5151 }
5152
Christopher Fauleta2097962019-07-15 16:25:33 +02005153 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005154
Christopher Fauleta2097962019-07-15 16:25:33 +02005155 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005156 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005157
Christopher Fauleta2097962019-07-15 16:25:33 +02005158 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005159}
5160
5161/* Append data in the output side of the buffer. This data is immediately
5162 * sent. The function returns the amount of data written. If the buffer
5163 * cannot contain the data, the function yields. The function returns -1
5164 * if the channel is closed.
5165 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005166__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005167{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005168 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01005169 struct conn_stream *cs = luactx->appctx->owner;
5170 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005171 struct htx *htx = htx_from_buf(&res->buf);
5172 const char *data;
5173 size_t len;
5174 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5175 int max;
5176
Christopher Faulet9060fc02019-07-03 11:39:30 +02005177 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005178 if (!max)
5179 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005180
5181 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5182
5183 /* Get the max amount of data which can write as input in the channel. */
5184 if (max > (len - l))
5185 max = len - l;
5186
5187 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005188 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005189 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005190
5191 /* update counters. */
5192 l += max;
5193 lua_pop(L, 1);
5194 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005195
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005196 /* If some data is not send, declares the situation to the
5197 * applet, and returns a yield.
5198 */
5199 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005200 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005201 htx_to_buf(htx, &res->buf);
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005202 cs_rx_room_blk(cs);
Willy Tarreau9635e032018-10-16 17:52:55 +02005203 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005204 }
5205
Christopher Fauleta2097962019-07-15 16:25:33 +02005206 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005207 return 1;
5208}
5209
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005210/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005211 * yield the LUA process, and resume it without checking the
5212 * input arguments.
5213 */
5214__LJMP static int hlua_applet_http_send(lua_State *L)
5215{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005216 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005217
5218 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005219 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005220 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5221 WILL_LJMP(lua_error(L));
5222 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005223
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005224 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005225 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005226
Christopher Fauleta2097962019-07-15 16:25:33 +02005227 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005228}
5229
5230__LJMP static int hlua_applet_http_addheader(lua_State *L)
5231{
5232 const char *name;
5233 int ret;
5234
5235 MAY_LJMP(hlua_checkapplet_http(L, 1));
5236 name = MAY_LJMP(luaL_checkstring(L, 2));
5237 MAY_LJMP(luaL_checkstring(L, 3));
5238
5239 /* Push in the stack the "response" entry. */
5240 ret = lua_getfield(L, 1, "response");
5241 if (ret != LUA_TTABLE) {
5242 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5243 "is expected as an array. %s found", lua_typename(L, ret));
5244 WILL_LJMP(lua_error(L));
5245 }
5246
5247 /* check if the header is already registered if it is not
5248 * the case, register it.
5249 */
5250 ret = lua_getfield(L, -1, name);
5251 if (ret == LUA_TNIL) {
5252
5253 /* Entry not found. */
5254 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5255
5256 /* Insert the new header name in the array in the top of the stack.
5257 * It left the new array in the top of the stack.
5258 */
5259 lua_newtable(L);
5260 lua_pushvalue(L, 2);
5261 lua_pushvalue(L, -2);
5262 lua_settable(L, -4);
5263
5264 } else if (ret != LUA_TTABLE) {
5265
5266 /* corruption error. */
5267 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5268 "is expected as an array. %s found", name, lua_typename(L, ret));
5269 WILL_LJMP(lua_error(L));
5270 }
5271
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005272 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005273 * the header value as new entry.
5274 */
5275 lua_pushvalue(L, 3);
5276 ret = lua_rawlen(L, -2);
5277 lua_rawseti(L, -2, ret + 1);
5278 lua_pushboolean(L, 1);
5279 return 1;
5280}
5281
5282__LJMP static int hlua_applet_http_status(lua_State *L)
5283{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005284 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005285 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005286 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005287
5288 if (status < 100 || status > 599) {
5289 lua_pushboolean(L, 0);
5290 return 1;
5291 }
5292
Willy Tarreau7e702d12021-04-28 17:59:21 +02005293 luactx->appctx->ctx.hlua_apphttp.status = status;
5294 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005295 lua_pushboolean(L, 1);
5296 return 1;
5297}
5298
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005299
Christopher Fauleta2097962019-07-15 16:25:33 +02005300__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005301{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005302 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01005303 struct conn_stream *cs = luactx->appctx->owner;
5304 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005305 struct htx *htx;
5306 struct htx_sl *sl;
5307 struct h1m h1m;
5308 const char *status, *reason;
5309 const char *name, *value;
5310 size_t nlen, vlen;
5311 unsigned int flags;
5312
5313 /* Send the message at once. */
5314 htx = htx_from_buf(&res->buf);
5315 h1m_init_res(&h1m);
5316
5317 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005318 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5319 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005320 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005321 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5322 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005323 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5324 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5325 }
5326 else {
5327 flags = HTX_SL_F_IS_RESP;
5328 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5329 }
5330 if (!sl) {
5331 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005332 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005333 WILL_LJMP(lua_error(L));
5334 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005335 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005336
5337 /* Get the array associated to the field "response" in the object AppletHTTP. */
5338 lua_pushvalue(L, 0);
5339 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5340 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005341 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005342 WILL_LJMP(lua_error(L));
5343 }
5344
5345 /* Browse the list of headers. */
5346 lua_pushnil(L);
5347 while(lua_next(L, -2) != 0) {
5348 /* We expect a string as -2. */
5349 if (lua_type(L, -2) != LUA_TSTRING) {
5350 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005351 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005352 lua_typename(L, lua_type(L, -2)));
5353 WILL_LJMP(lua_error(L));
5354 }
5355 name = lua_tolstring(L, -2, &nlen);
5356
5357 /* We expect an array as -1. */
5358 if (lua_type(L, -1) != LUA_TTABLE) {
5359 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 +02005360 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005361 name,
5362 lua_typename(L, lua_type(L, -1)));
5363 WILL_LJMP(lua_error(L));
5364 }
5365
5366 /* Browse the table who is on the top of the stack. */
5367 lua_pushnil(L);
5368 while(lua_next(L, -2) != 0) {
5369 int id;
5370
5371 /* We expect a number as -2. */
5372 if (lua_type(L, -2) != LUA_TNUMBER) {
5373 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 +02005374 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005375 name,
5376 lua_typename(L, lua_type(L, -2)));
5377 WILL_LJMP(lua_error(L));
5378 }
5379 id = lua_tointeger(L, -2);
5380
5381 /* We expect a string as -2. */
5382 if (lua_type(L, -1) != LUA_TSTRING) {
5383 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 +02005384 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005385 name, id,
5386 lua_typename(L, lua_type(L, -1)));
5387 WILL_LJMP(lua_error(L));
5388 }
5389 value = lua_tolstring(L, -1, &vlen);
5390
5391 /* Simple Protocol checks. */
Christopher Faulet545fbba2021-09-28 09:36:25 +02005392 if (isteqi(ist2(name, nlen), ist("transfer-encoding"))) {
5393 int ret;
5394
5395 ret = h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
5396 if (ret < 0) {
5397 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
5398 luactx->appctx->rule->arg.hlua_rule->fcn->name,
5399 name);
5400 WILL_LJMP(lua_error(L));
5401 }
5402 else if (ret == 0)
5403 goto next; /* Skip it */
5404 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005405 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5406 struct ist v = ist2(value, vlen);
5407 int ret;
5408
5409 ret = h1_parse_cont_len_header(&h1m, &v);
5410 if (ret < 0) {
5411 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005412 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005413 name);
5414 WILL_LJMP(lua_error(L));
5415 }
5416 else if (ret == 0)
5417 goto next; /* Skip it */
5418 }
5419
5420 /* Add a new header */
5421 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5422 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005423 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005424 name);
5425 WILL_LJMP(lua_error(L));
5426 }
5427 next:
5428 /* Remove the array from the stack, and get next element with a remaining string. */
5429 lua_pop(L, 1);
5430 }
5431
5432 /* Remove the array from the stack, and get next element with a remaining string. */
5433 lua_pop(L, 1);
5434 }
5435
5436 if (h1m.flags & H1_MF_CHNK)
5437 h1m.flags &= ~H1_MF_CLEN;
5438 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5439 h1m.flags |= H1_MF_XFER_LEN;
5440
5441 /* Uset HTX start-line flags */
5442 if (h1m.flags & H1_MF_XFER_ENC)
5443 flags |= HTX_SL_F_XFER_ENC;
5444 if (h1m.flags & H1_MF_XFER_LEN) {
5445 flags |= HTX_SL_F_XFER_LEN;
5446 if (h1m.flags & H1_MF_CHNK)
5447 flags |= HTX_SL_F_CHNK;
5448 else if (h1m.flags & H1_MF_CLEN)
5449 flags |= HTX_SL_F_CLEN;
5450 if (h1m.body_len == 0)
5451 flags |= HTX_SL_F_BODYLESS;
5452 }
5453 sl->flags |= flags;
5454
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005455 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005456 * and the status code implies the presence of a message body, we must
5457 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005458 * for the keepalive compliance. If the applet announces a transfer-encoding
5459 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005460 */
5461 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005462 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5463 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5464 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005465 /* Add a new header */
5466 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5467 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5468 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005469 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005470 WILL_LJMP(lua_error(L));
5471 }
5472 }
5473
5474 /* Finalize headers. */
5475 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5476 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005477 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005478 WILL_LJMP(lua_error(L));
5479 }
5480
5481 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5482 b_reset(&res->buf);
5483 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5484 WILL_LJMP(lua_error(L));
5485 }
5486
5487 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005488 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005489
5490 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005491 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005492 return 0;
5493
5494}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005495/* We will build the status line and the headers of the HTTP response.
5496 * We will try send at once if its not possible, we give back the hand
5497 * waiting for more room.
5498 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005499__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005500{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005501 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Christopher Faulet908628c2022-03-25 16:43:49 +01005502 struct conn_stream *cs = luactx->appctx->owner;
5503 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005504
5505 if (co_data(res)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02005506 cs_rx_room_blk(cs);
Christopher Fauleta2097962019-07-15 16:25:33 +02005507 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005508 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005509 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005510}
5511
5512
Christopher Fauleta2097962019-07-15 16:25:33 +02005513__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005514{
Christopher Fauleta2097962019-07-15 16:25:33 +02005515 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005516}
5517
Christopher Fauleta2097962019-07-15 16:25:33 +02005518/*
5519 *
5520 *
5521 * Class HTTP
5522 *
5523 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005524 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005525
5526/* Returns a struct hlua_txn if the stack entry "ud" is
5527 * a class stream, otherwise it throws an error.
5528 */
5529__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005530{
Christopher Fauleta2097962019-07-15 16:25:33 +02005531 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5532}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005533
Christopher Fauleta2097962019-07-15 16:25:33 +02005534/* This function creates and push in the stack a HTTP object
5535 * according with a current TXN.
5536 */
5537static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5538{
5539 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005540
Christopher Fauleta2097962019-07-15 16:25:33 +02005541 /* Check stack size. */
5542 if (!lua_checkstack(L, 3))
5543 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005544
Christopher Fauleta2097962019-07-15 16:25:33 +02005545 /* Create the object: obj[0] = userdata.
5546 * Note that the base of the Converters object is the
5547 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005548 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005549 lua_newtable(L);
5550 htxn = lua_newuserdata(L, sizeof(*htxn));
5551 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005552
5553 htxn->s = txn->s;
5554 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005555 htxn->dir = txn->dir;
5556 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005557
5558 /* Pop a class stream metatable and affect it to the table. */
5559 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5560 lua_setmetatable(L, -2);
5561
5562 return 1;
5563}
5564
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005565/* This function creates and returns an array containing the status-line
5566 * elements. This function does not fails.
5567 */
5568__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5569{
5570 /* Create the table. */
5571 lua_newtable(L);
5572
5573 if (sl->flags & HTX_SL_F_IS_RESP) {
5574 lua_pushstring(L, "version");
5575 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5576 lua_settable(L, -3);
5577 lua_pushstring(L, "code");
5578 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5579 lua_settable(L, -3);
5580 lua_pushstring(L, "reason");
5581 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5582 lua_settable(L, -3);
5583 }
5584 else {
5585 lua_pushstring(L, "method");
5586 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5587 lua_settable(L, -3);
5588 lua_pushstring(L, "uri");
5589 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5590 lua_settable(L, -3);
5591 lua_pushstring(L, "version");
5592 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5593 lua_settable(L, -3);
5594 }
5595 return 1;
5596}
5597
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005598/* This function creates ans returns an array of HTTP headers.
5599 * This function does not fails. It is used as wrapper with the
5600 * 2 following functions.
5601 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005602__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005603{
Christopher Fauleta2097962019-07-15 16:25:33 +02005604 struct htx *htx;
5605 int32_t pos;
5606
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005607 /* Create the table. */
5608 lua_newtable(L);
5609
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005610
Christopher Fauleta2097962019-07-15 16:25:33 +02005611 htx = htxbuf(&msg->chn->buf);
5612 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5613 struct htx_blk *blk = htx_get_blk(htx, pos);
5614 enum htx_blk_type type = htx_get_blk_type(blk);
5615 struct ist n, v;
5616 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005617
Christopher Fauleta2097962019-07-15 16:25:33 +02005618 if (type == HTX_BLK_HDR) {
5619 n = htx_get_blk_name(htx,blk);
5620 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005621 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005622 else if (type == HTX_BLK_EOH)
5623 break;
5624 else
5625 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005626
Christopher Fauleta2097962019-07-15 16:25:33 +02005627 /* Check for existing entry:
5628 * assume that the table is on the top of the stack, and
5629 * push the key in the stack, the function lua_gettable()
5630 * perform the lookup.
5631 */
5632 lua_pushlstring(L, n.ptr, n.len);
5633 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005634
Christopher Fauleta2097962019-07-15 16:25:33 +02005635 switch (lua_type(L, -1)) {
5636 case LUA_TNIL:
5637 /* Table not found, create it. */
5638 lua_pop(L, 1); /* remove the nil value. */
5639 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5640 lua_newtable(L); /* create and push empty table. */
5641 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5642 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5643 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005644 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005645
Christopher Fauleta2097962019-07-15 16:25:33 +02005646 case LUA_TTABLE:
5647 /* Entry found: push the value in the table. */
5648 len = lua_rawlen(L, -1);
5649 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5650 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5651 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5652 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005653
Christopher Fauleta2097962019-07-15 16:25:33 +02005654 default:
5655 /* Other cases are errors. */
5656 hlua_pusherror(L, "internal error during the parsing of headers.");
5657 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005658 }
5659 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005660 return 1;
5661}
5662
5663__LJMP static int hlua_http_req_get_headers(lua_State *L)
5664{
5665 struct hlua_txn *htxn;
5666
5667 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5668 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5669
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005670 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005671 WILL_LJMP(lua_error(L));
5672
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005673 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005674}
5675
5676__LJMP static int hlua_http_res_get_headers(lua_State *L)
5677{
5678 struct hlua_txn *htxn;
5679
5680 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5681 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5682
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005683 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005684 WILL_LJMP(lua_error(L));
5685
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005686 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005687}
5688
5689/* This function replace full header, or just a value in
5690 * the request or in the response. It is a wrapper fir the
5691 * 4 following functions.
5692 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005693__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005694{
5695 size_t name_len;
5696 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5697 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5698 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005699 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005700 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005701
Dragan Dosen26743032019-04-30 15:54:36 +02005702 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005703 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5704
Christopher Fauleta2097962019-07-15 16:25:33 +02005705 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005706 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005707 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005708 return 0;
5709}
5710
5711__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5712{
5713 struct hlua_txn *htxn;
5714
5715 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5716 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5717
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005718 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005719 WILL_LJMP(lua_error(L));
5720
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005721 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005722}
5723
5724__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5725{
5726 struct hlua_txn *htxn;
5727
5728 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5729 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5730
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005731 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005732 WILL_LJMP(lua_error(L));
5733
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005734 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005735}
5736
5737__LJMP static int hlua_http_req_rep_val(lua_State *L)
5738{
5739 struct hlua_txn *htxn;
5740
5741 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5742 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5743
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005744 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005745 WILL_LJMP(lua_error(L));
5746
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005747 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005748}
5749
5750__LJMP static int hlua_http_res_rep_val(lua_State *L)
5751{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005752 struct hlua_txn *htxn;
5753
5754 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5755 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5756
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005757 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005758 WILL_LJMP(lua_error(L));
5759
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005760 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005761}
5762
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005763/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005764 * It is a wrapper for the 2 following functions.
5765 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005766__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005767{
5768 size_t len;
5769 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005770 struct htx *htx = htxbuf(&msg->chn->buf);
5771 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005772
Christopher Fauleta2097962019-07-15 16:25:33 +02005773 ctx.blk = NULL;
5774 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5775 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005776 return 0;
5777}
5778
5779__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5780{
5781 struct hlua_txn *htxn;
5782
5783 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5784 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5785
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005786 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005787 WILL_LJMP(lua_error(L));
5788
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005789 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005790}
5791
5792__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5793{
5794 struct hlua_txn *htxn;
5795
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005796 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005797 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5798
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005799 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005800 WILL_LJMP(lua_error(L));
5801
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005802 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005803}
5804
5805/* This function adds an header. It is a wrapper used by
5806 * the 2 following functions.
5807 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005808__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005809{
5810 size_t name_len;
5811 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5812 size_t value_len;
5813 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005814 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005815
Christopher Fauleta2097962019-07-15 16:25:33 +02005816 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5817 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005818 return 0;
5819}
5820
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005821__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5822{
5823 struct hlua_txn *htxn;
5824
5825 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5826 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5827
5828 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5829 WILL_LJMP(lua_error(L));
5830
5831 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5832}
5833
5834__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5835{
5836 struct hlua_txn *htxn;
5837
5838 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5839 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5840
5841 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5842 WILL_LJMP(lua_error(L));
5843
5844 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5845}
5846
5847static int hlua_http_req_set_hdr(lua_State *L)
5848{
5849 struct hlua_txn *htxn;
5850
5851 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5852 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5853
5854 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5855 WILL_LJMP(lua_error(L));
5856
5857 hlua_http_del_hdr(L, &htxn->s->txn->req);
5858 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5859}
5860
5861static int hlua_http_res_set_hdr(lua_State *L)
5862{
5863 struct hlua_txn *htxn;
5864
5865 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5866 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5867
5868 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5869 WILL_LJMP(lua_error(L));
5870
5871 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5872 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5873}
5874
5875/* This function set the method. */
5876static int hlua_http_req_set_meth(lua_State *L)
5877{
5878 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5879 size_t name_len;
5880 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5881
5882 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5883 WILL_LJMP(lua_error(L));
5884
5885 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5886 return 1;
5887}
5888
5889/* This function set the method. */
5890static int hlua_http_req_set_path(lua_State *L)
5891{
5892 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5893 size_t name_len;
5894 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5895
5896 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5897 WILL_LJMP(lua_error(L));
5898
5899 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5900 return 1;
5901}
5902
5903/* This function set the query-string. */
5904static int hlua_http_req_set_query(lua_State *L)
5905{
5906 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5907 size_t name_len;
5908 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5909
5910 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5911 WILL_LJMP(lua_error(L));
5912
5913 /* Check length. */
5914 if (name_len > trash.size - 1) {
5915 lua_pushboolean(L, 0);
5916 return 1;
5917 }
5918
5919 /* Add the mark question as prefix. */
5920 chunk_reset(&trash);
5921 trash.area[trash.data++] = '?';
5922 memcpy(trash.area + trash.data, name, name_len);
5923 trash.data += name_len;
5924
5925 lua_pushboolean(L,
5926 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5927 return 1;
5928}
5929
5930/* This function set the uri. */
5931static int hlua_http_req_set_uri(lua_State *L)
5932{
5933 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5934 size_t name_len;
5935 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5936
5937 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5938 WILL_LJMP(lua_error(L));
5939
5940 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5941 return 1;
5942}
5943
5944/* This function set the response code & optionally reason. */
5945static int hlua_http_res_set_status(lua_State *L)
5946{
5947 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5948 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5949 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5950 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5951
5952 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5953 WILL_LJMP(lua_error(L));
5954
5955 http_res_set_status(code, reason, htxn->s);
5956 return 0;
5957}
5958
5959/*
5960 *
5961 *
5962 * Class HTTPMessage
5963 *
5964 *
5965 */
5966
5967/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5968 * otherwise it throws an error.
5969 */
5970__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5971{
5972 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5973}
5974
5975/* Creates and pushes on the stack a HTTP object according with a current TXN.
5976 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005977static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005978{
5979 /* Check stack size. */
5980 if (!lua_checkstack(L, 3))
5981 return 0;
5982
5983 lua_newtable(L);
5984 lua_pushlightuserdata(L, msg);
5985 lua_rawseti(L, -2, 0);
5986
5987 /* Create the "channel" field that contains the request channel object. */
5988 lua_pushstring(L, "channel");
5989 if (!hlua_channel_new(L, msg->chn))
5990 return 0;
5991 lua_rawset(L, -3);
5992
5993 /* Pop a class stream metatable and affect it to the table. */
5994 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5995 lua_setmetatable(L, -2);
5996
5997 return 1;
5998}
5999
6000/* Helper function returning a filter attached to the HTTP message at the
6001 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006002 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006003 * filled with output and input length respectively.
6004 */
6005static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
6006{
6007 struct channel *chn = msg->chn;
6008 struct htx *htx = htxbuf(&chn->buf);
6009 struct filter *filter = NULL;
6010
6011 *offset = co_data(msg->chn);
6012 *len = htx->data - co_data(msg->chn);
6013
6014 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
6015 filter = lua_touserdata (L, -1);
6016 if (msg->msg_state >= HTTP_MSG_DATA) {
6017 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6018
6019 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
6020 *len = flt_ctx->cur_len[CHN_IDX(chn)];
6021 }
6022 }
6023
6024 lua_pop(L, 1);
6025 return filter;
6026}
6027
6028/* Returns true if the channel attached to the HTTP message is the response
6029 * channel.
6030 */
6031__LJMP static int hlua_http_msg_is_resp(lua_State *L)
6032{
6033 struct http_msg *msg;
6034
6035 MAY_LJMP(check_args(L, 1, "is_resp"));
6036 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6037
6038 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
6039 return 1;
6040}
6041
6042/* Returns an array containing the elements status-line of the HTTP message. It relies
6043 * on hlua_http_get_stline().
6044 */
6045__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6046{
6047 struct http_msg *msg;
6048 struct htx *htx;
6049 struct htx_sl *sl;
6050
6051 MAY_LJMP(check_args(L, 1, "get_stline"));
6052 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6053
6054 if (msg->msg_state > HTTP_MSG_BODY)
6055 WILL_LJMP(lua_error(L));
6056
6057 htx = htxbuf(&msg->chn->buf);
6058 sl = http_get_stline(htx);
6059 if (!sl)
6060 return 0;
6061 return hlua_http_get_stline(L, sl);
6062}
6063
6064/* Returns an array containing all headers of the HTTP message. it relies on
6065 * hlua_http_get_headers().
6066 */
6067__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6068{
6069 struct http_msg *msg;
6070
6071 MAY_LJMP(check_args(L, 1, "get_headers"));
6072 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6073
6074 if (msg->msg_state > HTTP_MSG_BODY)
6075 WILL_LJMP(lua_error(L));
6076
6077 return hlua_http_get_headers(L, msg);
6078}
6079
6080/* Deletes all occurrences of an header in the HTTP message matching on its
6081 * name. It relies on hlua_http_del_hdr().
6082 */
6083__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6084{
6085 struct http_msg *msg;
6086
6087 MAY_LJMP(check_args(L, 2, "del_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_del_hdr(L, msg);
6094}
6095
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006096/* Matches the full value line 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_hdr(lua_State *L)
6101{
6102 struct http_msg *msg;
6103
6104 MAY_LJMP(check_args(L, 4, "rep_header"));
6105 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6106
6107 if (msg->msg_state > HTTP_MSG_BODY)
6108 WILL_LJMP(lua_error(L));
6109
6110 return hlua_http_rep_hdr(L, msg, 1);
6111}
6112
Ilya Shipitsinbd6b4be2021-10-15 16:18:21 +05006113/* Matches all comma-separated values of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006114 * message given its name against a regex and replaces it if it matches. It
6115 * relies on hlua_http_rep_hdr().
6116 */
6117__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6118{
6119 struct http_msg *msg;
6120
6121 MAY_LJMP(check_args(L, 4, "rep_value"));
6122 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6123
6124 if (msg->msg_state > HTTP_MSG_BODY)
6125 WILL_LJMP(lua_error(L));
6126
6127 return hlua_http_rep_hdr(L, msg, 0);
6128}
6129
6130/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6131__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6132{
6133 struct http_msg *msg;
6134
6135 MAY_LJMP(check_args(L, 3, "add_header"));
6136 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6137
6138 if (msg->msg_state > HTTP_MSG_BODY)
6139 WILL_LJMP(lua_error(L));
6140
6141 return hlua_http_add_hdr(L, msg);
6142}
6143
6144/* Add an header in the HTTP message removing existing headers with the same
6145 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6146 */
6147__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6148{
6149 struct http_msg *msg;
6150
6151 MAY_LJMP(check_args(L, 3, "set_header"));
6152 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6153
6154 if (msg->msg_state > HTTP_MSG_BODY)
6155 WILL_LJMP(lua_error(L));
6156
6157 hlua_http_del_hdr(L, msg);
6158 return hlua_http_add_hdr(L, msg);
6159}
6160
6161/* Rewrites the request method. It relies on http_req_replace_stline(). */
6162__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6163{
6164 struct stream *s;
6165 struct http_msg *msg;
6166 const char *name;
6167 size_t name_len;
6168
6169 MAY_LJMP(check_args(L, 2, "set_method"));
6170 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6171 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6172
6173 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6174 WILL_LJMP(lua_error(L));
6175
6176 s = chn_strm(msg->chn);
6177 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6178 return 1;
6179}
6180
6181/* Rewrites the request path. It relies on http_req_replace_stline(). */
6182__LJMP static int hlua_http_msg_set_path(lua_State *L)
6183{
6184 struct stream *s;
6185 struct http_msg *msg;
6186 const char *name;
6187 size_t name_len;
6188
6189 MAY_LJMP(check_args(L, 2, "set_path"));
6190 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6191 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6192
6193 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6194 WILL_LJMP(lua_error(L));
6195
6196 s = chn_strm(msg->chn);
6197 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6198 return 1;
6199}
6200
6201/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6202__LJMP static int hlua_http_msg_set_query(lua_State *L)
6203{
6204 struct stream *s;
6205 struct http_msg *msg;
6206 const char *name;
6207 size_t name_len;
6208
6209 MAY_LJMP(check_args(L, 2, "set_query"));
6210 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6211 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6212
6213 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6214 WILL_LJMP(lua_error(L));
6215
6216 /* Check length. */
6217 if (name_len > trash.size - 1) {
6218 lua_pushboolean(L, 0);
6219 return 1;
6220 }
6221
6222 /* Add the mark question as prefix. */
6223 chunk_reset(&trash);
6224 trash.area[trash.data++] = '?';
6225 memcpy(trash.area + trash.data, name, name_len);
6226 trash.data += name_len;
6227
6228 s = chn_strm(msg->chn);
6229 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6230 return 1;
6231}
6232
6233/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6234__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6235{
6236 struct stream *s;
6237 struct http_msg *msg;
6238 const char *name;
6239 size_t name_len;
6240
6241 MAY_LJMP(check_args(L, 2, "set_uri"));
6242 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6243 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6244
6245 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6246 WILL_LJMP(lua_error(L));
6247
6248 s = chn_strm(msg->chn);
6249 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6250 return 1;
6251}
6252
6253/* Rewrites the response status code. It relies on http_res_set_status(). */
6254__LJMP static int hlua_http_msg_set_status(lua_State *L)
6255{
6256 struct http_msg *msg;
6257 unsigned int code;
6258 const char *reason;
6259 size_t reason_len;
6260
6261 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6262 code = MAY_LJMP(luaL_checkinteger(L, 2));
6263 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6264
6265 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6266 WILL_LJMP(lua_error(L));
6267
6268 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6269 return 1;
6270}
6271
6272/* Returns true if the HTTP message is full. */
6273__LJMP static int hlua_http_msg_is_full(lua_State *L)
6274{
6275 struct http_msg *msg;
6276
6277 MAY_LJMP(check_args(L, 1, "is_full"));
6278 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6279 lua_pushboolean(L, channel_full(msg->chn, 0));
6280 return 1;
6281}
6282
6283/* Returns true if the HTTP message may still receive data. */
6284__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6285{
6286 struct http_msg *msg;
6287 struct htx *htx;
6288
6289 MAY_LJMP(check_args(L, 1, "may_recv"));
6290 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6291 htx = htxbuf(&msg->chn->buf);
6292 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6293 return 1;
6294}
6295
6296/* Returns true if the HTTP message EOM was received */
6297__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6298{
6299 struct http_msg *msg;
6300 struct htx *htx;
6301
6302 MAY_LJMP(check_args(L, 1, "may_recv"));
6303 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6304 htx = htxbuf(&msg->chn->buf);
6305 lua_pushboolean(L, !htx_expect_more(htx));
6306 return 1;
6307}
6308
6309/* Returns the number of bytes available in the input side of the HTTP
6310 * message. This function never fails.
6311 */
6312__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6313{
6314 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006315 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006316
6317 MAY_LJMP(check_args(L, 1, "input"));
6318 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006319 hlua_http_msg_filter(L, 1, msg, &output, &input);
6320 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006321 return 1;
6322}
6323
6324/* Returns the number of bytes available in the output side of the HTTP
6325 * message. This function never fails.
6326 */
6327__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6328{
6329 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006330 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006331
6332 MAY_LJMP(check_args(L, 1, "output"));
6333 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006334 hlua_http_msg_filter(L, 1, msg, &output, &input);
6335 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006336 return 1;
6337}
6338
6339/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6340 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006341 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006342 * block. This function is called during the payload filtering, so the headers
6343 * are already scheduled for output (from the filter point of view).
6344 */
6345static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6346{
6347 struct htx *htx = htxbuf(&msg->chn->buf);
6348 struct htx_blk *blk;
6349 struct htx_ret htxret;
6350 luaL_Buffer b;
6351 int ret = 0;
6352
6353 luaL_buffinit(L, &b);
6354 htxret = htx_find_offset(htx, offset);
6355 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6356 enum htx_blk_type type = htx_get_blk_type(blk);
6357 struct ist v;
6358
6359 switch (type) {
6360 case HTX_BLK_UNUSED:
6361 break;
6362
6363 case HTX_BLK_DATA:
6364 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006365 v = istadv(v, offset);
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006366 v = isttrim(v, len);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006367
6368 luaL_addlstring(&b, v.ptr, v.len);
6369 ret += v.len;
6370 break;
6371
6372 default:
vishnu0af4bd72021-10-24 06:46:24 +05306373 if (!ret)
6374 goto no_data;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006375 goto end;
6376 }
6377 offset = 0;
6378 }
6379
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006380end:
vishnu0af4bd72021-10-24 06:46:24 +05306381 if (!ret && (htx->flags & HTX_FL_EOM))
6382 goto no_data;
6383 luaL_pushresult(&b);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006384 return ret;
vishnu0af4bd72021-10-24 06:46:24 +05306385
6386 no_data:
6387 /* Remove the empty string and push nil on the stack */
6388 lua_pop(L, 1);
6389 lua_pushnil(L);
6390 return 0;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006391}
6392
6393/* Copies the string <str> to the HTTP message <msg> at the offset
6394 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006395 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006396 * the filter context.
6397 */
6398static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6399{
6400 struct htx *htx = htx_from_buf(&msg->chn->buf);
6401 struct htx_ret htxret;
6402 int /*max, */ret = 0;
6403
6404 /* Nothing to do, just return */
6405 if (unlikely(istlen(str) == 0))
6406 goto end;
6407
6408 if (istlen(str) > htx_free_data_space(htx)) {
6409 ret = -1;
6410 goto end;
6411 }
6412
6413 htxret = htx_find_offset(htx, offset);
6414 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6415 if (!htx_add_last_data(htx, str))
6416 goto end;
6417 }
6418 else {
6419 struct ist v = htx_get_blk_value(htx, htxret.blk);
6420 v.ptr += htxret.ret;
6421 v.len = 0;
6422 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6423 goto end;
6424 }
6425 ret = str.len;
6426 if (ret) {
6427 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6428 flt_update_offsets(filter, msg->chn, ret);
6429 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6430 }
6431
6432 end:
6433 htx_to_buf(htx, &msg->chn->buf);
6434 return ret;
6435}
6436
6437/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6438 * position <offset>. It stops on the first non-DATA HTX block. This function is
6439 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006440 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006441 * update the filter context.
6442 */
6443static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6444{
6445 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6446 struct htx *htx = htx_from_buf(&msg->chn->buf);
6447 struct htx_blk *blk;
6448 struct htx_ret htxret;
6449 size_t ret = 0;
6450
6451 /* Be sure <len> is always the amount of DATA to remove */
6452 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6453 htx_truncate(htx, offset);
6454 ret = len;
6455 goto end;
6456 }
6457
6458 htxret = htx_find_offset(htx, offset);
6459 blk = htxret.blk;
6460 if (htxret.ret) {
6461 struct ist v;
6462
6463 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6464 goto end;
6465 v = htx_get_blk_value(htx, blk);
6466 v.ptr += htxret.ret;
Tim Duesterhus2471f5c2021-11-08 09:05:01 +01006467 v = isttrim(v, len);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006468 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006469 len -= v.len;
6470 ret += v.len;
6471 }
6472
6473
6474 while (blk && len) {
6475 enum htx_blk_type type = htx_get_blk_type(blk);
6476 uint32_t sz = htx_get_blksz(blk);
6477
6478 switch (type) {
6479 case HTX_BLK_UNUSED:
6480 break;
6481
6482 case HTX_BLK_DATA:
6483 if (len < sz) {
6484 htx_cut_data_blk(htx, blk, len);
6485 ret += len;
6486 goto end;
6487 }
6488 break;
6489
6490 default:
6491 goto end;
6492 }
6493
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006494 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006495 len -= sz;
6496 ret += sz;
6497 blk = htx_remove_blk(htx, blk);
6498 }
6499
6500end:
6501 flt_update_offsets(filter, msg->chn, -ret);
6502 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6503 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6504 * to loose the EOM flag if the message is empty.
6505 */
6506}
6507
6508/* Copies input data found in an HTTP message. Unlike the channel function used
6509 * to duplicate raw data, this one can only be called inside a filter, from
6510 * http_payload callback. So it cannot yield. An exception is returned if it is
6511 * called from another callback. If nothing was copied, a nil value is pushed on
6512 * the stack.
6513 */
6514__LJMP static int hlua_http_msg_get_body(lua_State *L)
6515{
6516 struct http_msg *msg;
6517 struct filter *filter;
6518 size_t output, input;
6519 int offset, len;
6520
6521 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6522 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6523 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6524
6525 if (msg->msg_state < HTTP_MSG_DATA)
6526 WILL_LJMP(lua_error(L));
6527
6528 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6529 if (!filter || !hlua_filter_from_payload(filter))
6530 WILL_LJMP(lua_error(L));
6531
6532 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6533 lua_pushnil(L);
6534 return 1;
6535 }
6536
6537 offset = output;
6538 if (lua_gettop(L) > 1) {
6539 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6540 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006541 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006542 offset += output;
6543 if (offset < output || offset > input + output) {
6544 lua_pushfstring(L, "offset out of range.");
6545 WILL_LJMP(lua_error(L));
6546 }
6547 }
6548 len = output + input - offset;
6549 if (lua_gettop(L) == 3) {
6550 len = MAY_LJMP(luaL_checkinteger(L, 3));
6551 if (!len)
6552 goto dup;
6553 if (len == -1)
6554 len = global.tune.bufsize;
6555 if (len < 0) {
6556 lua_pushfstring(L, "length out of range.");
6557 WILL_LJMP(lua_error(L));
6558 }
6559 }
6560
6561 dup:
6562 _hlua_http_msg_dup(msg, L, offset, len);
6563 return 1;
6564}
6565
6566/* Appends a string to the HTTP message, after all existing DATA blocks but
6567 * before the trailers, if any. It returns the amount of data written or -1 if
6568 * nothing was copied. Unlike the channel function used to append data, this one
6569 * can only be called inside a filter, from http_payload callback. So it cannot
6570 * yield. An exception is returned if it is called from another callback.
6571 */
6572__LJMP static int hlua_http_msg_append(lua_State *L)
6573{
6574 struct http_msg *msg;
6575 struct filter *filter;
6576 const char *str;
6577 size_t offset, len, sz;
6578 int ret;
6579
6580 MAY_LJMP(check_args(L, 2, "append"));
6581 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6582
6583 if (msg->msg_state < HTTP_MSG_DATA)
6584 WILL_LJMP(lua_error(L));
6585
6586 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6587 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6588 if (!filter || !hlua_filter_from_payload(filter))
6589 WILL_LJMP(lua_error(L));
6590
6591 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6592 lua_pushinteger(L, ret);
6593 return 1;
6594}
6595
6596/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6597 * returns the amount of data written or -1 if nothing was copied. Unlike the
6598 * channel function used to prepend data, this one can only be called inside a
6599 * filter, from http_payload callback. So it cannot yield. An exception is
6600 * returned if it is called from another callback.
6601 */
6602__LJMP static int hlua_http_msg_prepend(lua_State *L)
6603{
6604 struct http_msg *msg;
6605 struct filter *filter;
6606 const char *str;
6607 size_t offset, len, sz;
6608 int ret;
6609
6610 MAY_LJMP(check_args(L, 2, "prepend"));
6611 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006612
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006613 if (msg->msg_state < HTTP_MSG_DATA)
6614 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006615
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006616 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6617 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6618 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006619 WILL_LJMP(lua_error(L));
6620
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006621 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6622 lua_pushinteger(L, ret);
6623 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006624}
6625
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006626/* Inserts a string to the HTTP message at a given offset. By default the string
6627 * is appended at the end of DATA blocks. It returns the amount of data written
6628 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6629 * this one can only be called inside a filter, from http_payload callback. So
6630 * it cannot yield. An exception is returned if it is called from another
6631 * callback.
6632 */
6633__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006634{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006635 struct http_msg *msg;
6636 struct filter *filter;
6637 const char *str;
6638 size_t input, output, sz;
6639 int offset;
6640 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006641
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006642 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6643 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6644 MAY_LJMP(check_args(L, 2, "insert"));
6645 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006646
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006647 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006648 WILL_LJMP(lua_error(L));
6649
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006650 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6651 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6652 if (!filter || !hlua_filter_from_payload(filter))
6653 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006654
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006655 offset = input + output;
6656 if (lua_gettop(L) > 2) {
6657 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6658 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006659 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006660 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006661 if (offset < output || offset > output + input) {
6662 lua_pushfstring(L, "offset out of range.");
6663 WILL_LJMP(lua_error(L));
6664 }
6665 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006666
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006667 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6668 lua_pushinteger(L, ret);
6669 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006670}
6671
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006672/* Removes a given amount of data from the HTTP message at a given offset. By
6673 * default all DATA blocks are removed. It returns the amount of data
6674 * removed. Unlike the channel function used to remove data, this one can only
6675 * be called inside a filter, from http_payload callback. So it cannot yield. An
6676 * exception is returned if it is called from another callback.
6677 */
6678__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006679{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006680 struct http_msg *msg;
6681 struct filter *filter;
6682 size_t input, output;
6683 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006684
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006685 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6686 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6687 MAY_LJMP(check_args(L, 2, "insert"));
6688 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006689
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006690 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006691 WILL_LJMP(lua_error(L));
6692
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006693 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6694 if (!filter || !hlua_filter_from_payload(filter))
6695 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006696
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006697 offset = input + output;
6698 if (lua_gettop(L) > 2) {
6699 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6700 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006701 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006702 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006703 if (offset < output || offset > output + input) {
6704 lua_pushfstring(L, "offset out of range.");
6705 WILL_LJMP(lua_error(L));
6706 }
6707 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006708
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006709 len = output + input - offset;
6710 if (lua_gettop(L) == 4) {
6711 len = MAY_LJMP(luaL_checkinteger(L, 4));
6712 if (!len)
6713 goto end;
6714 if (len == -1)
6715 len = output + input - offset;
6716 if (len < 0 || offset + len > output + input) {
6717 lua_pushfstring(L, "length out of range.");
6718 WILL_LJMP(lua_error(L));
6719 }
6720 }
6721
6722 _hlua_http_msg_delete(msg, filter, offset, len);
6723
6724 end:
6725 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006726 return 1;
6727}
6728
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006729/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006730 * all remaining data are removed, accordingly to the filter context. It returns
6731 * the amount of data written or -1 if nothing was copied. Unlike the channel
6732 * function used to replace data, this one can only be called inside a filter,
6733 * from http_payload callback. So it cannot yield. An exception is returned if
6734 * it is called from another callback.
6735 */
6736__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006737{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006738 struct http_msg *msg;
6739 struct filter *filter;
6740 struct htx *htx;
6741 const char *str;
6742 size_t input, output, sz;
6743 int offset, len;
6744 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006745
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006746 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6747 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6748 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6749
6750 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006751 WILL_LJMP(lua_error(L));
6752
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006753 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6754 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6755 if (!filter || !hlua_filter_from_payload(filter))
6756 WILL_LJMP(lua_error(L));
6757
6758 offset = output;
6759 if (lua_gettop(L) > 2) {
6760 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6761 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006762 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006763 offset += output;
6764 if (offset < output || offset > input + output) {
6765 lua_pushfstring(L, "offset out of range.");
6766 WILL_LJMP(lua_error(L));
6767 }
6768 }
6769
6770 len = output + input - offset;
6771 if (lua_gettop(L) == 4) {
6772 len = MAY_LJMP(luaL_checkinteger(L, 4));
6773 if (!len)
6774 goto set;
6775 if (len == -1)
6776 len = output + input - offset;
6777 if (len < 0 || offset + len > output + input) {
6778 lua_pushfstring(L, "length out of range.");
6779 WILL_LJMP(lua_error(L));
6780 }
6781 }
6782
6783 set:
6784 /* Be sure we can copied the string once input data will be removed. */
6785 htx = htx_from_buf(&msg->chn->buf);
6786 if (sz > htx_free_data_space(htx) + len)
6787 lua_pushinteger(L, -1);
6788 else {
6789 _hlua_http_msg_delete(msg, filter, offset, len);
6790 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6791 lua_pushinteger(L, ret);
6792 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006793 return 1;
6794}
6795
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006796/* Prepends data into an HTTP message and forward it, from the filter point of
6797 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6798 * the channel function used to send data, this one can only be called inside a
6799 * filter, from http_payload callback. So it cannot yield. An exception is
6800 * returned if it is called from another callback.
6801 */
6802__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006803{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006804 struct http_msg *msg;
6805 struct filter *filter;
6806 struct htx *htx;
6807 const char *str;
6808 size_t offset, len, sz;
6809 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006810
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006811 MAY_LJMP(check_args(L, 2, "send"));
6812 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6813
6814 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006815 WILL_LJMP(lua_error(L));
6816
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006817 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6818 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6819 if (!filter || !hlua_filter_from_payload(filter))
6820 WILL_LJMP(lua_error(L));
6821
6822 /* Return an error if the channel's output is closed */
6823 if (unlikely(channel_output_closed(msg->chn))) {
6824 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006825 return 1;
6826 }
6827
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006828 htx = htx_from_buf(&msg->chn->buf);
6829 if (sz > htx_free_data_space(htx)) {
6830 lua_pushinteger(L, -1);
6831 return 1;
6832 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006833
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006834 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6835 if (ret > 0) {
6836 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6837
6838 FLT_OFF(filter, msg->chn) += ret;
6839 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6840 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6841 }
6842
6843 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006844 return 1;
6845}
6846
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006847/* Forwards a given amount of bytes. It return -1 if the channel's output is
6848 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6849 * channel function used to forward data, this one can only be called inside a
6850 * filter, from http_payload callback. So it cannot yield. An exception is
6851 * returned if it is called from another callback. All other functions deal with
6852 * DATA block, this one not.
6853*/
6854__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006855{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006856 struct http_msg *msg;
6857 struct filter *filter;
6858 size_t offset, len;
6859 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006860
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006861 MAY_LJMP(check_args(L, 2, "forward"));
6862 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6863
6864 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006865 WILL_LJMP(lua_error(L));
6866
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006867 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6868 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6869 if (!filter || !hlua_filter_from_payload(filter))
6870 WILL_LJMP(lua_error(L));
6871
6872 /* Nothing to do, just return */
6873 if (!fwd)
6874 goto end;
6875
6876 /* Return an error if the channel's output is closed */
6877 if (unlikely(channel_output_closed(msg->chn))) {
6878 ret = -1;
6879 goto end;
6880 }
6881
6882 ret = fwd;
6883 if (ret > len)
6884 ret = len;
6885
6886 if (ret) {
6887 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6888
6889 FLT_OFF(filter, msg->chn) += ret;
6890 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6891 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6892 }
6893
6894 end:
6895 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006896 return 1;
6897}
6898
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006899/* Set 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_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006905{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006906 struct http_msg *msg;
6907 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006908
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006909 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;
6913 return 0;
6914}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006915
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006916/* Unset EOM flag on the HTX message.
6917 *
6918 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6919 * really know how to do without this feature.
6920 */
6921__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6922{
6923 struct http_msg *msg;
6924 struct htx *htx;
6925
6926 MAY_LJMP(check_args(L, 1, "set_eom"));
6927 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6928 htx = htxbuf(&msg->chn->buf);
6929 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006930 return 0;
6931}
6932
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006933/*
6934 *
6935 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006936 * Class HTTPClient
6937 *
6938 *
6939 */
6940__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6941{
6942 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6943}
6944
William Lallemandf77f1de2021-09-28 19:10:38 +02006945
6946/* stops the httpclient and ask it to kill itself */
6947__LJMP static int hlua_httpclient_gc(lua_State *L)
6948{
6949 struct hlua_httpclient *hlua_hc;
6950
6951 MAY_LJMP(check_args(L, 1, "__gc"));
6952
6953 hlua_hc = MAY_LJMP(hlua_checkhttpclient(L, 1));
6954
6955 httpclient_stop_and_destroy(hlua_hc->hc);
6956
6957 hlua_hc->hc = NULL;
6958
6959
6960 return 0;
6961}
6962
6963
William Lallemand3956c4e2021-09-21 16:25:15 +02006964__LJMP static int hlua_httpclient_new(lua_State *L)
6965{
6966 struct hlua_httpclient *hlua_hc;
6967 struct hlua *hlua;
6968
6969 /* Get hlua struct, or NULL if we execute from main lua state */
6970 hlua = hlua_gethlua(L);
6971 if (!hlua)
6972 return 0;
6973
6974 /* Check stack size. */
6975 if (!lua_checkstack(L, 3)) {
6976 hlua_pusherror(L, "httpclient: full stack");
6977 goto err;
6978 }
6979 /* Create the object: obj[0] = userdata. */
6980 lua_newtable(L);
6981 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6982 lua_rawseti(L, -2, 0);
6983 memset(hlua_hc, 0, sizeof(*hlua_hc));
6984
6985 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6986 if (!hlua_hc->hc)
6987 goto err;
6988
6989 /* Pop a class stream metatable and affect it to the userdata. */
6990 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6991 lua_setmetatable(L, -2);
6992
6993 return 1;
6994
6995 err:
6996 WILL_LJMP(lua_error(L));
6997 return 0;
6998}
6999
7000
7001/*
7002 * Callback of the httpclient, this callback wakes the lua task up, once the
7003 * httpclient receives some data
7004 *
7005 */
7006
William Lallemandbd5739e2021-10-28 15:41:38 +02007007static void hlua_httpclient_cb(struct httpclient *hc)
William Lallemand3956c4e2021-09-21 16:25:15 +02007008{
7009 struct hlua *hlua = hc->caller;
7010
7011 if (!hlua || !hlua->task)
7012 return;
7013
7014 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7015}
7016
7017/*
William Lallemandd7df73a2021-09-23 17:54:00 +02007018 * Fill the lua stack with headers from the httpclient response
7019 * This works the same way as the hlua_http_get_headers() function
7020 */
7021__LJMP static int hlua_httpclient_get_headers(lua_State *L, struct hlua_httpclient *hlua_hc)
7022{
7023 struct http_hdr *hdr;
7024
7025 lua_newtable(L);
7026
William Lallemandef574b22021-10-05 16:19:31 +02007027 for (hdr = hlua_hc->hc->res.hdrs; hdr && isttest(hdr->n); hdr++) {
William Lallemandd7df73a2021-09-23 17:54:00 +02007028 struct ist n, v;
7029 int len;
7030
7031 n = hdr->n;
7032 v = hdr->v;
7033
7034 /* Check for existing entry:
7035 * assume that the table is on the top of the stack, and
7036 * push the key in the stack, the function lua_gettable()
7037 * perform the lookup.
7038 */
7039
7040 lua_pushlstring(L, n.ptr, n.len);
7041 lua_gettable(L, -2);
7042
7043 switch (lua_type(L, -1)) {
7044 case LUA_TNIL:
7045 /* Table not found, create it. */
7046 lua_pop(L, 1); /* remove the nil value. */
7047 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
7048 lua_newtable(L); /* create and push empty table. */
7049 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7050 lua_rawseti(L, -2, 0); /* index header value (pop it). */
7051 lua_rawset(L, -3); /* index new table with header name (pop the values). */
7052 break;
7053
7054 case LUA_TTABLE:
7055 /* Entry found: push the value in the table. */
7056 len = lua_rawlen(L, -1);
7057 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
7058 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
7059 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
7060 break;
7061
7062 default:
7063 /* Other cases are errors. */
7064 hlua_pusherror(L, "internal error during the parsing of headers.");
7065 WILL_LJMP(lua_error(L));
7066 }
7067 }
7068 return 1;
7069}
7070
7071/*
William Lallemand746e6f32021-10-06 10:57:44 +02007072 * Allocate and return an array of http_hdr ist extracted from the <headers> lua table
7073 *
7074 * Caller must free the result
7075 */
7076struct http_hdr *hlua_httpclient_table_to_hdrs(lua_State *L)
7077{
7078 struct http_hdr hdrs[global.tune.max_http_hdr];
7079 struct http_hdr *result = NULL;
7080 uint32_t hdr_num = 0;
7081
7082 lua_pushnil(L);
7083 while (lua_next(L, -2) != 0) {
7084 struct ist name, value;
7085 const char *n, *v;
7086 size_t nlen, vlen;
7087
7088 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7089 /* Skip element if the key is not a string or if the value is not a table */
7090 goto next_hdr;
7091 }
7092
7093 n = lua_tolstring(L, -2, &nlen);
7094 name = ist2(n, nlen);
7095
7096 /* Loop on header's values */
7097 lua_pushnil(L);
7098 while (lua_next(L, -2)) {
7099 if (!lua_isstring(L, -1)) {
7100 /* Skip the value if it is not a string */
7101 goto next_value;
7102 }
7103
7104 v = lua_tolstring(L, -1, &vlen);
7105 value = ist2(v, vlen);
7106 name = ist2(n, nlen);
7107
7108 hdrs[hdr_num].n = istdup(name);
7109 hdrs[hdr_num].v = istdup(value);
7110
7111 hdr_num++;
7112
7113 next_value:
7114 lua_pop(L, 1);
7115 }
7116
7117 next_hdr:
7118 lua_pop(L, 1);
7119
7120 }
7121
7122 if (hdr_num) {
7123 /* alloc and copy the headers in the httpclient struct */
Tim Duesterhus16cc16d2021-11-06 15:14:45 +01007124 result = calloc((hdr_num + 1), sizeof(*result));
William Lallemand746e6f32021-10-06 10:57:44 +02007125 if (!result)
7126 goto skip_headers;
7127 memcpy(result, hdrs, sizeof(struct http_hdr) * (hdr_num + 1));
7128
7129 result[hdr_num].n = IST_NULL;
7130 result[hdr_num].v = IST_NULL;
7131 }
7132
7133skip_headers:
William Lallemand746e6f32021-10-06 10:57:44 +02007134
7135 return result;
7136}
7137
7138
William Lallemandbd5739e2021-10-28 15:41:38 +02007139/*
7140 * For each yield, checks if there is some data in the httpclient and push them
7141 * in the lua buffer, once the httpclient finished its job, push the result on
7142 * the stack
7143 */
7144__LJMP static int hlua_httpclient_rcv_yield(lua_State *L, int status, lua_KContext ctx)
7145{
7146 struct buffer *tr;
7147 int res;
7148 struct hlua *hlua = hlua_gethlua(L);
7149 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7150
7151
7152 tr = get_trash_chunk();
7153
7154 res = httpclient_res_xfer(hlua_hc->hc, tr);
7155 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
7156
7157 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
7158
7159 luaL_pushresult(&hlua_hc->b);
7160 lua_settable(L, -3);
7161
7162 lua_pushstring(L, "status");
7163 lua_pushinteger(L, hlua_hc->hc->res.status);
7164 lua_settable(L, -3);
7165
7166
7167 lua_pushstring(L, "reason");
7168 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
7169 lua_settable(L, -3);
7170
7171 lua_pushstring(L, "headers");
7172 hlua_httpclient_get_headers(L, hlua_hc);
7173 lua_settable(L, -3);
7174
7175 return 1;
7176 }
7177
7178 if (httpclient_data(hlua_hc->hc))
7179 task_wakeup(hlua->task, TASK_WOKEN_MSG);
7180
7181 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7182
7183 return 0;
7184}
7185
7186/*
7187 * Call this when trying to stream a body during a request
7188 */
7189__LJMP static int hlua_httpclient_snd_yield(lua_State *L, int status, lua_KContext ctx)
7190{
7191 struct hlua *hlua;
7192 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
7193 const char *body_str = NULL;
7194 int ret;
7195 int end = 0;
7196 size_t buf_len;
7197 size_t to_send = 0;
7198
7199 hlua = hlua_gethlua(L);
7200
7201 if (!hlua || !hlua->task)
7202 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7203 "'frontend', 'backend' or 'task'"));
7204
7205 ret = lua_getfield(L, -1, "body");
7206 if (ret != LUA_TSTRING)
7207 goto rcv;
7208
7209 body_str = lua_tolstring(L, -1, &buf_len);
7210 lua_pop(L, 1);
7211
Christopher Fauletfc591292022-01-12 14:46:03 +01007212 to_send = buf_len - hlua_hc->sent;
William Lallemandbd5739e2021-10-28 15:41:38 +02007213
7214 if ((hlua_hc->sent + to_send) >= buf_len)
7215 end = 1;
7216
7217 /* the end flag is always set since we are using the whole remaining size */
7218 hlua_hc->sent += httpclient_req_xfer(hlua_hc->hc, ist2(body_str + hlua_hc->sent, to_send), end);
7219
7220 if (buf_len > hlua_hc->sent) {
7221 /* still need to process the buffer */
7222 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
7223 } else {
7224 goto rcv;
7225 /* we sent the whole request buffer we can recv */
7226 }
7227 return 0;
7228
7229rcv:
7230
7231 /* we return a "res" object */
7232 lua_newtable(L);
7233
William Lallemandbd5739e2021-10-28 15:41:38 +02007234 lua_pushstring(L, "body");
William Lallemandd1187eb2021-11-02 10:40:06 +01007235 luaL_buffinit(L, &hlua_hc->b);
William Lallemandbd5739e2021-10-28 15:41:38 +02007236
William Lallemand933fe392021-11-04 09:45:58 +01007237 task_wakeup(hlua->task, TASK_WOKEN_MSG);
William Lallemandbd5739e2021-10-28 15:41:38 +02007238 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_rcv_yield, TICK_ETERNITY, 0));
7239
7240 return 1;
7241}
William Lallemand746e6f32021-10-06 10:57:44 +02007242
William Lallemand3956c4e2021-09-21 16:25:15 +02007243/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007244 * Send an HTTP request and wait for a response
William Lallemand3956c4e2021-09-21 16:25:15 +02007245 */
7246
William Lallemanddc2cc902021-10-26 11:43:26 +02007247__LJMP static int hlua_httpclient_send(lua_State *L, enum http_meth_t meth)
William Lallemand3956c4e2021-09-21 16:25:15 +02007248{
7249 struct hlua_httpclient *hlua_hc;
William Lallemand746e6f32021-10-06 10:57:44 +02007250 struct http_hdr *hdrs = NULL;
7251 struct http_hdr *hdrs_i = NULL;
William Lallemand3956c4e2021-09-21 16:25:15 +02007252 struct hlua *hlua;
William Lallemand746e6f32021-10-06 10:57:44 +02007253 const char *url_str = NULL;
William Lallemanddec25c32021-10-25 19:48:37 +02007254 const char *body_str = NULL;
William Lallemandbd5739e2021-10-28 15:41:38 +02007255 size_t buf_len;
William Lallemand746e6f32021-10-06 10:57:44 +02007256 int ret;
William Lallemand3956c4e2021-09-21 16:25:15 +02007257
7258 hlua = hlua_gethlua(L);
7259
7260 if (!hlua || !hlua->task)
7261 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7262 "'frontend', 'backend' or 'task'"));
7263
William Lallemand746e6f32021-10-06 10:57:44 +02007264 if (lua_gettop(L) != 2 || lua_type(L, -1) != LUA_TTABLE)
7265 WILL_LJMP(luaL_error(L, "'get' needs a table as argument"));
7266
William Lallemand4f4f2b72022-02-17 20:00:23 +01007267 hlua_hc = hlua_checkhttpclient(L, 1);
7268
William Lallemand7177a952022-03-03 15:33:12 +01007269 lua_pushnil(L); /* first key */
7270 while (lua_next(L, 2)) {
7271 if (strcmp(lua_tostring(L, -2), "dst") == 0) {
7272 if (httpclient_set_dst(hlua_hc->hc, lua_tostring(L, -1)) < 0)
7273 WILL_LJMP(luaL_error(L, "Can't use the 'dst' argument"));
William Lallemand4f4f2b72022-02-17 20:00:23 +01007274
William Lallemand7177a952022-03-03 15:33:12 +01007275 } else if (strcmp(lua_tostring(L, -2), "url") == 0) {
7276 if (lua_type(L, -1) != LUA_TSTRING)
7277 WILL_LJMP(luaL_error(L, "invalid parameter in 'url', must be a string"));
7278 url_str = lua_tostring(L, -1);
William Lallemand3956c4e2021-09-21 16:25:15 +02007279
William Lallemand7177a952022-03-03 15:33:12 +01007280 } else if (strcmp(lua_tostring(L, -2), "timeout") == 0) {
7281 if (lua_type(L, -1) != LUA_TNUMBER)
7282 WILL_LJMP(luaL_error(L, "invalid parameter in 'timeout', must be a number"));
7283 httpclient_set_timeout(hlua_hc->hc, lua_tointeger(L, -1));
William Lallemandb4a4ef62022-02-23 14:18:16 +01007284
William Lallemand7177a952022-03-03 15:33:12 +01007285 } else if (strcmp(lua_tostring(L, -2), "headers") == 0) {
7286 if (lua_type(L, -1) != LUA_TTABLE)
7287 WILL_LJMP(luaL_error(L, "invalid parameter in 'headers', must be a table"));
7288 hdrs = hlua_httpclient_table_to_hdrs(L);
William Lallemand79416cb2021-09-24 14:51:44 +02007289
William Lallemand7177a952022-03-03 15:33:12 +01007290 } else if (strcmp(lua_tostring(L, -2), "body") == 0) {
7291 if (lua_type(L, -1) != LUA_TSTRING)
7292 WILL_LJMP(luaL_error(L, "invalid parameter in 'body', must be a string"));
7293 body_str = lua_tolstring(L, -1, &buf_len);
William Lallemandbd5739e2021-10-28 15:41:38 +02007294
William Lallemand7177a952022-03-03 15:33:12 +01007295 } else {
7296 WILL_LJMP(luaL_error(L, "'%s' invalid parameter name", lua_tostring(L, -2)));
7297 }
7298 /* removes 'value'; keeps 'key' for next iteration */
7299 lua_pop(L, 1);
7300 }
William Lallemanddec25c32021-10-25 19:48:37 +02007301
William Lallemand746e6f32021-10-06 10:57:44 +02007302 if (!url_str) {
7303 WILL_LJMP(luaL_error(L, "'get' need a 'url' argument"));
7304 return 0;
7305 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007306
William Lallemand10a37362022-03-02 16:18:26 +01007307 hlua_hc->sent = 0;
William Lallemand3956c4e2021-09-21 16:25:15 +02007308
7309 hlua_hc->hc->req.url = istdup(ist(url_str));
William Lallemanddc2cc902021-10-26 11:43:26 +02007310 hlua_hc->hc->req.meth = meth;
William Lallemand3956c4e2021-09-21 16:25:15 +02007311
7312 /* update the httpclient callbacks */
William Lallemandbd5739e2021-10-28 15:41:38 +02007313 hlua_hc->hc->ops.res_stline = hlua_httpclient_cb;
7314 hlua_hc->hc->ops.res_headers = hlua_httpclient_cb;
7315 hlua_hc->hc->ops.res_payload = hlua_httpclient_cb;
William Lallemand8f170c72022-03-15 10:52:07 +01007316 hlua_hc->hc->ops.res_end = hlua_httpclient_cb;
William Lallemand3956c4e2021-09-21 16:25:15 +02007317
William Lallemandbd5739e2021-10-28 15:41:38 +02007318 /* a body is available, it will use the request callback */
7319 if (body_str) {
7320 hlua_hc->hc->ops.req_payload = hlua_httpclient_cb;
7321 }
William Lallemand3956c4e2021-09-21 16:25:15 +02007322
William Lallemandbd5739e2021-10-28 15:41:38 +02007323 ret = httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, meth, hdrs, IST_NULL);
William Lallemand3956c4e2021-09-21 16:25:15 +02007324
William Lallemand746e6f32021-10-06 10:57:44 +02007325 /* free the temporary headers array */
7326 hdrs_i = hdrs;
7327 while (hdrs_i && isttest(hdrs_i->n)) {
7328 istfree(&hdrs_i->n);
7329 istfree(&hdrs_i->v);
7330 hdrs_i++;
7331 }
7332 ha_free(&hdrs);
7333
7334
William Lallemand6137a9e2021-10-26 15:01:53 +02007335 if (ret != ERR_NONE) {
7336 WILL_LJMP(luaL_error(L, "Can't generate the HTTP request"));
7337 return 0;
7338 }
7339
William Lallemandc2d3db42022-04-26 11:46:13 +02007340 if (!httpclient_start(hlua_hc->hc))
7341 WILL_LJMP(luaL_error(L, "couldn't start the httpclient"));
William Lallemand6137a9e2021-10-26 15:01:53 +02007342
William Lallemandbd5739e2021-10-28 15:41:38 +02007343 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_snd_yield, TICK_ETERNITY, 0));
William Lallemand3956c4e2021-09-21 16:25:15 +02007344
William Lallemand3956c4e2021-09-21 16:25:15 +02007345 return 0;
7346}
7347
7348/*
William Lallemanddc2cc902021-10-26 11:43:26 +02007349 * Sends an HTTP HEAD request and wait for a response
7350 *
7351 * httpclient:head(url, headers, payload)
7352 */
7353__LJMP static int hlua_httpclient_head(lua_State *L)
7354{
7355 return hlua_httpclient_send(L, HTTP_METH_HEAD);
7356}
7357
7358/*
7359 * Send an HTTP GET request and wait for a response
7360 *
7361 * httpclient:get(url, headers, payload)
7362 */
7363__LJMP static int hlua_httpclient_get(lua_State *L)
7364{
7365 return hlua_httpclient_send(L, HTTP_METH_GET);
7366
7367}
7368
7369/*
7370 * Sends an HTTP PUT request and wait for a response
7371 *
7372 * httpclient:put(url, headers, payload)
7373 */
7374__LJMP static int hlua_httpclient_put(lua_State *L)
7375{
7376 return hlua_httpclient_send(L, HTTP_METH_PUT);
7377}
7378
7379/*
7380 * Send an HTTP POST request and wait for a response
7381 *
7382 * httpclient:post(url, headers, payload)
7383 */
7384__LJMP static int hlua_httpclient_post(lua_State *L)
7385{
7386 return hlua_httpclient_send(L, HTTP_METH_POST);
7387}
7388
7389
7390/*
7391 * Sends an HTTP DELETE request and wait for a response
7392 *
7393 * httpclient:delete(url, headers, payload)
7394 */
7395__LJMP static int hlua_httpclient_delete(lua_State *L)
7396{
7397 return hlua_httpclient_send(L, HTTP_METH_DELETE);
7398}
7399
7400/*
William Lallemand3956c4e2021-09-21 16:25:15 +02007401 *
7402 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007403 * Class TXN
7404 *
7405 *
7406 */
7407
7408/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007409 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007410 */
7411__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7412{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007413 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007414}
7415
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007416__LJMP static int hlua_set_var(lua_State *L)
7417{
7418 struct hlua_txn *htxn;
7419 const char *name;
7420 size_t len;
7421 struct sample smp;
7422
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007423 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7424 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007425
7426 /* It is useles to retrieve the stream, but this function
7427 * runs only in a stream context.
7428 */
7429 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7430 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7431
7432 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007433 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007434 hlua_lua2smp(L, 3, &smp);
7435
7436 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007437 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007438
7439 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7440 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7441 else
7442 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7443
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007444 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007445}
7446
Christopher Faulet85d79c92016-11-09 16:54:56 +01007447__LJMP static int hlua_unset_var(lua_State *L)
7448{
7449 struct hlua_txn *htxn;
7450 const char *name;
7451 size_t len;
7452 struct sample smp;
7453
7454 MAY_LJMP(check_args(L, 2, "unset_var"));
7455
7456 /* It is useles to retrieve the stream, but this function
7457 * runs only in a stream context.
7458 */
7459 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7460 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7461
7462 /* Unset the variable. */
7463 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007464 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7465 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007466}
7467
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007468__LJMP static int hlua_get_var(lua_State *L)
7469{
7470 struct hlua_txn *htxn;
7471 const char *name;
7472 size_t len;
7473 struct sample smp;
7474
7475 MAY_LJMP(check_args(L, 2, "get_var"));
7476
7477 /* It is useles to retrieve the stream, but this function
7478 * runs only in a stream context.
7479 */
7480 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7481 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7482
Willy Tarreau7560dd42016-03-10 16:28:58 +01007483 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007484 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007485 lua_pushnil(L);
7486 return 1;
7487 }
7488
7489 return hlua_smp2lua(L, &smp);
7490}
7491
Willy Tarreau59551662015-03-10 14:23:13 +01007492__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007493{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007494 struct hlua *hlua;
7495
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007496 MAY_LJMP(check_args(L, 2, "set_priv"));
7497
Willy Tarreau87b09662015-04-03 00:22:06 +02007498 /* It is useles to retrieve the stream, but this function
7499 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007500 */
7501 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007502
7503 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007504 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007505 if (!hlua)
7506 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007507
7508 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007509 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007510
7511 /* Get and store new value. */
7512 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7513 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7514
7515 return 0;
7516}
7517
Willy Tarreau59551662015-03-10 14:23:13 +01007518__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007519{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007520 struct hlua *hlua;
7521
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007522 MAY_LJMP(check_args(L, 1, "get_priv"));
7523
Willy Tarreau87b09662015-04-03 00:22:06 +02007524 /* It is useles to retrieve the stream, but this function
7525 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007526 */
7527 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007528
7529 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007530 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007531 if (!hlua) {
7532 lua_pushnil(L);
7533 return 1;
7534 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007535
7536 /* Push configuration index in the stack. */
7537 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7538
7539 return 1;
7540}
7541
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007542/* Create stack entry containing a class TXN. This function
7543 * return 0 if the stack does not contains free slots,
7544 * otherwise it returns 1.
7545 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007546static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007547{
Willy Tarreaude491382015-04-06 11:04:28 +02007548 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007549
7550 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007551 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007552 return 0;
7553
7554 /* NOTE: The allocation never fails. The failure
7555 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007556 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007557 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007558 /* Create the object: obj[0] = userdata. */
7559 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007560 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007561 lua_rawseti(L, -2, 0);
7562
Willy Tarreaude491382015-04-06 11:04:28 +02007563 htxn->s = s;
7564 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007565 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007566 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007567
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007568 /* Create the "f" field that contains a list of fetches. */
7569 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007570 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007571 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007572 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007573
7574 /* Create the "sf" field that contains a list of stringsafe fetches. */
7575 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007576 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007577 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007578 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007579
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007580 /* Create the "c" field that contains a list of converters. */
7581 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007582 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007583 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007584 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007585
7586 /* Create the "sc" field that contains a list of stringsafe converters. */
7587 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007588 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007589 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007590 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007591
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007592 /* Create the "req" field that contains the request channel object. */
7593 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007594 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007595 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007596 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007597
7598 /* Create the "res" field that contains the response channel object. */
7599 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007600 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007601 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007602 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007603
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007604 /* Creates the HTTP object is the current proxy allows http. */
7605 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007606 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007607 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007608 return 0;
7609 }
7610 else
7611 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007612 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007613
Christopher Faulet78c35472020-02-26 17:14:08 +01007614 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7615 /* HTTPMessage object are created when a lua TXN is created from
7616 * a filter context only
7617 */
7618
7619 /* Creates the HTTP-Request object is the current proxy allows http. */
7620 lua_pushstring(L, "http_req");
7621 if (p->mode == PR_MODE_HTTP) {
7622 if (!hlua_http_msg_new(L, &s->txn->req))
7623 return 0;
7624 }
7625 else
7626 lua_pushnil(L);
7627 lua_rawset(L, -3);
7628
7629 /* Creates the HTTP-Response object is the current proxy allows http. */
7630 lua_pushstring(L, "http_res");
7631 if (p->mode == PR_MODE_HTTP) {
7632 if (!hlua_http_msg_new(L, &s->txn->rsp))
7633 return 0;
7634 }
7635 else
7636 lua_pushnil(L);
7637 lua_rawset(L, -3);
7638 }
7639
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007640 /* Pop a class sesison metatable and affect it to the userdata. */
7641 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7642 lua_setmetatable(L, -2);
7643
7644 return 1;
7645}
7646
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007647__LJMP static int hlua_txn_deflog(lua_State *L)
7648{
7649 const char *msg;
7650 struct hlua_txn *htxn;
7651
7652 MAY_LJMP(check_args(L, 2, "deflog"));
7653 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7654 msg = MAY_LJMP(luaL_checkstring(L, 2));
7655
7656 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7657 return 0;
7658}
7659
7660__LJMP static int hlua_txn_log(lua_State *L)
7661{
7662 int level;
7663 const char *msg;
7664 struct hlua_txn *htxn;
7665
7666 MAY_LJMP(check_args(L, 3, "log"));
7667 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7668 level = MAY_LJMP(luaL_checkinteger(L, 2));
7669 msg = MAY_LJMP(luaL_checkstring(L, 3));
7670
7671 if (level < 0 || level >= NB_LOG_LEVELS)
7672 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7673
7674 hlua_sendlog(htxn->s->be, level, msg);
7675 return 0;
7676}
7677
7678__LJMP static int hlua_txn_log_debug(lua_State *L)
7679{
7680 const char *msg;
7681 struct hlua_txn *htxn;
7682
7683 MAY_LJMP(check_args(L, 2, "Debug"));
7684 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7685 msg = MAY_LJMP(luaL_checkstring(L, 2));
7686 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7687 return 0;
7688}
7689
7690__LJMP static int hlua_txn_log_info(lua_State *L)
7691{
7692 const char *msg;
7693 struct hlua_txn *htxn;
7694
7695 MAY_LJMP(check_args(L, 2, "Info"));
7696 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7697 msg = MAY_LJMP(luaL_checkstring(L, 2));
7698 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7699 return 0;
7700}
7701
7702__LJMP static int hlua_txn_log_warning(lua_State *L)
7703{
7704 const char *msg;
7705 struct hlua_txn *htxn;
7706
7707 MAY_LJMP(check_args(L, 2, "Warning"));
7708 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7709 msg = MAY_LJMP(luaL_checkstring(L, 2));
7710 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7711 return 0;
7712}
7713
7714__LJMP static int hlua_txn_log_alert(lua_State *L)
7715{
7716 const char *msg;
7717 struct hlua_txn *htxn;
7718
7719 MAY_LJMP(check_args(L, 2, "Alert"));
7720 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7721 msg = MAY_LJMP(luaL_checkstring(L, 2));
7722 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7723 return 0;
7724}
7725
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007726__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7727{
7728 struct hlua_txn *htxn;
7729 int ll;
7730
7731 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7732 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7733 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7734
7735 if (ll < 0 || ll > 7)
7736 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7737
7738 htxn->s->logs.level = ll;
7739 return 0;
7740}
7741
7742__LJMP static int hlua_txn_set_tos(lua_State *L)
7743{
7744 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007745 int tos;
7746
7747 MAY_LJMP(check_args(L, 2, "set_tos"));
7748 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7749 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7750
Willy Tarreau1a18b542018-12-11 16:37:42 +01007751 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007752 return 0;
7753}
7754
7755__LJMP static int hlua_txn_set_mark(lua_State *L)
7756{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007757 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007758 int mark;
7759
7760 MAY_LJMP(check_args(L, 2, "set_mark"));
7761 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7762 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7763
Lukas Tribus579e3e32019-08-11 18:03:45 +02007764 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007765 return 0;
7766}
7767
Patrick Hemmer268a7072018-05-11 12:52:31 -04007768__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7769{
7770 struct hlua_txn *htxn;
7771
7772 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7773 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7774 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7775 return 0;
7776}
7777
7778__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7779{
7780 struct hlua_txn *htxn;
7781
7782 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7783 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7784 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7785 return 0;
7786}
7787
Christopher Faulet700d9e82020-01-31 12:21:52 +01007788/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007789 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007790 * message and terminate the transaction. It returns 1 on success and 0 on
7791 * error. The Reply must be on top of the stack.
7792 */
7793__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7794{
7795 struct htx *htx;
7796 struct htx_sl *sl;
7797 struct h1m h1m;
7798 const char *status, *reason, *body;
7799 size_t status_len, reason_len, body_len;
7800 int ret, code, flags;
7801
7802 code = 200;
7803 status = "200";
7804 status_len = 3;
7805 ret = lua_getfield(L, -1, "status");
7806 if (ret == LUA_TNUMBER) {
7807 code = lua_tointeger(L, -1);
7808 status = lua_tolstring(L, -1, &status_len);
7809 }
7810 lua_pop(L, 1);
7811
7812 reason = http_get_reason(code);
7813 reason_len = strlen(reason);
7814 ret = lua_getfield(L, -1, "reason");
7815 if (ret == LUA_TSTRING)
7816 reason = lua_tolstring(L, -1, &reason_len);
7817 lua_pop(L, 1);
7818
7819 body = NULL;
7820 body_len = 0;
7821 ret = lua_getfield(L, -1, "body");
7822 if (ret == LUA_TSTRING)
7823 body = lua_tolstring(L, -1, &body_len);
7824 lua_pop(L, 1);
7825
7826 /* Prepare the response before inserting the headers */
7827 h1m_init_res(&h1m);
7828 htx = htx_from_buf(&s->res.buf);
7829 channel_htx_truncate(&s->res, htx);
7830 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7831 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7832 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7833 ist2(status, status_len), ist2(reason, reason_len));
7834 }
7835 else {
7836 flags = HTX_SL_F_IS_RESP;
7837 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7838 ist2(status, status_len), ist2(reason, reason_len));
7839 }
7840 if (!sl)
7841 goto fail;
7842 sl->info.res.status = code;
7843
7844 /* Push in the stack the "headers" entry. */
7845 ret = lua_getfield(L, -1, "headers");
7846 if (ret != LUA_TTABLE)
7847 goto skip_headers;
7848
7849 lua_pushnil(L);
7850 while (lua_next(L, -2) != 0) {
7851 struct ist name, value;
7852 const char *n, *v;
7853 size_t nlen, vlen;
7854
7855 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7856 /* Skip element if the key is not a string or if the value is not a table */
7857 goto next_hdr;
7858 }
7859
7860 n = lua_tolstring(L, -2, &nlen);
7861 name = ist2(n, nlen);
7862 if (isteqi(name, ist("content-length"))) {
7863 /* Always skip content-length header. It will be added
7864 * later with the correct len
7865 */
7866 goto next_hdr;
7867 }
7868
7869 /* Loop on header's values */
7870 lua_pushnil(L);
7871 while (lua_next(L, -2)) {
7872 if (!lua_isstring(L, -1)) {
7873 /* Skip the value if it is not a string */
7874 goto next_value;
7875 }
7876
7877 v = lua_tolstring(L, -1, &vlen);
7878 value = ist2(v, vlen);
7879
7880 if (isteqi(name, ist("transfer-encoding")))
7881 h1_parse_xfer_enc_header(&h1m, value);
7882 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7883 goto fail;
7884
7885 next_value:
7886 lua_pop(L, 1);
7887 }
7888
7889 next_hdr:
7890 lua_pop(L, 1);
7891 }
7892 skip_headers:
7893 lua_pop(L, 1);
7894
7895 /* Update h1m flags: CLEN is set if CHNK is not present */
7896 if (!(h1m.flags & H1_MF_CHNK)) {
7897 const char *clen = ultoa(body_len);
7898
7899 h1m.flags |= H1_MF_CLEN;
7900 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7901 goto fail;
7902 }
7903 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7904 h1m.flags |= H1_MF_XFER_LEN;
7905
7906 /* Update HTX start-line flags */
7907 if (h1m.flags & H1_MF_XFER_ENC)
7908 flags |= HTX_SL_F_XFER_ENC;
7909 if (h1m.flags & H1_MF_XFER_LEN) {
7910 flags |= HTX_SL_F_XFER_LEN;
7911 if (h1m.flags & H1_MF_CHNK)
7912 flags |= HTX_SL_F_CHNK;
7913 else if (h1m.flags & H1_MF_CLEN)
7914 flags |= HTX_SL_F_CLEN;
7915 if (h1m.body_len == 0)
7916 flags |= HTX_SL_F_BODYLESS;
7917 }
7918 sl->flags |= flags;
7919
7920
7921 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007922 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007923 goto fail;
7924
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007925 htx->flags |= HTX_FL_EOM;
7926
Christopher Faulet700d9e82020-01-31 12:21:52 +01007927 /* Now, forward the response and terminate the transaction */
7928 s->txn->status = code;
7929 htx_to_buf(htx, &s->res.buf);
7930 if (!http_forward_proxy_resp(s, 1))
7931 goto fail;
7932
7933 return 1;
7934
7935 fail:
7936 channel_htx_truncate(&s->res, htx);
7937 return 0;
7938}
7939
7940/* Terminate a transaction if called from a lua action. For TCP streams,
7941 * processing is just aborted. Nothing is returned to the client and all
7942 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7943 * is forwarded to the client before terminating the transaction. On success,
7944 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7945 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7946 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007947 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007948__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007949{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007950 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007951 struct stream *s;
7952 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007953
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007954 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007955
Christopher Faulet700d9e82020-01-31 12:21:52 +01007956 /* If the flags NOTERM is set, we cannot terminate the session, so we
7957 * just end the execution of the current lua code. */
7958 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007959 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007960
Christopher Faulet700d9e82020-01-31 12:21:52 +01007961 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007962 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007963 struct channel *req = &s->req;
7964 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007965
Christopher Faulet700d9e82020-01-31 12:21:52 +01007966 channel_auto_read(req);
7967 channel_abort(req);
7968 channel_auto_close(req);
7969 channel_erase(req);
7970
7971 res->wex = tick_add_ifset(now_ms, res->wto);
7972 channel_auto_read(res);
7973 channel_auto_close(res);
7974 channel_shutr_now(res);
7975
7976 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7977 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007978 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007979
Christopher Faulet700d9e82020-01-31 12:21:52 +01007980 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7981 /* No reply or invalid reply */
7982 s->txn->status = 0;
7983 http_reply_and_close(s, 0, NULL);
7984 }
7985 else {
7986 /* Remove extra args to have the reply on top of the stack */
7987 if (lua_gettop(L) > 2)
7988 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007989
Christopher Faulet700d9e82020-01-31 12:21:52 +01007990 if (!hlua_txn_forward_reply(L, s)) {
7991 if (!(s->flags & SF_ERR_MASK))
7992 s->flags |= SF_ERR_PRXCOND;
7993 lua_pushinteger(L, ACT_RET_ERR);
7994 WILL_LJMP(hlua_done(L));
7995 return 0; /* Never reached */
7996 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007997 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007998
Christopher Faulet700d9e82020-01-31 12:21:52 +01007999 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
8000 if (htxn->dir == SMP_OPT_DIR_REQ) {
8001 /* let's log the request time */
8002 s->logs.tv_request = now;
8003 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02008004 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008005 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008006
Christopher Faulet700d9e82020-01-31 12:21:52 +01008007 done:
8008 if (!(s->flags & SF_ERR_MASK))
8009 s->flags |= SF_ERR_LOCAL;
8010 if (!(s->flags & SF_FINST_MASK))
8011 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02008012
Christopher Faulete48d1dc2021-08-13 14:11:17 +02008013 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
8014 lua_pushinteger(L, -1);
8015 else
8016 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02008017 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008018 return 0;
8019}
8020
Christopher Faulet700d9e82020-01-31 12:21:52 +01008021/*
8022 *
8023 *
8024 * Class REPLY
8025 *
8026 *
8027 */
8028
8029/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
8030 * free slots, the function fails and returns 0;
8031 */
8032static int hlua_txn_reply_new(lua_State *L)
8033{
8034 struct hlua_txn *htxn;
8035 const char *reason, *body = NULL;
8036 int ret, status;
8037
8038 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008039 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01008040 hlua_pusherror(L, "txn object is not an HTTP transaction.");
8041 WILL_LJMP(lua_error(L));
8042 }
8043
8044 /* Default value */
8045 status = 200;
8046 reason = http_get_reason(status);
8047
8048 if (lua_istable(L, 2)) {
8049 /* load status and reason from the table argument at index 2 */
8050 ret = lua_getfield(L, 2, "status");
8051 if (ret == LUA_TNIL)
8052 goto reason;
8053 else if (ret != LUA_TNUMBER) {
8054 /* invalid status: ignore the reason */
8055 goto body;
8056 }
8057 status = lua_tointeger(L, -1);
8058
8059 reason:
8060 lua_pop(L, 1); /* restore the stack: remove status */
8061 ret = lua_getfield(L, 2, "reason");
8062 if (ret == LUA_TSTRING)
8063 reason = lua_tostring(L, -1);
8064
8065 body:
8066 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
8067 ret = lua_getfield(L, 2, "body");
8068 if (ret == LUA_TSTRING)
8069 body = lua_tostring(L, -1);
8070 lua_pop(L, 1); /* restore the stack: remove body */
8071 }
8072
8073 /* Create the Reply table */
8074 lua_newtable(L);
8075
8076 /* Add status element */
8077 lua_pushstring(L, "status");
8078 lua_pushinteger(L, status);
8079 lua_settable(L, -3);
8080
8081 /* Add reason element */
8082 reason = http_get_reason(status);
8083 lua_pushstring(L, "reason");
8084 lua_pushstring(L, reason);
8085 lua_settable(L, -3);
8086
8087 /* Add body element, nil if undefined */
8088 lua_pushstring(L, "body");
8089 if (body)
8090 lua_pushstring(L, body);
8091 else
8092 lua_pushnil(L);
8093 lua_settable(L, -3);
8094
8095 /* Add headers element */
8096 lua_pushstring(L, "headers");
8097 lua_newtable(L);
8098
8099 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8100 if (lua_istable(L, 2)) {
8101 /* load headers from the table argument at index 2. If it is a table, copy it. */
8102 ret = lua_getfield(L, 2, "headers");
8103 if (ret == LUA_TTABLE) {
8104 /* stack: [ ... <headers:table>, <table> ] */
8105 lua_pushnil(L);
8106 while (lua_next(L, -2) != 0) {
8107 /* stack: [ ... <headers:table>, <table>, k, v] */
8108 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
8109 /* invalid value type, skip it */
8110 lua_pop(L, 1);
8111 continue;
8112 }
8113
8114
8115 /* Duplicate the key and swap it with the value. */
8116 lua_pushvalue(L, -2);
8117 lua_insert(L, -2);
8118 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
8119
8120 lua_newtable(L);
8121 lua_insert(L, -2);
8122 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
8123
8124 if (lua_isstring(L, -1)) {
8125 /* push the value in the inner table */
8126 lua_rawseti(L, -2, 1);
8127 }
8128 else { /* table */
8129 lua_pushnil(L);
8130 while (lua_next(L, -2) != 0) {
8131 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
8132 if (!lua_isstring(L, -1)) {
8133 /* invalid value type, skip it*/
8134 lua_pop(L, 1);
8135 continue;
8136 }
8137 /* push the value in the inner table */
8138 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
8139 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
8140 }
8141 lua_pop(L, 1);
8142 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
8143 }
8144
8145 /* push (k,v) on the stack in the headers table:
8146 * stack: [ ... <headers:table>, <table>, k, k, v ]
8147 */
8148 lua_settable(L, -5);
8149 /* stack: [ ... <headers:table>, <table>, k ] */
8150 }
8151 }
8152 lua_pop(L, 1);
8153 }
8154 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
8155 lua_settable(L, -3);
8156 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
8157
8158 /* Pop a class sesison metatable and affect it to the userdata. */
8159 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
8160 lua_setmetatable(L, -2);
8161 return 1;
8162}
8163
8164/* Set the reply status code, and optionally the reason. If no reason is
8165 * provided, the default one corresponding to the status code is used.
8166 */
8167__LJMP static int hlua_txn_reply_set_status(lua_State *L)
8168{
8169 int status = MAY_LJMP(luaL_checkinteger(L, 2));
8170 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
8171
8172 /* First argument (self) must be a table */
8173 luaL_checktype(L, 1, LUA_TTABLE);
8174
8175 if (status < 100 || status > 599) {
8176 lua_pushboolean(L, 0);
8177 return 1;
8178 }
8179 if (!reason)
8180 reason = http_get_reason(status);
8181
8182 lua_pushinteger(L, status);
8183 lua_setfield(L, 1, "status");
8184
8185 lua_pushstring(L, reason);
8186 lua_setfield(L, 1, "reason");
8187
8188 lua_pushboolean(L, 1);
8189 return 1;
8190}
8191
8192/* Add a header into the reply object. Each header name is associated to an
8193 * array of values in the "headers" table. If the header name is not found, a
8194 * new entry is created.
8195 */
8196__LJMP static int hlua_txn_reply_add_header(lua_State *L)
8197{
8198 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8199 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
8200 int ret;
8201
8202 /* First argument (self) must be a table */
8203 luaL_checktype(L, 1, LUA_TTABLE);
8204
8205 /* Push in the stack the "headers" entry. */
8206 ret = lua_getfield(L, 1, "headers");
8207 if (ret != LUA_TTABLE) {
8208 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
8209 WILL_LJMP(lua_error(L));
8210 }
8211
8212 /* check if the header is already registered. If not, register it. */
8213 ret = lua_getfield(L, -1, name);
8214 if (ret == LUA_TNIL) {
8215 /* Entry not found. */
8216 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
8217
8218 /* Insert the new header name in the array in the top of the stack.
8219 * It left the new array in the top of the stack.
8220 */
8221 lua_newtable(L);
8222 lua_pushstring(L, name);
8223 lua_pushvalue(L, -2);
8224 lua_settable(L, -4);
8225 }
8226 else if (ret != LUA_TTABLE) {
8227 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
8228 WILL_LJMP(lua_error(L));
8229 }
8230
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008231 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01008232 * the header value as new entry.
8233 */
8234 lua_pushstring(L, value);
8235 ret = lua_rawlen(L, -2);
8236 lua_rawseti(L, -2, ret + 1);
8237
8238 lua_pushboolean(L, 1);
8239 return 1;
8240}
8241
8242/* Remove all occurrences of a given header name. */
8243__LJMP static int hlua_txn_reply_del_header(lua_State *L)
8244{
8245 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
8246 int ret;
8247
8248 /* First argument (self) must be a table */
8249 luaL_checktype(L, 1, LUA_TTABLE);
8250
8251 /* Push in the stack the "headers" entry. */
8252 ret = lua_getfield(L, 1, "headers");
8253 if (ret != LUA_TTABLE) {
8254 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
8255 WILL_LJMP(lua_error(L));
8256 }
8257
8258 lua_pushstring(L, name);
8259 lua_pushnil(L);
8260 lua_settable(L, -3);
8261
8262 lua_pushboolean(L, 1);
8263 return 1;
8264}
8265
8266/* Set the reply's body. Overwrite any existing entry. */
8267__LJMP static int hlua_txn_reply_set_body(lua_State *L)
8268{
8269 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
8270
8271 /* First argument (self) must be a table */
8272 luaL_checktype(L, 1, LUA_TTABLE);
8273
8274 lua_pushstring(L, payload);
8275 lua_setfield(L, 1, "body");
8276
8277 lua_pushboolean(L, 1);
8278 return 1;
8279}
8280
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008281__LJMP static int hlua_log(lua_State *L)
8282{
8283 int level;
8284 const char *msg;
8285
8286 MAY_LJMP(check_args(L, 2, "log"));
8287 level = MAY_LJMP(luaL_checkinteger(L, 1));
8288 msg = MAY_LJMP(luaL_checkstring(L, 2));
8289
8290 if (level < 0 || level >= NB_LOG_LEVELS)
8291 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
8292
8293 hlua_sendlog(NULL, level, msg);
8294 return 0;
8295}
8296
8297__LJMP static int hlua_log_debug(lua_State *L)
8298{
8299 const char *msg;
8300
8301 MAY_LJMP(check_args(L, 1, "debug"));
8302 msg = MAY_LJMP(luaL_checkstring(L, 1));
8303 hlua_sendlog(NULL, LOG_DEBUG, msg);
8304 return 0;
8305}
8306
8307__LJMP static int hlua_log_info(lua_State *L)
8308{
8309 const char *msg;
8310
8311 MAY_LJMP(check_args(L, 1, "info"));
8312 msg = MAY_LJMP(luaL_checkstring(L, 1));
8313 hlua_sendlog(NULL, LOG_INFO, msg);
8314 return 0;
8315}
8316
8317__LJMP static int hlua_log_warning(lua_State *L)
8318{
8319 const char *msg;
8320
8321 MAY_LJMP(check_args(L, 1, "warning"));
8322 msg = MAY_LJMP(luaL_checkstring(L, 1));
8323 hlua_sendlog(NULL, LOG_WARNING, msg);
8324 return 0;
8325}
8326
8327__LJMP static int hlua_log_alert(lua_State *L)
8328{
8329 const char *msg;
8330
8331 MAY_LJMP(check_args(L, 1, "alert"));
8332 msg = MAY_LJMP(luaL_checkstring(L, 1));
8333 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01008334 return 0;
8335}
8336
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008337__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008338{
8339 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau12c02702021-09-30 16:12:31 +02008340 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02008341 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008342 return 0;
8343}
8344
8345__LJMP static int hlua_sleep(lua_State *L)
8346{
8347 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008348 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008349
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008350 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008351
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008352 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008353 wakeup_ms = tick_add(now_ms, delay);
8354 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008355
Willy Tarreau9635e032018-10-16 17:52:55 +02008356 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008357 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008358}
8359
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008360__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008361{
8362 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008363 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008364
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008365 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008366
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008367 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008368 wakeup_ms = tick_add(now_ms, delay);
8369 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008370
Willy Tarreau9635e032018-10-16 17:52:55 +02008371 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008372 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008373}
8374
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008375/* This functionis an LUA binding. it permits to give back
8376 * the hand at the HAProxy scheduler. It is used when the
8377 * LUA processing consumes a lot of time.
8378 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008379__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008380{
8381 return 0;
8382}
8383
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008384__LJMP static int hlua_yield(lua_State *L)
8385{
Willy Tarreau9635e032018-10-16 17:52:55 +02008386 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008387 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008388}
8389
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008390/* This function change the nice of the currently executed
8391 * task. It is used set low or high priority at the current
8392 * task.
8393 */
Willy Tarreau59551662015-03-10 14:23:13 +01008394__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008395{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008396 struct hlua *hlua;
8397 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008398
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008399 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008400 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008401
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008402 /* Get hlua struct, or NULL if we execute from main lua state */
8403 hlua = hlua_gethlua(L);
8404
8405 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008406 if (!hlua || !hlua->task)
8407 return 0;
8408
8409 if (nice < -1024)
8410 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008411 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008412 nice = 1024;
8413
8414 hlua->task->nice = nice;
8415 return 0;
8416}
8417
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008418/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008419 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8420 * return an E_AGAIN signal, the emmiter of this signal must set a
8421 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008422 *
8423 * Task wrapper are longjmp safe because the only one Lua code
8424 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008425 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008426struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008427{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008428 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008429 enum hlua_exec status;
8430
Christopher Faulet5bc99722018-04-25 10:34:45 +02008431 if (task->thread_mask == MAX_THREADS_MASK)
8432 task_set_affinity(task, tid_bit);
8433
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008434 /* If it is the first call to the task, we must initialize the
8435 * execution timeouts.
8436 */
8437 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008438 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008439
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008440 /* Execute the Lua code. */
8441 status = hlua_ctx_resume(hlua, 1);
8442
8443 switch (status) {
8444 /* finished or yield */
8445 case HLUA_E_OK:
8446 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008447 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008448 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008449 break;
8450
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008451 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008452 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008453 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008454 break;
8455
8456 /* finished with error. */
8457 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008458 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008459 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008460 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008461 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008462 break;
8463
8464 case HLUA_E_ERR:
8465 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008466 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008467 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008468 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008469 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008470 break;
8471 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008472 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008473}
8474
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008475/* This function is an LUA binding that register LUA function to be
8476 * executed after the HAProxy configuration parsing and before the
8477 * HAProxy scheduler starts. This function expect only one LUA
8478 * argument that is a function. This function returns nothing, but
8479 * throws if an error is encountered.
8480 */
8481__LJMP static int hlua_register_init(lua_State *L)
8482{
8483 struct hlua_init_function *init;
8484 int ref;
8485
8486 MAY_LJMP(check_args(L, 1, "register_init"));
8487
8488 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8489
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008490 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008491 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008492 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008493
8494 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008495 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008496 return 0;
8497}
8498
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008499/* This functio is an LUA binding. It permits to register a task
8500 * executed in parallel of the main HAroxy activity. The task is
8501 * created and it is set in the HAProxy scheduler. It can be called
8502 * from the "init" section, "post init" or during the runtime.
8503 *
8504 * Lua prototype:
8505 *
8506 * <none> core.register_task(<function>)
8507 */
8508static int hlua_register_task(lua_State *L)
8509{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008510 struct hlua *hlua = NULL;
8511 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008512 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008513 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008514
8515 MAY_LJMP(check_args(L, 1, "register_task"));
8516
8517 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8518
Thierry Fournier75fc0292020-11-28 13:18:56 +01008519 /* Get the reference state. If the reference is NULL, L is the master
8520 * state, otherwise hlua->T is.
8521 */
8522 hlua = hlua_gethlua(L);
8523 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008524 /* we are in runtime processing */
8525 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008526 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008527 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008528 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008529
Willy Tarreaubafbe012017-11-24 17:34:44 +01008530 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008531 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008532 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008533 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008534
Thierry Fournier59f11be2020-11-29 00:37:41 +01008535 /* We are in the common lua state, execute the task anywhere,
8536 * otherwise, inherit the current thread identifier
8537 */
8538 if (state_id == 0)
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008539 task = task_new_anywhere();
Thierry Fournier59f11be2020-11-29 00:37:41 +01008540 else
Willy Tarreaubeeabf52021-10-01 18:23:30 +02008541 task = task_new_here();
Willy Tarreaue09101e2018-10-16 17:37:12 +02008542 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008543 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008544
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008545 task->context = hlua;
8546 task->process = hlua_process_task;
8547
Thierry Fournier021d9862020-11-28 23:42:03 +01008548 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008549 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008550
8551 /* Restore the function in the stack. */
8552 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8553 hlua->nargs = 0;
8554
8555 /* Schedule task. */
Willy Tarreaue3957f82021-09-30 16:17:37 +02008556 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008557
8558 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008559
8560 alloc_error:
8561 task_destroy(task);
8562 hlua_ctx_destroy(hlua);
8563 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8564 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008565}
8566
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008567/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8568 * doesn't allow "yield" functions because the HAProxy engine cannot
8569 * resume converters.
8570 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008571static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008572{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008573 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008574 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008575 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008576
Willy Tarreaube508f12016-03-10 11:47:01 +01008577 if (!stream)
8578 return 0;
8579
Willy Tarreau87b09662015-04-03 00:22:06 +02008580 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008581 * Lua context can be not initialized. This behavior
8582 * permits to save performances because a systematic
8583 * Lua initialization cause 5% performances loss.
8584 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008585 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008586 struct hlua *hlua;
8587
8588 hlua = pool_alloc(pool_head_hlua);
8589 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008590 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8591 return 0;
8592 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008593 HLUA_INIT(hlua);
8594 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008595 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008596 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8597 return 0;
8598 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008599 }
8600
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008601 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008602 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008603
8604 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008605 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008606 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8607 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008608 else
8609 error = "critical error";
8610 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008611 return 0;
8612 }
8613
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008614 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008615 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008616 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008617 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008618 return 0;
8619 }
8620
8621 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008622 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008623
8624 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008625 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008626 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008627 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008628 return 0;
8629 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008630 hlua_smp2lua(stream->hlua->T, smp);
8631 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008632
8633 /* push keywords in the stack. */
8634 if (arg_p) {
8635 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008636 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008637 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008638 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008639 return 0;
8640 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008641 hlua_arg2lua(stream->hlua->T, arg_p);
8642 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008643 }
8644 }
8645
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008646 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008647 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008648
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008649 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008650 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008651 }
8652
8653 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008654 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008655 /* finished. */
8656 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008657 /* If the stack is empty, the function fails. */
8658 if (lua_gettop(stream->hlua->T) <= 0)
8659 return 0;
8660
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008661 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008662 hlua_lua2smp(stream->hlua->T, -1, smp);
8663 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008664 return 1;
8665
8666 /* yield. */
8667 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008668 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008669 return 0;
8670
8671 /* finished with error. */
8672 case HLUA_E_ERRMSG:
8673 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008674 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008675 fcn->name, lua_tostring(stream->hlua->T, -1));
8676 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008677 return 0;
8678
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008679 case HLUA_E_ETMOUT:
8680 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8681 return 0;
8682
8683 case HLUA_E_NOMEM:
8684 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8685 return 0;
8686
8687 case HLUA_E_YIELD:
8688 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8689 return 0;
8690
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008691 case HLUA_E_ERR:
8692 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008693 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008694 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008695
8696 default:
8697 return 0;
8698 }
8699}
8700
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008701/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8702 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008703 * resume sample-fetches. This function will be called by the sample
8704 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008705 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008706static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8707 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008708{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008709 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008710 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008711 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008712 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008713
Willy Tarreaube508f12016-03-10 11:47:01 +01008714 if (!stream)
8715 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008716
Willy Tarreau87b09662015-04-03 00:22:06 +02008717 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008718 * Lua context can be not initialized. This behavior
8719 * permits to save performances because a systematic
8720 * Lua initialization cause 5% performances loss.
8721 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008722 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008723 struct hlua *hlua;
8724
8725 hlua = pool_alloc(pool_head_hlua);
8726 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008727 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8728 return 0;
8729 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008730 hlua->T = NULL;
8731 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008732 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008733 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8734 return 0;
8735 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008736 }
8737
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008738 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008739 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008740
8741 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008742 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008743 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8744 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008745 else
8746 error = "critical error";
8747 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008748 return 0;
8749 }
8750
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008751 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008752 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008753 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008754 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008755 return 0;
8756 }
8757
8758 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008759 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008760
8761 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008762 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008763 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008764 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008765 return 0;
8766 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008767 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008768
8769 /* push keywords in the stack. */
8770 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8771 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008772 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008773 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008774 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008775 return 0;
8776 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008777 hlua_arg2lua(stream->hlua->T, arg_p);
8778 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008779 }
8780
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008781 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008782 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008783
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008784 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008785 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008786 }
8787
8788 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008789 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008790 /* finished. */
8791 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008792 /* If the stack is empty, the function fails. */
8793 if (lua_gettop(stream->hlua->T) <= 0)
8794 return 0;
8795
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008796 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008797 hlua_lua2smp(stream->hlua->T, -1, smp);
8798 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008799
8800 /* Set the end of execution flag. */
8801 smp->flags &= ~SMP_F_MAY_CHANGE;
8802 return 1;
8803
8804 /* yield. */
8805 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008806 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008807 return 0;
8808
8809 /* finished with error. */
8810 case HLUA_E_ERRMSG:
8811 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008812 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008813 fcn->name, lua_tostring(stream->hlua->T, -1));
8814 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008815 return 0;
8816
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008817 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008818 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8819 return 0;
8820
8821 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008822 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8823 return 0;
8824
8825 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008826 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8827 return 0;
8828
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008829 case HLUA_E_ERR:
8830 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008831 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008832 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008833
8834 default:
8835 return 0;
8836 }
8837}
8838
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008839/* This function is an LUA binding used for registering
8840 * "sample-conv" functions. It expects a converter name used
8841 * in the haproxy configuration file, and an LUA function.
8842 */
8843__LJMP static int hlua_register_converters(lua_State *L)
8844{
8845 struct sample_conv_kw_list *sck;
8846 const char *name;
8847 int ref;
8848 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008849 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008850 struct sample_conv *sc;
8851 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008852
8853 MAY_LJMP(check_args(L, 2, "register_converters"));
8854
8855 /* First argument : converter name. */
8856 name = MAY_LJMP(luaL_checkstring(L, 1));
8857
8858 /* Second argument : lua function. */
8859 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8860
Thierry Fournierf67442e2020-11-28 20:41:07 +01008861 /* Check if the converter is already registered */
8862 trash = get_trash_chunk();
8863 chunk_printf(trash, "lua.%s", name);
8864 sc = find_sample_conv(trash->area, trash->data);
8865 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008866 fcn = sc->private;
8867 if (fcn->function_ref[hlua_state_id] != -1) {
8868 ha_warning("Trying to register converter 'lua.%s' more than once. "
8869 "This will become a hard error in version 2.5.\n", name);
8870 }
8871 fcn->function_ref[hlua_state_id] = ref;
8872 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008873 }
8874
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008875 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008876 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008877 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008878 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008879 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008880 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008881 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008882
8883 /* Fill fcn. */
8884 fcn->name = strdup(name);
8885 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008886 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008887 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008888
8889 /* List head */
8890 sck->list.n = sck->list.p = NULL;
8891
8892 /* converter keyword. */
8893 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008894 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008895 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008896 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008897
8898 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8899 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008900 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 +01008901 sck->kw[0].val_args = NULL;
8902 sck->kw[0].in_type = SMP_T_STR;
8903 sck->kw[0].out_type = SMP_T_STR;
8904 sck->kw[0].private = fcn;
8905
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008906 /* Register this new converter */
8907 sample_register_convs(sck);
8908
8909 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008910
8911 alloc_error:
8912 release_hlua_function(fcn);
8913 ha_free(&sck);
8914 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8915 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008916}
8917
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008918/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008919 * "sample-fetch" functions. It expects a converter name used
8920 * in the haproxy configuration file, and an LUA function.
8921 */
8922__LJMP static int hlua_register_fetches(lua_State *L)
8923{
8924 const char *name;
8925 int ref;
8926 int len;
8927 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008928 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008929 struct sample_fetch *sf;
8930 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008931
8932 MAY_LJMP(check_args(L, 2, "register_fetches"));
8933
8934 /* First argument : sample-fetch name. */
8935 name = MAY_LJMP(luaL_checkstring(L, 1));
8936
8937 /* Second argument : lua function. */
8938 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8939
Thierry Fournierf67442e2020-11-28 20:41:07 +01008940 /* Check if the sample-fetch is already registered */
8941 trash = get_trash_chunk();
8942 chunk_printf(trash, "lua.%s", name);
8943 sf = find_sample_fetch(trash->area, trash->data);
8944 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008945 fcn = sf->private;
8946 if (fcn->function_ref[hlua_state_id] != -1) {
8947 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8948 "This will become a hard error in version 2.5.\n", name);
8949 }
8950 fcn->function_ref[hlua_state_id] = ref;
8951 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008952 }
8953
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008954 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008955 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008956 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008957 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008958 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008959 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008960 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008961
8962 /* Fill fcn. */
8963 fcn->name = strdup(name);
8964 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008965 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008966 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008967
8968 /* List head */
8969 sfk->list.n = sfk->list.p = NULL;
8970
8971 /* sample-fetch keyword. */
8972 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008973 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008974 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008975 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008976
8977 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8978 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008979 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 +01008980 sfk->kw[0].val_args = NULL;
8981 sfk->kw[0].out_type = SMP_T_STR;
8982 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8983 sfk->kw[0].val = 0;
8984 sfk->kw[0].private = fcn;
8985
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008986 /* Register this new fetch. */
8987 sample_register_fetches(sfk);
8988
8989 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008990
8991 alloc_error:
8992 release_hlua_function(fcn);
8993 ha_free(&sfk);
8994 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8995 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008996}
8997
Christopher Faulet501465d2020-02-26 14:54:16 +01008998/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008999 */
Christopher Faulet501465d2020-02-26 14:54:16 +01009000__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009001{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009002 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009003 unsigned int delay;
9004 unsigned int wakeup_ms;
9005
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009006 /* Get hlua struct, or NULL if we execute from main lua state */
9007 hlua = hlua_gethlua(L);
9008 if (!hlua) {
9009 return 0;
9010 }
9011
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009012 MAY_LJMP(check_args(L, 1, "wake_time"));
9013
9014 delay = MAY_LJMP(luaL_checkinteger(L, 1));
9015 wakeup_ms = tick_add(now_ms, delay);
9016 hlua->wake_time = wakeup_ms;
9017 return 0;
9018}
9019
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009020/* This function is a wrapper to execute each LUA function declared as an action
9021 * wrapper during the initialisation period. This function may return any
9022 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
9023 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
9024 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009025 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009026static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02009027 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009028{
9029 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02009030 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009031 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009032 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009033
9034 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01009035 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
9036 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
9037 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
9038 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009039 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009040 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009041 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009042 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009043
Willy Tarreau87b09662015-04-03 00:22:06 +02009044 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009045 * Lua context can be not initialized. This behavior
9046 * permits to save performances because a systematic
9047 * Lua initialization cause 5% performances loss.
9048 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009049 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009050 struct hlua *hlua;
9051
9052 hlua = pool_alloc(pool_head_hlua);
9053 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009054 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009055 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009056 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009057 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01009058 HLUA_INIT(hlua);
9059 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01009060 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 +01009061 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009062 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009063 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009064 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01009065 }
9066
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009067 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009068 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009069
9070 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009071 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009072 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
9073 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01009074 else
9075 error = "critical error";
9076 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009077 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009078 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009079 }
9080
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009081 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009082 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009083 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009084 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009085 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009086 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009087 }
9088
9089 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009090 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 +01009091
Willy Tarreau87b09662015-04-03 00:22:06 +02009092 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02009093 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009094 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009095 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009096 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009097 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009098 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009099 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009100
9101 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009102 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009103 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009104 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009105 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009106 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009107 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009108 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009109 lua_pushstring(s->hlua->T, *arg);
9110 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009111 }
9112
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009113 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009114 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009115
Thierry FOURNIERbd413492015-03-03 16:52:26 +01009116 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009117 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009118 }
9119
9120 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01009121 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009122 /* finished. */
9123 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009124 /* Catch the return value */
9125 if (lua_gettop(s->hlua->T) > 0)
9126 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009127
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009128 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02009129 if (act_ret == ACT_RET_YIELD) {
9130 if (flags & ACT_OPT_FINAL)
9131 goto err_yield;
9132
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009133 if (dir == SMP_OPT_DIR_REQ)
9134 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9135 s->hlua->wake_time);
9136 else
9137 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9138 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009139 }
9140 goto end;
9141
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009142 /* yield. */
9143 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01009144 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009145 if (dir == SMP_OPT_DIR_REQ)
9146 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
9147 s->hlua->wake_time);
9148 else
9149 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
9150 s->hlua->wake_time);
9151
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009152 /* Some actions can be wake up when a "write" event
9153 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009154 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009155 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02009156 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009157 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009158 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01009159 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009160 act_ret = ACT_RET_YIELD;
9161 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009162
9163 /* finished with error. */
9164 case HLUA_E_ERRMSG:
9165 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009166 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009167 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01009168 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009169 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009170
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009171 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009172 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009173 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009174
9175 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01009176 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009177 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009178
9179 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02009180 err_yield:
9181 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009182 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009183 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009184 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009185
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009186 case HLUA_E_ERR:
9187 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02009188 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009189 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009190
9191 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009192 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009193 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009194
9195 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02009196 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02009197 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01009198 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009199}
9200
Willy Tarreau144f84a2021-03-02 16:09:26 +01009201struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009202{
Olivier Houchard9f6af332018-05-25 14:04:04 +02009203 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009204
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009205 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02009206 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02009207 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009208}
9209
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009210static int hlua_applet_tcp_init(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009211{
Christopher Faulet908628c2022-03-25 16:43:49 +01009212 struct conn_stream *cs = ctx->owner;
9213 struct stream *strm = __cs_strm(cs);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009214 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009215 struct task *task;
9216 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009217 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009218
Willy Tarreaubafbe012017-11-24 17:34:44 +01009219 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009220 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009221 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009222 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009223 return 0;
9224 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009225 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009226 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009227 ctx->ctx.hlua_apptcp.flags = 0;
9228
9229 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009230 task = task_new_here();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009231 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009232 SEND_ERR(strm->be, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009233 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009234 return 0;
9235 }
9236 task->nice = 0;
9237 task->context = ctx;
9238 task->process = hlua_applet_wakeup;
9239 ctx->ctx.hlua_apptcp.task = task;
9240
9241 /* In the execution wrappers linked with a stream, the
9242 * Lua context can be not initialized. This behavior
9243 * permits to save performances because a systematic
9244 * Lua initialization cause 5% performances loss.
9245 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009246 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 +01009247 SEND_ERR(strm->be, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009248 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009249 return 0;
9250 }
9251
9252 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009253 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009254
9255 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009256 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009257 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9258 error = lua_tostring(hlua->T, -1);
9259 else
9260 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009261 SEND_ERR(strm->be, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009262 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009263 return 0;
9264 }
9265
9266 /* Check stack available size. */
9267 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009268 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009269 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009270 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009271 return 0;
9272 }
9273
9274 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009275 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009276
9277 /* Create and and push object stream in the stack. */
9278 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009279 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009280 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009281 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009282 return 0;
9283 }
9284 hlua->nargs = 1;
9285
9286 /* push keywords in the stack. */
9287 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9288 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009289 SEND_ERR(strm->be, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009290 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009291 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009292 return 0;
9293 }
9294 lua_pushstring(hlua->T, *arg);
9295 hlua->nargs++;
9296 }
9297
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009298 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009299
9300 /* Wakeup the applet ASAP. */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009301 cs_cant_get(cs);
9302 cs_rx_endp_more(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009303
9304 return 1;
9305}
9306
Willy Tarreau60409db2019-08-21 14:14:50 +02009307void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009308{
Christopher Faulet908628c2022-03-25 16:43:49 +01009309 struct conn_stream *cs = ctx->owner;
9310 struct stream *strm = __cs_strm(cs);
9311 struct channel *res = cs_ic(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009312 struct act_rule *rule = ctx->rule;
9313 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009314 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009315
9316 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02009317 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
9318 /* eat the whole request */
Christopher Faulet908628c2022-03-25 16:43:49 +01009319 co_skip(cs_oc(cs), co_data(cs_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009320 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02009321 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009322
9323 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +02009324 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009325 return;
9326
9327 /* Execute the function. */
9328 switch (hlua_ctx_resume(hlua, 1)) {
9329 /* finished. */
9330 case HLUA_E_OK:
9331 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9332
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009333 /* eat the whole request */
Christopher Faulet908628c2022-03-25 16:43:49 +01009334 co_skip(cs_oc(cs), co_data(cs_oc(cs)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009335 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009336 cs_shutr(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009337 return;
9338
9339 /* yield. */
9340 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01009341 if (hlua->wake_time != TICK_ETERNITY)
9342 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009343 return;
9344
9345 /* finished with error. */
9346 case HLUA_E_ERRMSG:
9347 /* Display log. */
9348 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009349 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009350 lua_pop(hlua->T, 1);
9351 goto error;
9352
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009353 case HLUA_E_ETMOUT:
9354 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009355 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009356 goto error;
9357
9358 case HLUA_E_NOMEM:
9359 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009360 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009361 goto error;
9362
9363 case HLUA_E_YIELD: /* unexpected */
9364 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009365 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009366 goto error;
9367
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009368 case HLUA_E_ERR:
9369 /* Display log. */
9370 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009371 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009372 goto error;
9373
9374 default:
9375 goto error;
9376 }
9377
9378error:
9379
9380 /* For all other cases, just close the stream. */
Christopher Fauletda098e62022-03-31 17:44:45 +02009381 cs_shutw(cs);
9382 cs_shutr(cs);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009383 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9384}
9385
9386static void hlua_applet_tcp_release(struct appctx *ctx)
9387{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009388 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009389 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009390 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009391 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009392}
9393
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009394/* The function returns 1 if the initialisation is complete, 0 if
9395 * an errors occurs and -1 if more data are required for initializing
9396 * the applet.
9397 */
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009398static int hlua_applet_http_init(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009399{
Christopher Faulet908628c2022-03-25 16:43:49 +01009400 struct conn_stream *cs = ctx->owner;
9401 struct stream *strm = __cs_strm(cs);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009402 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009403 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009404 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009405 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009406 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009407
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009408 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009409 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009410 if (!hlua) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009411 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009412 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009413 return 0;
9414 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009415 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009416 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009417 ctx->ctx.hlua_apphttp.left_bytes = -1;
9418 ctx->ctx.hlua_apphttp.flags = 0;
9419
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009420 if (txn->req.flags & HTTP_MSGF_VER_11)
9421 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
9422
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009423 /* Create task used by signal to wakeup applets. */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02009424 task = task_new_here();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009425 if (!task) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009426 SEND_ERR(strm->be, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009427 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009428 return 0;
9429 }
9430 task->nice = 0;
9431 task->context = ctx;
9432 task->process = hlua_applet_wakeup;
9433 ctx->ctx.hlua_apphttp.task = task;
9434
9435 /* In the execution wrappers linked with a stream, the
9436 * Lua context can be not initialized. This behavior
9437 * permits to save performances because a systematic
9438 * Lua initialization cause 5% performances loss.
9439 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009440 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 +01009441 SEND_ERR(strm->be, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009442 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009443 return 0;
9444 }
9445
9446 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009447 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009448
9449 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009450 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009451 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9452 error = lua_tostring(hlua->T, -1);
9453 else
9454 error = "critical error";
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009455 SEND_ERR(strm->be, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009456 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009457 return 0;
9458 }
9459
9460 /* Check stack available size. */
9461 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009462 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009463 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009464 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009465 return 0;
9466 }
9467
9468 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009469 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009470
9471 /* Create and and push object stream in the stack. */
9472 if (!hlua_applet_http_new(hlua->T, ctx)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009473 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009474 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009475 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009476 return 0;
9477 }
9478 hlua->nargs = 1;
9479
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009480 /* push keywords in the stack. */
9481 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9482 if (!lua_checkstack(hlua->T, 1)) {
Christopher Faulet4aa1d282022-01-13 16:01:35 +01009483 SEND_ERR(strm->be, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009484 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009485 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009486 return 0;
9487 }
9488 lua_pushstring(hlua->T, *arg);
9489 hlua->nargs++;
9490 }
9491
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009492 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009493
9494 /* Wakeup the applet when data is ready for read. */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009495 cs_cant_get(cs);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009496
9497 return 1;
9498}
9499
Willy Tarreau60409db2019-08-21 14:14:50 +02009500void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009501{
Christopher Faulet908628c2022-03-25 16:43:49 +01009502 struct conn_stream *cs = ctx->owner;
9503 struct stream *strm = __cs_strm(cs);
9504 struct channel *req = cs_oc(cs);
9505 struct channel *res = cs_ic(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009506 struct act_rule *rule = ctx->rule;
9507 struct proxy *px = strm->be;
9508 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
9509 struct htx *req_htx, *res_htx;
9510
9511 res_htx = htx_from_buf(&res->buf);
9512
9513 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +02009514 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009515 goto out;
9516
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009517 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009518 if (!b_size(&res->buf)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009519 cs_rx_room_blk(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009520 goto out;
9521 }
9522 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009523 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009524 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9525
9526 /* Set the currently running flag. */
9527 if (!HLUA_IS_RUNNING(hlua) &&
9528 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009529 if (!co_data(req)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009530 cs_cant_get(cs);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009531 goto out;
9532 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009533 }
9534
9535 /* Executes The applet if it is not done. */
9536 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9537
9538 /* Execute the function. */
9539 switch (hlua_ctx_resume(hlua, 1)) {
9540 /* finished. */
9541 case HLUA_E_OK:
9542 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9543 break;
9544
9545 /* yield. */
9546 case HLUA_E_AGAIN:
9547 if (hlua->wake_time != TICK_ETERNITY)
9548 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009549 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009550
9551 /* finished with error. */
9552 case HLUA_E_ERRMSG:
9553 /* Display log. */
9554 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009555 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009556 lua_pop(hlua->T, 1);
9557 goto error;
9558
9559 case HLUA_E_ETMOUT:
9560 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009561 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009562 goto error;
9563
9564 case HLUA_E_NOMEM:
9565 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009566 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009567 goto error;
9568
9569 case HLUA_E_YIELD: /* unexpected */
9570 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009571 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009572 goto error;
9573
9574 case HLUA_E_ERR:
9575 /* Display log. */
9576 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009577 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009578 goto error;
9579
9580 default:
9581 goto error;
9582 }
9583 }
9584
9585 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009586 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9587 goto done;
9588
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009589 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9590 goto error;
9591
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009592 /* no more data are expected. If the response buffer is empty
9593 * for a chunked message, be sure to add something (EOT block in
9594 * this case) to have something to send. It is important to be
9595 * sure the EOM flags will be handled by the endpoint.
9596 */
9597 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
9598 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02009599 cs_rx_room_blk(cs);
Christopher Fauletf89af9c2022-04-07 10:07:18 +02009600 goto out;
9601 }
9602 channel_add_input(res, 1);
9603 }
9604
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009605 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet908628c2022-03-25 16:43:49 +01009606 cs->endp->flags |= CS_EP_EOI;
Christopher Fauletd8d27082022-03-07 15:50:54 +01009607 res->flags |= CF_EOI;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009608 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9609 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009610 }
9611
9612 done:
9613 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009614 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009615 res->flags |= CF_READ_NULL;
Christopher Fauletda098e62022-03-31 17:44:45 +02009616 cs_shutr(cs);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009617 }
9618
9619 /* eat the whole request */
9620 if (co_data(req)) {
9621 req_htx = htx_from_buf(&req->buf);
9622 co_htx_skip(req, req_htx, co_data(req));
9623 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009624 }
9625 }
9626
9627 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009628 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009629 return;
9630
9631 error:
9632
9633 /* If we are in HTTP mode, and we are not send any
9634 * data, return a 500 server error in best effort:
9635 * if there is no room available in the buffer,
9636 * just close the connection.
9637 */
9638 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009639 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009640
9641 channel_erase(res);
9642 res->buf.data = b_data(err);
9643 memcpy(res->buf.area, b_head(err), b_data(err));
9644 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009645 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009646 }
9647 if (!(strm->flags & SF_ERR_MASK))
9648 strm->flags |= SF_ERR_RESOURCE;
9649 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9650 goto done;
9651}
9652
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009653static void hlua_applet_http_release(struct appctx *ctx)
9654{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009655 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009656 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009657 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009658 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009659}
9660
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009661/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009662 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009663 *
9664 * This function can fail with an abort() due to an Lua critical error.
9665 * We are in the configuration parsing process of HAProxy, this abort() is
9666 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009667 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009668static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9669 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009670{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009671 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009672 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009673
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009674 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009675 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009676 if (!rule->arg.hlua_rule) {
9677 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009678 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009679 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009680
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009681 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009682 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9683 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009684 if (!rule->arg.hlua_rule->args) {
9685 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009686 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009687 }
9688
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009689 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009690 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009691
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009692 /* Expect some arguments */
9693 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009694 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009695 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009696 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009697 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009698 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009699 if (!rule->arg.hlua_rule->args[i]) {
9700 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009701 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009702 }
9703 (*cur_arg)++;
9704 }
9705 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009706
Thierry FOURNIER42148732015-09-02 17:17:33 +02009707 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009708 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009709 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009710
9711 error:
9712 if (rule->arg.hlua_rule) {
9713 if (rule->arg.hlua_rule->args) {
9714 for (i = 0; i < fcn->nargs; i++)
9715 ha_free(&rule->arg.hlua_rule->args[i]);
9716 ha_free(&rule->arg.hlua_rule->args);
9717 }
9718 ha_free(&rule->arg.hlua_rule);
9719 }
9720 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009721}
9722
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009723static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9724 struct act_rule *rule, char **err)
9725{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009726 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009727
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009728 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009729 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009730 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009731 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009732 * the call of this analyzer.
9733 */
9734 if (rule->from != ACT_F_HTTP_REQ) {
9735 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9736 return ACT_RET_PRS_ERR;
9737 }
9738
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009739 /* Memory for the rule. */
9740 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9741 if (!rule->arg.hlua_rule) {
9742 memprintf(err, "out of memory error");
9743 return ACT_RET_PRS_ERR;
9744 }
9745
9746 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009747 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009748
9749 /* TODO: later accept arguments. */
9750 rule->arg.hlua_rule->args = NULL;
9751
9752 /* Add applet pointer in the rule. */
9753 rule->applet.obj_type = OBJ_TYPE_APPLET;
9754 rule->applet.name = fcn->name;
9755 rule->applet.init = hlua_applet_http_init;
9756 rule->applet.fct = hlua_applet_http_fct;
9757 rule->applet.release = hlua_applet_http_release;
9758 rule->applet.timeout = hlua_timeout_applet;
9759
9760 return ACT_RET_PRS_OK;
9761}
9762
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009763/* This function is an LUA binding used for registering
9764 * "sample-conv" functions. It expects a converter name used
9765 * in the haproxy configuration file, and an LUA function.
9766 */
9767__LJMP static int hlua_register_action(lua_State *L)
9768{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009769 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009770 const char *name;
9771 int ref;
9772 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009773 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009774 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009775 struct buffer *trash;
9776 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009777
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009778 /* Initialise the number of expected arguments at 0. */
9779 nargs = 0;
9780
9781 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9782 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009783
9784 /* First argument : converter name. */
9785 name = MAY_LJMP(luaL_checkstring(L, 1));
9786
9787 /* Second argument : environment. */
9788 if (lua_type(L, 2) != LUA_TTABLE)
9789 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9790
9791 /* Third argument : lua function. */
9792 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9793
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009794 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009795 if (lua_gettop(L) >= 4)
9796 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9797
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009798 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009799 lua_pushnil(L);
9800 while (lua_next(L, 2) != 0) {
9801 if (lua_type(L, -1) != LUA_TSTRING)
9802 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9803
Thierry Fournierf67442e2020-11-28 20:41:07 +01009804 /* Check if action exists */
9805 trash = get_trash_chunk();
9806 chunk_printf(trash, "lua.%s", name);
9807 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9808 akw = tcp_req_cont_action(trash->area);
9809 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9810 akw = tcp_res_cont_action(trash->area);
9811 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9812 akw = action_http_req_custom(trash->area);
9813 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9814 akw = action_http_res_custom(trash->area);
9815 } else {
9816 akw = NULL;
9817 }
9818 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009819 fcn = akw->private;
9820 if (fcn->function_ref[hlua_state_id] != -1) {
9821 ha_warning("Trying to register action 'lua.%s' more than once. "
9822 "This will become a hard error in version 2.5.\n", name);
9823 }
9824 fcn->function_ref[hlua_state_id] = ref;
9825
9826 /* pop the environment string. */
9827 lua_pop(L, 1);
9828 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009829 }
9830
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009831 /* Check required environment. Only accepted "http" or "tcp". */
9832 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009833 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009834 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009835 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009836 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009837 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009838 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009839
9840 /* Fill fcn. */
9841 fcn->name = strdup(name);
9842 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009843 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009844 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009845
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009846 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009847 fcn->nargs = nargs;
9848
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009849 /* List head */
9850 akl->list.n = akl->list.p = NULL;
9851
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009852 /* action keyword. */
9853 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009854 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009855 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009856 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009857
9858 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9859
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009860 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009861 akl->kw[0].private = fcn;
9862 akl->kw[0].parse = action_register_lua;
9863
9864 /* select the action registering point. */
9865 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9866 tcp_req_cont_keywords_register(akl);
9867 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9868 tcp_res_cont_keywords_register(akl);
9869 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9870 http_req_keywords_register(akl);
9871 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9872 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009873 else {
9874 release_hlua_function(fcn);
9875 if (akl)
9876 ha_free((char **)&(akl->kw[0].kw));
9877 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009878 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009879 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9880 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009881 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009882
9883 /* pop the environment string. */
9884 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009885
9886 /* reset for next loop */
9887 akl = NULL;
9888 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009889 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009890 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009891
9892 alloc_error:
9893 release_hlua_function(fcn);
9894 ha_free(&akl);
9895 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9896 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009897}
9898
9899static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9900 struct act_rule *rule, char **err)
9901{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009902 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009903
Christopher Faulet280f85b2019-07-15 15:02:04 +02009904 if (px->mode == PR_MODE_HTTP) {
9905 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009906 return ACT_RET_PRS_ERR;
9907 }
9908
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009909 /* Memory for the rule. */
9910 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9911 if (!rule->arg.hlua_rule) {
9912 memprintf(err, "out of memory error");
9913 return ACT_RET_PRS_ERR;
9914 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009915
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009916 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009917 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009918
9919 /* TODO: later accept arguments. */
9920 rule->arg.hlua_rule->args = NULL;
9921
9922 /* Add applet pointer in the rule. */
9923 rule->applet.obj_type = OBJ_TYPE_APPLET;
9924 rule->applet.name = fcn->name;
9925 rule->applet.init = hlua_applet_tcp_init;
9926 rule->applet.fct = hlua_applet_tcp_fct;
9927 rule->applet.release = hlua_applet_tcp_release;
9928 rule->applet.timeout = hlua_timeout_applet;
9929
9930 return 0;
9931}
9932
9933/* This function is an LUA binding used for registering
9934 * "sample-conv" functions. It expects a converter name used
9935 * in the haproxy configuration file, and an LUA function.
9936 */
9937__LJMP static int hlua_register_service(lua_State *L)
9938{
9939 struct action_kw_list *akl;
9940 const char *name;
9941 const char *env;
9942 int ref;
9943 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009944 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009945 struct buffer *trash;
9946 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009947
9948 MAY_LJMP(check_args(L, 3, "register_service"));
9949
9950 /* First argument : converter name. */
9951 name = MAY_LJMP(luaL_checkstring(L, 1));
9952
9953 /* Second argument : environment. */
9954 env = MAY_LJMP(luaL_checkstring(L, 2));
9955
9956 /* Third argument : lua function. */
9957 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9958
Thierry Fournierf67442e2020-11-28 20:41:07 +01009959 /* Check for service already registered */
9960 trash = get_trash_chunk();
9961 chunk_printf(trash, "lua.%s", name);
9962 akw = service_find(trash->area);
9963 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009964 fcn = akw->private;
9965 if (fcn->function_ref[hlua_state_id] != -1) {
9966 ha_warning("Trying to register service 'lua.%s' more than once. "
9967 "This will become a hard error in version 2.5.\n", name);
9968 }
9969 fcn->function_ref[hlua_state_id] = ref;
9970 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009971 }
9972
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009973 /* Allocate and fill the sample fetch keyword struct. */
9974 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9975 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009976 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009977 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009978 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009979 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009980
9981 /* Fill fcn. */
9982 len = strlen("<lua.>") + strlen(name) + 1;
9983 fcn->name = calloc(1, len);
9984 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009985 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009986 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009987 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009988
9989 /* List head */
9990 akl->list.n = akl->list.p = NULL;
9991
9992 /* converter keyword. */
9993 len = strlen("lua.") + strlen(name) + 1;
9994 akl->kw[0].kw = calloc(1, len);
9995 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009996 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009997
9998 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9999
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +010010000 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010001 if (strcmp(env, "tcp") == 0)
10002 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020010003 else if (strcmp(env, "http") == 0)
10004 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010005 else {
10006 release_hlua_function(fcn);
10007 if (akl)
10008 ha_free((char **)&(akl->kw[0].kw));
10009 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +010010010 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +010010011 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +020010012 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010013
Amaury Denoyellee4a617c2021-05-06 15:33:09 +020010014 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010015 akl->kw[0].private = fcn;
10016
10017 /* End of array. */
10018 memset(&akl->kw[1], 0, sizeof(*akl->kw));
10019
10020 /* Register this new converter */
10021 service_keywords_register(akl);
10022
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010023 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +020010024
10025 alloc_error:
10026 release_hlua_function(fcn);
10027 ha_free(&akl);
10028 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10029 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +020010030}
10031
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010032/* This function initialises Lua cli handler. It copies the
10033 * arguments in the Lua stack and create channel IO objects.
10034 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +020010035static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010036{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010037 struct hlua_cli_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010038 struct hlua *hlua;
10039 struct hlua_function *fcn;
10040 int i;
10041 const char *error;
10042
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010043 fcn = private;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010044 ctx->fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010045
Willy Tarreaubafbe012017-11-24 17:34:44 +010010046 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010047 if (!hlua) {
10048 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010049 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +010010050 }
10051 HLUA_INIT(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010052 ctx->hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010053
10054 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +050010055 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010056 * applet_http. It is absolutely compatible.
10057 */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010058 ctx->task = task_new_here();
10059 if (!ctx->task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +010010060 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010061 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010062 }
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010063 ctx->task->nice = 0;
10064 ctx->task->context = appctx;
10065 ctx->task->process = hlua_applet_wakeup;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010066
10067 /* Initialises the Lua context */
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010068 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), ctx->task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010069 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +010010070 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010071 }
10072
10073 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010074 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010075 if (lua_type(hlua->T, -1) == LUA_TSTRING)
10076 error = lua_tostring(hlua->T, -1);
10077 else
10078 error = "critical error";
10079 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
10080 goto error;
10081 }
10082
10083 /* Check stack available size. */
10084 if (!lua_checkstack(hlua->T, 2)) {
10085 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10086 goto error;
10087 }
10088
10089 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +010010090 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010091
10092 /* Once the arguments parsed, the CLI is like an AppletTCP,
10093 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010094 */
10095 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
10096 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10097 goto error;
10098 }
10099 hlua->nargs = 1;
10100
10101 /* push keywords in the stack. */
10102 for (i = 0; *args[i]; i++) {
10103 /* Check stack available size. */
10104 if (!lua_checkstack(hlua->T, 1)) {
10105 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
10106 goto error;
10107 }
10108 lua_pushstring(hlua->T, args[i]);
10109 hlua->nargs++;
10110 }
10111
10112 /* We must initialize the execution timeouts. */
10113 hlua->max_time = hlua_timeout_session;
10114
10115 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010116 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010117
10118 /* It's ok */
10119 return 0;
10120
10121 /* It's not ok. */
10122error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +010010123 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010124 hlua_ctx_destroy(hlua);
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010125 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010126 return 1;
10127}
10128
10129static int hlua_cli_io_handler_fct(struct appctx *appctx)
10130{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010131 struct hlua_cli_ctx *ctx = appctx->svcctx;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010132 struct hlua *hlua;
Christopher Faulet908628c2022-03-25 16:43:49 +010010133 struct conn_stream *cs;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010134 struct hlua_function *fcn;
10135
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010136 hlua = ctx->hlua;
Christopher Faulet908628c2022-03-25 16:43:49 +010010137 cs = appctx->owner;
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010138 fcn = ctx->fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010139
10140 /* If the stream is disconnect or closed, ldo nothing. */
Christopher Faulet62e75742022-03-31 09:16:34 +020010141 if (unlikely(cs->state == CS_ST_DIS || cs->state == CS_ST_CLO))
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010142 return 1;
10143
10144 /* Execute the function. */
10145 switch (hlua_ctx_resume(hlua, 1)) {
10146
10147 /* finished. */
10148 case HLUA_E_OK:
10149 return 1;
10150
10151 /* yield. */
10152 case HLUA_E_AGAIN:
10153 /* We want write. */
10154 if (HLUA_IS_WAKERESWR(hlua))
Christopher Fauleta0bdec32022-04-04 07:51:21 +020010155 cs_rx_room_blk(cs);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010156 /* Set the timeout. */
10157 if (hlua->wake_time != TICK_ETERNITY)
10158 task_schedule(hlua->task, hlua->wake_time);
10159 return 0;
10160
10161 /* finished with error. */
10162 case HLUA_E_ERRMSG:
10163 /* Display log. */
10164 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
10165 fcn->name, lua_tostring(hlua->T, -1));
10166 lua_pop(hlua->T, 1);
10167 return 1;
10168
Thierry Fournierd5b073c2018-05-21 19:42:47 +020010169 case HLUA_E_ETMOUT:
10170 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
10171 fcn->name);
10172 return 1;
10173
10174 case HLUA_E_NOMEM:
10175 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
10176 fcn->name);
10177 return 1;
10178
10179 case HLUA_E_YIELD: /* unexpected */
10180 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
10181 fcn->name);
10182 return 1;
10183
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010184 case HLUA_E_ERR:
10185 /* Display log. */
10186 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
10187 fcn->name);
10188 return 1;
10189
10190 default:
10191 return 1;
10192 }
10193
10194 return 1;
10195}
10196
10197static void hlua_cli_io_release_fct(struct appctx *appctx)
10198{
Willy Tarreaubcda5f62022-05-03 18:13:39 +020010199 struct hlua_cli_ctx *ctx = appctx->svcctx;
10200
10201 hlua_ctx_destroy(ctx->hlua);
10202 ctx->hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010203}
10204
10205/* This function is an LUA binding used for registering
10206 * new keywords in the cli. It expects a list of keywords
10207 * which are the "path". It is limited to 5 keywords. A
10208 * description of the command, a function to be executed
10209 * for the parsing and a function for io handlers.
10210 */
10211__LJMP static int hlua_register_cli(lua_State *L)
10212{
10213 struct cli_kw_list *cli_kws;
10214 const char *message;
10215 int ref_io;
10216 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010217 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010218 int index;
10219 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010220 struct buffer *trash;
10221 const char *kw[5];
10222 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010223 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010224
10225 MAY_LJMP(check_args(L, 3, "register_cli"));
10226
10227 /* First argument : an array of maximum 5 keywords. */
10228 if (!lua_istable(L, 1))
10229 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
10230
10231 /* Second argument : string with contextual message. */
10232 message = MAY_LJMP(luaL_checkstring(L, 2));
10233
10234 /* Third and fourth argument : lua function. */
10235 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
10236
Thierry Fournierf67442e2020-11-28 20:41:07 +010010237 /* Check for CLI service already registered */
10238 trash = get_trash_chunk();
10239 index = 0;
10240 lua_pushnil(L);
10241 memset(kw, 0, sizeof(kw));
10242 while (lua_next(L, 1) != 0) {
10243 if (index >= CLI_PREFIX_KW_NB)
10244 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
10245 if (lua_type(L, -1) != LUA_TSTRING)
10246 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
10247 kw[index] = lua_tostring(L, -1);
10248 if (index == 0)
10249 chunk_printf(trash, "%s", kw[index]);
10250 else
10251 chunk_appendf(trash, " %s", kw[index]);
10252 index++;
10253 lua_pop(L, 1);
10254 }
10255 cli_kw = cli_find_kw_exact((char **)kw);
10256 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +010010257 fcn = cli_kw->private;
10258 if (fcn->function_ref[hlua_state_id] != -1) {
10259 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
10260 "This will become a hard error in version 2.5.\n", trash->area);
10261 }
10262 fcn->function_ref[hlua_state_id] = ref_io;
10263 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +010010264 }
10265
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010266 /* Allocate and fill the sample fetch keyword struct. */
10267 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010268 if (!cli_kws) {
10269 errmsg = "Lua out of memory error.";
10270 goto error;
10271 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +010010272 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010273 if (!fcn) {
10274 errmsg = "Lua out of memory error.";
10275 goto error;
10276 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010277
10278 /* Fill path. */
10279 index = 0;
10280 lua_pushnil(L);
10281 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010282 if (index >= 5) {
10283 errmsg = "1st argument must be a table with a maximum of 5 entries";
10284 goto error;
10285 }
10286 if (lua_type(L, -1) != LUA_TSTRING) {
10287 errmsg = "1st argument must be a table filled with strings";
10288 goto error;
10289 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010290 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010291 if (!cli_kws->kw[0].str_kw[index]) {
10292 errmsg = "Lua out of memory error.";
10293 goto error;
10294 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010295 index++;
10296 lua_pop(L, 1);
10297 }
10298
10299 /* Copy help message. */
10300 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010301 if (!cli_kws->kw[0].usage) {
10302 errmsg = "Lua out of memory error.";
10303 goto error;
10304 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010305
10306 /* Fill fcn io handler. */
10307 len = strlen("<lua.cli>") + 1;
10308 for (i = 0; i < index; i++)
10309 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
10310 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010311 if (!fcn->name) {
10312 errmsg = "Lua out of memory error.";
10313 goto error;
10314 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010315 strncat((char *)fcn->name, "<lua.cli", len);
10316 for (i = 0; i < index; i++) {
10317 strncat((char *)fcn->name, ".", len);
10318 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
10319 }
10320 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +010010321 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010322
10323 /* Fill last entries. */
10324 cli_kws->kw[0].private = fcn;
10325 cli_kws->kw[0].parse = hlua_cli_parse_fct;
10326 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
10327 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
10328
10329 /* Register this new converter */
10330 cli_register_kw(cli_kws);
10331
10332 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +020010333
10334 error:
10335 release_hlua_function(fcn);
10336 if (cli_kws) {
10337 for (i = 0; i < index; i++)
10338 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
10339 ha_free((char **)&(cli_kws->kw[0].usage));
10340 }
10341 ha_free(&cli_kws);
10342 WILL_LJMP(luaL_error(L, errmsg));
10343 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010010344}
10345
Christopher Faulet69c581a2021-05-31 08:54:04 +020010346static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
10347{
10348 struct hlua_flt_config *conf = fconf->conf;
10349 lua_State *L;
10350 int error, pos, state_id, flt_ref;
10351
10352 state_id = reg_flt_to_stack_id(conf->reg);
10353 L = hlua_states[state_id];
10354 pos = lua_gettop(L);
10355
10356 /* The filter parsing function */
10357 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
10358
10359 /* Push the filter class on the stack and resolve all callbacks */
10360 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
10361
10362 /* Duplicate the filter class so each filter will have its own copy */
10363 lua_newtable(L);
10364 lua_pushnil(L);
10365
10366 while (lua_next(L, pos+2)) {
10367 lua_pushvalue(L, -2);
10368 lua_insert(L, -2);
10369 lua_settable(L, -4);
10370 }
10371 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
10372
10373 /* Remove the original lua filter class from the stack */
10374 lua_pop(L, 1);
10375
10376 /* Push the copy on the stack */
10377 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10378
10379 /* extra args are pushed in a table */
10380 lua_newtable(L);
10381 for (pos = 0; conf->args[pos]; pos++) {
10382 /* Check stack available size. */
10383 if (!lua_checkstack(L, 1)) {
10384 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10385 goto error;
10386 }
10387 lua_pushstring(L, conf->args[pos]);
10388 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10389 }
10390
10391 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10392 switch (error) {
10393 case LUA_OK:
10394 /* replace the filter ref */
10395 conf->ref[state_id] = flt_ref;
10396 break;
10397 case LUA_ERRRUN:
10398 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10399 goto error;
10400 case LUA_ERRMEM:
10401 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10402 goto error;
10403 case LUA_ERRERR:
10404 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10405 goto error;
10406#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10407 case LUA_ERRGCMM:
10408 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10409 goto error;
10410#endif
10411 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010412 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010413 goto error;
10414 }
10415
10416 lua_settop(L, 0);
10417 return 0;
10418
10419 error:
10420 lua_settop(L, 0);
10421 return -1;
10422}
10423
10424static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10425{
10426 struct hlua_flt_config *conf = fconf->conf;
10427 lua_State *L;
10428 int state_id;
10429
10430 if (!conf)
10431 return;
10432
10433 state_id = reg_flt_to_stack_id(conf->reg);
10434 L = hlua_states[state_id];
10435 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10436}
10437
10438static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10439{
10440 struct hlua_flt_config *conf = fconf->conf;
10441 int state_id = reg_flt_to_stack_id(conf->reg);
10442
10443 /* Rely on per-thread init for global scripts */
10444 if (!state_id)
10445 return hlua_filter_init_per_thread(px, fconf);
10446 return 0;
10447}
10448
10449static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10450{
10451
10452 if (fconf->conf) {
10453 struct hlua_flt_config *conf = fconf->conf;
10454 int state_id = reg_flt_to_stack_id(conf->reg);
10455 int pos;
10456
10457 /* Rely on per-thread deinit for global scripts */
10458 if (!state_id)
10459 hlua_filter_deinit_per_thread(px, fconf);
10460
10461 for (pos = 0; conf->args[pos]; pos++)
10462 free(conf->args[pos]);
10463 free(conf->args);
10464 }
10465 ha_free(&fconf->conf);
10466 ha_free((char **)&fconf->id);
10467 ha_free(&fconf->ops);
10468}
10469
10470static int hlua_filter_new(struct stream *s, struct filter *filter)
10471{
10472 struct hlua_flt_config *conf = FLT_CONF(filter);
10473 struct hlua_flt_ctx *flt_ctx = NULL;
10474 int ret = 1;
10475
10476 /* In the execution wrappers linked with a stream, the
10477 * Lua context can be not initialized. This behavior
10478 * permits to save performances because a systematic
10479 * Lua initialization cause 5% performances loss.
10480 */
10481 if (!s->hlua) {
10482 struct hlua *hlua;
10483
10484 hlua = pool_alloc(pool_head_hlua);
10485 if (!hlua) {
10486 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10487 conf->reg->name);
10488 ret = 0;
10489 goto end;
10490 }
10491 HLUA_INIT(hlua);
10492 s->hlua = hlua;
10493 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10494 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10495 conf->reg->name);
10496 ret = 0;
10497 goto end;
10498 }
10499 }
10500
10501 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10502 if (!flt_ctx) {
10503 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10504 conf->reg->name);
10505 ret = 0;
10506 goto end;
10507 }
10508 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10509 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10510 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10511 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10512 conf->reg->name);
10513 ret = 0;
10514 goto end;
10515 }
10516 HLUA_INIT(flt_ctx->hlua[0]);
10517 HLUA_INIT(flt_ctx->hlua[1]);
10518 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10519 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10520 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10521 conf->reg->name);
10522 ret = 0;
10523 goto end;
10524 }
10525
10526 if (!HLUA_IS_RUNNING(s->hlua)) {
10527 /* The following Lua calls can fail. */
10528 if (!SET_SAFE_LJMP(s->hlua)) {
10529 const char *error;
10530
10531 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10532 error = lua_tostring(s->hlua->T, -1);
10533 else
10534 error = "critical error";
10535 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10536 ret = 0;
10537 goto end;
10538 }
10539
10540 /* Check stack size. */
10541 if (!lua_checkstack(s->hlua->T, 1)) {
10542 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010543 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010544 ret = 0;
10545 goto end;
10546 }
10547
10548 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10549 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10550 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10551 conf->reg->name);
10552 RESET_SAFE_LJMP(s->hlua);
10553 ret = 0;
10554 goto end;
10555 }
10556 lua_insert(s->hlua->T, -2);
10557
10558 /* Push the copy on the stack */
10559 s->hlua->nargs = 1;
10560
10561 /* We must initialize the execution timeouts. */
10562 s->hlua->max_time = hlua_timeout_session;
10563
10564 /* At this point the execution is safe. */
10565 RESET_SAFE_LJMP(s->hlua);
10566 }
10567
10568 switch (hlua_ctx_resume(s->hlua, 0)) {
10569 case HLUA_E_OK:
10570 /* Nothing returned or not a table, ignore the filter for current stream */
10571 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10572 ret = 0;
10573 goto end;
10574 }
10575
10576 /* Attached the filter pointer to the ctx */
10577 lua_pushstring(s->hlua->T, "__filter");
10578 lua_pushlightuserdata(s->hlua->T, filter);
10579 lua_settable(s->hlua->T, -3);
10580
10581 /* Save a ref on the filter ctx */
10582 lua_pushvalue(s->hlua->T, 1);
10583 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10584 filter->ctx = flt_ctx;
10585 break;
10586 case HLUA_E_ERRMSG:
10587 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10588 ret = -1;
10589 goto end;
10590 case HLUA_E_ETMOUT:
10591 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10592 ret = 0;
10593 goto end;
10594 case HLUA_E_NOMEM:
10595 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10596 ret = 0;
10597 goto end;
10598 case HLUA_E_AGAIN:
10599 case HLUA_E_YIELD:
10600 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10601 " are not allowed from 'new' function.\n", conf->reg->name);
10602 ret = 0;
10603 goto end;
10604 case HLUA_E_ERR:
10605 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10606 ret = 0;
10607 goto end;
10608 default:
10609 ret = 0;
10610 goto end;
10611 }
10612
10613 end:
10614 if (s->hlua)
10615 lua_settop(s->hlua->T, 0);
10616 if (ret <= 0) {
10617 if (flt_ctx) {
10618 hlua_ctx_destroy(flt_ctx->hlua[0]);
10619 hlua_ctx_destroy(flt_ctx->hlua[1]);
10620 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10621 }
10622 }
10623 return ret;
10624}
10625
10626static void hlua_filter_delete(struct stream *s, struct filter *filter)
10627{
10628 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10629
10630 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10631 hlua_ctx_destroy(flt_ctx->hlua[0]);
10632 hlua_ctx_destroy(flt_ctx->hlua[1]);
10633 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10634 filter->ctx = NULL;
10635}
10636
Christopher Faulet9f55a502020-02-25 15:21:02 +010010637static int hlua_filter_from_payload(struct filter *filter)
10638{
10639 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10640
10641 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10642}
10643
Christopher Fauletc404f112020-02-26 15:03:09 +010010644static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10645 int dir, unsigned int flags)
10646{
10647 struct hlua *flt_hlua;
10648 struct hlua_flt_config *conf = FLT_CONF(filter);
10649 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10650 unsigned int hflags = HLUA_TXN_FLT_CTX;
10651 int ret = 1;
10652
10653 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10654 if (!flt_hlua)
10655 goto end;
10656
10657 if (!HLUA_IS_RUNNING(flt_hlua)) {
10658 int extra_idx = lua_gettop(flt_hlua->T);
10659
10660 /* The following Lua calls can fail. */
10661 if (!SET_SAFE_LJMP(flt_hlua)) {
10662 const char *error;
10663
10664 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10665 error = lua_tostring(flt_hlua->T, -1);
10666 else
10667 error = "critical error";
10668 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10669 goto end;
10670 }
10671
10672 /* Check stack size. */
10673 if (!lua_checkstack(flt_hlua->T, 3)) {
10674 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10675 RESET_SAFE_LJMP(flt_hlua);
10676 goto end;
10677 }
10678
10679 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10680 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10681 RESET_SAFE_LJMP(flt_hlua);
10682 goto end;
10683 }
10684 lua_insert(flt_hlua->T, -2);
10685
10686 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10687 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10688 RESET_SAFE_LJMP(flt_hlua);
10689 goto end;
10690 }
10691 flt_hlua->nargs = 2;
10692
10693 if (flags & HLUA_FLT_CB_ARG_CHN) {
10694 if (dir == SMP_OPT_DIR_REQ)
10695 lua_getfield(flt_hlua->T, -1, "req");
10696 else
10697 lua_getfield(flt_hlua->T, -1, "res");
10698 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10699 lua_pushstring(flt_hlua->T, "__filter");
10700 lua_pushlightuserdata(flt_hlua->T, filter);
10701 lua_settable(flt_hlua->T, -3);
10702 }
10703 flt_hlua->nargs++;
10704 }
10705 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010706 if (dir == SMP_OPT_DIR_REQ)
10707 lua_getfield(flt_hlua->T, -1, "http_req");
10708 else
10709 lua_getfield(flt_hlua->T, -1, "http_res");
10710 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10711 lua_pushstring(flt_hlua->T, "__filter");
10712 lua_pushlightuserdata(flt_hlua->T, filter);
10713 lua_settable(flt_hlua->T, -3);
10714 }
10715 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010716 }
10717
10718 /* Check stack size. */
10719 if (!lua_checkstack(flt_hlua->T, 1)) {
10720 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10721 RESET_SAFE_LJMP(flt_hlua);
10722 goto end;
10723 }
10724
10725 while (extra_idx--) {
10726 lua_pushvalue(flt_hlua->T, 1);
10727 lua_remove(flt_hlua->T, 1);
10728 flt_hlua->nargs++;
10729 }
10730
10731 /* We must initialize the execution timeouts. */
10732 flt_hlua->max_time = hlua_timeout_session;
10733
10734 /* At this point the execution is safe. */
10735 RESET_SAFE_LJMP(flt_hlua);
10736 }
10737
10738 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10739 case HLUA_E_OK:
10740 /* Catch the return value if it required */
10741 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10742 ret = lua_tointeger(flt_hlua->T, -1);
10743 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10744 }
10745
10746 /* Set timeout in the required channel. */
10747 if (flt_hlua->wake_time != TICK_ETERNITY) {
10748 if (dir == SMP_OPT_DIR_REQ)
10749 s->req.analyse_exp = flt_hlua->wake_time;
10750 else
10751 s->res.analyse_exp = flt_hlua->wake_time;
10752 }
10753 break;
10754 case HLUA_E_AGAIN:
10755 /* Set timeout in the required channel. */
10756 if (flt_hlua->wake_time != TICK_ETERNITY) {
10757 if (dir == SMP_OPT_DIR_REQ)
10758 s->req.analyse_exp = flt_hlua->wake_time;
10759 else
10760 s->res.analyse_exp = flt_hlua->wake_time;
10761 }
10762 /* Some actions can be wake up when a "write" event
10763 * is detected on a response channel. This is useful
10764 * only for actions targeted on the requests.
10765 */
10766 if (HLUA_IS_WAKERESWR(flt_hlua))
10767 s->res.flags |= CF_WAKE_WRITE;
10768 if (HLUA_IS_WAKEREQWR(flt_hlua))
10769 s->req.flags |= CF_WAKE_WRITE;
10770 ret = 0;
10771 goto end;
10772 case HLUA_E_ERRMSG:
10773 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10774 ret = -1;
10775 goto end;
10776 case HLUA_E_ETMOUT:
10777 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10778 goto end;
10779 case HLUA_E_NOMEM:
10780 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10781 goto end;
10782 case HLUA_E_YIELD:
10783 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10784 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10785 goto end;
10786 case HLUA_E_ERR:
10787 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10788 goto end;
10789 default:
10790 goto end;
10791 }
10792
10793
10794 end:
10795 return ret;
10796}
10797
10798static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10799{
10800 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10801
10802 flt_ctx->flags = 0;
10803 return hlua_filter_callback(s, filter, "start_analyze",
10804 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10805 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10806}
10807
10808static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10809{
10810 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10811
10812 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10813 return hlua_filter_callback(s, filter, "end_analyze",
10814 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10815 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10816}
10817
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010818static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10819{
10820 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10821
10822 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10823 return hlua_filter_callback(s, filter, "http_headers",
10824 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10825 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10826}
10827
10828static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10829 unsigned int offset, unsigned int len)
10830{
10831 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10832 struct hlua *flt_hlua;
10833 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10834 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10835 int ret;
10836
10837 flt_hlua = flt_ctx->hlua[idx];
10838 flt_ctx->cur_off[idx] = offset;
10839 flt_ctx->cur_len[idx] = len;
10840 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10841 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10842 if (ret != -1) {
10843 ret = flt_ctx->cur_len[idx];
10844 if (lua_gettop(flt_hlua->T) > 0) {
10845 ret = lua_tointeger(flt_hlua->T, -1);
10846 if (ret > flt_ctx->cur_len[idx])
10847 ret = flt_ctx->cur_len[idx];
10848 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10849 }
10850 }
10851 return ret;
10852}
10853
10854static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10855{
10856 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10857
10858 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10859 return hlua_filter_callback(s, filter, "http_end",
10860 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10861 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10862}
10863
Christopher Fauletc404f112020-02-26 15:03:09 +010010864static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10865 unsigned int offset, unsigned int len)
10866{
10867 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10868 struct hlua *flt_hlua;
10869 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10870 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10871 int ret;
10872
10873 flt_hlua = flt_ctx->hlua[idx];
10874 flt_ctx->cur_off[idx] = offset;
10875 flt_ctx->cur_len[idx] = len;
10876 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10877 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10878 if (ret != -1) {
10879 ret = flt_ctx->cur_len[idx];
10880 if (lua_gettop(flt_hlua->T) > 0) {
10881 ret = lua_tointeger(flt_hlua->T, -1);
10882 if (ret > flt_ctx->cur_len[idx])
10883 ret = flt_ctx->cur_len[idx];
10884 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10885 }
10886 }
10887 return ret;
10888}
10889
Christopher Faulet69c581a2021-05-31 08:54:04 +020010890static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10891 struct flt_conf *fconf, char **err, void *private)
10892{
10893 struct hlua_reg_filter *reg_flt = private;
10894 lua_State *L;
10895 struct hlua_flt_config *conf = NULL;
10896 const char *flt_id = NULL;
10897 int state_id, pos, flt_flags = 0;
10898 struct flt_ops *hlua_flt_ops = NULL;
10899
10900 state_id = reg_flt_to_stack_id(reg_flt);
10901 L = hlua_states[state_id];
10902
10903 /* Initialize the filter ops with default callbacks */
10904 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010905 if (!hlua_flt_ops)
10906 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010907 hlua_flt_ops->init = hlua_filter_init;
10908 hlua_flt_ops->deinit = hlua_filter_deinit;
10909 if (state_id) {
10910 /* Set per-thread callback if script is loaded per-thread */
10911 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10912 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10913 }
10914 hlua_flt_ops->attach = hlua_filter_new;
10915 hlua_flt_ops->detach = hlua_filter_delete;
10916
10917 /* Push the filter class on the stack and resolve all callbacks */
10918 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10919
Christopher Fauletc404f112020-02-26 15:03:09 +010010920 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10921 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10922 lua_pop(L, 1);
10923 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10924 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10925 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010926 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10927 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10928 lua_pop(L, 1);
10929 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10930 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10931 lua_pop(L, 1);
10932 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10933 hlua_flt_ops->http_end = hlua_filter_http_end;
10934 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010935 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10936 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10937 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010938
10939 /* Get id and flags of the filter class */
10940 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10941 flt_id = lua_tostring(L, -1);
10942 lua_pop(L, 1);
10943 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10944 flt_flags = lua_tointeger(L, -1);
10945 lua_pop(L, 1);
10946
10947 /* Create the filter config */
10948 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010949 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010950 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010951 conf->reg = reg_flt;
10952
10953 /* duplicate args */
10954 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10955 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010956 if (!conf->args)
10957 goto error;
10958 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010959 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010960 if (!conf->args[pos])
10961 goto error;
10962 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010963 conf->args[pos] = NULL;
10964 *cur_arg += pos + 1;
10965
Christopher Fauletc86bb872021-08-13 08:33:57 +020010966 if (flt_id) {
10967 fconf->id = strdup(flt_id);
10968 if (!fconf->id)
10969 goto error;
10970 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010971 fconf->flags = flt_flags;
10972 fconf->conf = conf;
10973 fconf->ops = hlua_flt_ops;
10974
10975 lua_settop(L, 0);
10976 return 0;
10977
10978 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010979 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010980 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010981 if (conf && conf->args) {
10982 for (pos = 0; conf->args[pos]; pos++)
10983 free(conf->args[pos]);
10984 free(conf->args);
10985 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010986 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010987 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010988 lua_settop(L, 0);
10989 return -1;
10990}
10991
Christopher Fauletc404f112020-02-26 15:03:09 +010010992__LJMP static int hlua_register_data_filter(lua_State *L)
10993{
10994 struct filter *filter;
10995 struct channel *chn;
10996
10997 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10998 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10999 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11000
11001 lua_getfield(L, 1, "__filter");
11002 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11003 filter = lua_touserdata (L, -1);
11004 lua_pop(L, 1);
11005
11006 register_data_filter(chn_strm(chn), chn, filter);
11007 return 1;
11008}
11009
11010__LJMP static int hlua_unregister_data_filter(lua_State *L)
11011{
11012 struct filter *filter;
11013 struct channel *chn;
11014
11015 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
11016 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
11017 chn = MAY_LJMP(hlua_checkchannel(L, 2));
11018
11019 lua_getfield(L, 1, "__filter");
11020 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
11021 filter = lua_touserdata (L, -1);
11022 lua_pop(L, 1);
11023
11024 unregister_data_filter(chn_strm(chn), chn, filter);
11025 return 1;
11026}
11027
Christopher Faulet69c581a2021-05-31 08:54:04 +020011028/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011029 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020011030 * parse configuration arguments.
11031 */
11032__LJMP static int hlua_register_filter(lua_State *L)
11033{
11034 struct buffer *trash;
11035 struct flt_kw_list *fkl;
11036 struct flt_kw *fkw;
11037 const char *name;
11038 struct hlua_reg_filter *reg_flt= NULL;
11039 int flt_ref, fun_ref;
11040 int len;
11041
11042 MAY_LJMP(check_args(L, 3, "register_filter"));
11043
11044 /* First argument : filter name. */
11045 name = MAY_LJMP(luaL_checkstring(L, 1));
11046
11047 /* Second argument : The filter class */
11048 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
11049
11050 /* Third argument : lua function. */
11051 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
11052
11053 trash = get_trash_chunk();
11054 chunk_printf(trash, "lua.%s", name);
11055 fkw = flt_find_kw(trash->area);
11056 if (fkw != NULL) {
11057 reg_flt = fkw->private;
11058 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
11059 ha_warning("Trying to register filter 'lua.%s' more than once. "
11060 "This will become a hard error in version 2.5.\n", name);
11061 }
11062 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11063 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11064 return 0;
11065 }
11066
11067 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
11068 if (!fkl)
11069 goto alloc_error;
11070 fkl->scope = "HLUA";
11071
11072 reg_flt = new_hlua_reg_filter(name);
11073 if (!reg_flt)
11074 goto alloc_error;
11075
11076 reg_flt->flt_ref[hlua_state_id] = flt_ref;
11077 reg_flt->fun_ref[hlua_state_id] = fun_ref;
11078
11079 /* The filter keyword */
11080 len = strlen("lua.") + strlen(name) + 1;
11081 fkl->kw[0].kw = calloc(1, len);
11082 if (!fkl->kw[0].kw)
11083 goto alloc_error;
11084
11085 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
11086
11087 fkl->kw[0].parse = hlua_filter_parse_fct;
11088 fkl->kw[0].private = reg_flt;
11089 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
11090
11091 /* Register this new filter */
11092 flt_register_keywords(fkl);
11093
11094 return 0;
11095
11096 alloc_error:
11097 release_hlua_reg_filter(reg_flt);
11098 ha_free(&fkl);
11099 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
11100 return 0; /* Never reached */
11101}
11102
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011103static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011104 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011105 char **err, unsigned int *timeout)
11106{
11107 const char *error;
11108
11109 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020011110 if (error == PARSE_TIME_OVER) {
11111 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
11112 args[1], args[0]);
11113 return -1;
11114 }
11115 else if (error == PARSE_TIME_UNDER) {
11116 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
11117 args[1], args[0]);
11118 return -1;
11119 }
11120 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011121 memprintf(err, "%s: invalid timeout", args[0]);
11122 return -1;
11123 }
11124 return 0;
11125}
11126
11127static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011128 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011129 char **err)
11130{
11131 return hlua_read_timeout(args, section_type, curpx, defpx,
11132 file, line, err, &hlua_timeout_session);
11133}
11134
11135static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011136 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011137 char **err)
11138{
11139 return hlua_read_timeout(args, section_type, curpx, defpx,
11140 file, line, err, &hlua_timeout_task);
11141}
11142
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011143static int hlua_applet_timeout(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,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011145 char **err)
11146{
11147 return hlua_read_timeout(args, section_type, curpx, defpx,
11148 file, line, err, &hlua_timeout_applet);
11149}
11150
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011151static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011152 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011153 char **err)
11154{
11155 char *error;
11156
11157 hlua_nb_instruction = strtoll(args[1], &error, 10);
11158 if (*error != '\0') {
11159 memprintf(err, "%s: invalid number", args[0]);
11160 return -1;
11161 }
11162 return 0;
11163}
11164
Willy Tarreau32f61e22015-03-18 17:54:59 +010011165static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011166 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010011167 char **err)
11168{
11169 char *error;
11170
11171 if (*(args[1]) == 0) {
11172 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
11173 return -1;
11174 }
11175 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
11176 if (*error != '\0') {
11177 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
11178 return -1;
11179 }
11180 return 0;
11181}
11182
11183
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011184/* This function is called by the main configuration key "lua-load". It loads and
11185 * execute an lua file during the parsing of the HAProxy configuration file. It is
11186 * the main lua entry point.
11187 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011188 * This function runs with the HAProxy keywords API. It returns -1 if an error
11189 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011190 *
11191 * In some error case, LUA set an error message in top of the stack. This function
11192 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011193 *
11194 * This function can fail with an abort() due to an Lua critical error.
11195 * We are in the configuration parsing process of HAProxy, this abort() is
11196 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011197 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011198static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011199{
11200 int error;
11201
11202 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011203 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011204 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011205 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
11206 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011207 return -1;
11208 }
11209
11210 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011211 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011212 switch (error) {
11213 case LUA_OK:
11214 break;
11215 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011216 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
11217 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011218 return -1;
11219 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010011220 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011221 return -1;
11222 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011223 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
11224 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011225 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011226#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011227 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011228 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
11229 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011230 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020011231#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011232 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011233 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
11234 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011235 return -1;
11236 }
11237
11238 return 0;
11239}
11240
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011241static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011242 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011243 char **err)
11244{
11245 if (*(args[1]) == 0) {
11246 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
11247 return -1;
11248 }
11249
Thierry Fournier59f11be2020-11-29 00:37:41 +010011250 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010011251 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011252 ha_set_thread(NULL);
Thierry Fournierafc63e22020-11-28 17:06:51 +010011253 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010011254}
11255
Thierry Fournier59f11be2020-11-29 00:37:41 +010011256static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011257 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010011258 char **err)
11259{
11260 int len;
11261
11262 if (*(args[1]) == 0) {
11263 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
11264 return -1;
11265 }
11266
11267 if (per_thread_load == NULL) {
11268 /* allocate the first entry large enough to store the final NULL */
11269 per_thread_load = calloc(1, sizeof(*per_thread_load));
11270 if (per_thread_load == NULL) {
11271 memprintf(err, "out of memory error");
11272 return -1;
11273 }
11274 }
11275
11276 /* count used entries */
11277 for (len = 0; per_thread_load[len] != NULL; len++)
11278 ;
11279
11280 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
11281 if (per_thread_load == NULL) {
11282 memprintf(err, "out of memory error");
11283 return -1;
11284 }
11285
11286 per_thread_load[len] = strdup(args[1]);
11287 per_thread_load[len + 1] = NULL;
11288
11289 if (per_thread_load[len] == NULL) {
11290 memprintf(err, "out of memory error");
11291 return -1;
11292 }
11293
11294 /* loading for thread 1 only */
11295 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011296 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011297 return hlua_load_state(args[1], hlua_states[1], err);
11298}
11299
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011300/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
11301 * in the given <ctx>.
11302 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011303static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011304{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010011305 lua_getglobal(L, "package"); /* push package variable */
11306 lua_pushstring(L, path); /* push given path */
11307 lua_pushstring(L, ";"); /* push semicolon */
11308 lua_getfield(L, -3, type); /* push old path */
11309 lua_concat(L, 3); /* concatenate to new path */
11310 lua_setfield(L, -2, type); /* store new path */
11311 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010011312
11313 return 0;
11314}
11315
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011316static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010011317 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011318 char **err)
11319{
11320 char *path;
11321 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011322 struct prepend_path *p = NULL;
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011323 size_t i;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011324
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011325 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011326 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011327 }
11328
11329 if (!(*args[1])) {
11330 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011331 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011332 }
11333 path = args[1];
11334
11335 if (*args[2]) {
11336 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
11337 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011338 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011339 }
11340 type = args[2];
11341 }
11342
Thierry Fournier59f11be2020-11-29 00:37:41 +010011343 p = calloc(1, sizeof(*p));
11344 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011345 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011346 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011347 }
11348 p->path = strdup(path);
11349 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011350 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011351 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011352 }
11353 p->type = strdup(type);
11354 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010011355 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011356 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011357 }
Willy Tarreau2b718102021-04-21 07:32:39 +020011358 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011359
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011360 /* Handle the global state and the per-thread state for the first
11361 * thread. The remaining threads will be initialized based on
11362 * prepend_path_list.
11363 */
Bertrand Jacquin7fbc7702021-11-24 21:16:06 +000011364 for (i = 0; i < 2; i++) {
Tim Duesterhus9e5e5862021-10-11 18:51:08 +020011365 lua_State *L = hlua_states[i];
11366 const char *error;
11367
11368 if (setjmp(safe_ljmp_env) != 0) {
11369 lua_atpanic(L, hlua_panic_safe);
11370 if (lua_type(L, -1) == LUA_TSTRING)
11371 error = lua_tostring(L, -1);
11372 else
11373 error = "critical error";
11374 fprintf(stderr, "lua-prepend-path: %s.\n", error);
11375 exit(1);
11376 } else {
11377 lua_atpanic(L, hlua_panic_ljmp);
11378 }
11379
11380 hlua_prepend_path(L, type, path);
11381
11382 lua_atpanic(L, hlua_panic_safe);
11383 }
11384
Thierry Fournier59f11be2020-11-29 00:37:41 +010011385 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010011386
11387err2:
11388 free(p->type);
11389 free(p->path);
11390err:
11391 free(p);
11392 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011393}
11394
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011395/* configuration keywords declaration */
11396static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010011397 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011398 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010011399 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011400 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11401 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011402 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011403 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011404 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011405 { 0, NULL, NULL },
11406}};
11407
Willy Tarreau0108d902018-11-25 19:14:37 +010011408INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11409
William Lallemand52139182022-03-30 15:05:42 +020011410#ifdef USE_OPENSSL
Christopher Fauletafd8f102018-11-08 11:34:21 +010011411
William Lallemand30fcca12022-03-30 12:03:12 +020011412/*
11413 * This function replace a ckch_store by another one, and rebuild the ckch_inst and all its dependencies.
11414 * It does the sam as "cli_io_handler_commit_cert" but for lua, the major
11415 * difference is that the yield in lua and for the CLI is not handled the same
11416 * way.
11417 */
11418__LJMP static int hlua_ckch_commit_yield(lua_State *L, int status, lua_KContext ctx)
11419{
11420 struct ckch_inst **lua_ckchi = lua_touserdata(L, -1);
11421 struct ckch_store **lua_ckchs = lua_touserdata(L, -2);
11422 struct ckch_inst *ckchi = *lua_ckchi;
11423 struct ckch_store *old_ckchs = lua_ckchs[0];
11424 struct ckch_store *new_ckchs = lua_ckchs[1];
11425 struct hlua *hlua;
11426 char *err = NULL;
11427 int y = 1;
11428
11429 hlua = hlua_gethlua(L);
11430
11431 /* get the first ckchi to copy */
11432 if (ckchi == NULL)
11433 ckchi = LIST_ELEM(old_ckchs->ckch_inst.n, typeof(ckchi), by_ckchs);
11434
11435 /* walk through the old ckch_inst and creates new ckch_inst using the updated ckchs */
11436 list_for_each_entry_from(ckchi, &old_ckchs->ckch_inst, by_ckchs) {
11437 struct ckch_inst *new_inst;
11438
11439 /* it takes a lot of CPU to creates SSL_CTXs, so we yield every 10 CKCH instances */
11440 if (y % 10 == 0) {
11441
11442 *lua_ckchi = ckchi;
11443
11444 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11445 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11446 }
11447
11448 if (ckch_inst_rebuild(new_ckchs, ckchi, &new_inst, &err))
11449 goto error;
11450
11451 /* link the new ckch_inst to the duplicate */
11452 LIST_APPEND(&new_ckchs->ckch_inst, &new_inst->by_ckchs);
11453 y++;
11454 }
11455
11456 /* The generation is finished, we can insert everything */
11457 ckch_store_replace(old_ckchs, new_ckchs);
11458
11459 lua_pop(L, 2); /* pop the lua_ckchs and ckchi */
11460
11461 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11462
11463 return 0;
11464
11465error:
11466 ckch_store_free(new_ckchs);
11467 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11468 WILL_LJMP(luaL_error(L, "%s", err));
11469 free(err);
11470
11471 return 0;
11472}
11473
11474/*
11475 * Replace a ckch_store <filename> in the ckchs_tree with a ckch_store created
11476 * from the table in parameter.
11477 *
11478 * This is equivalent to "set ssl cert" + "commit ssl cert" over the CLI, which
11479 * means it does not need to have a transaction since everything is done in the
11480 * same function.
11481 *
11482 * CertCache.set{filename="", crt="", key="", sctl="", ocsp="", issuer=""}
11483 *
11484 */
11485__LJMP static int hlua_ckch_set(lua_State *L)
11486{
11487 struct hlua *hlua;
11488 struct ckch_inst **lua_ckchi;
11489 struct ckch_store **lua_ckchs;
11490 struct ckch_store *old_ckchs = NULL;
11491 struct ckch_store *new_ckchs = NULL;
11492 int errcode = 0;
11493 char *err = NULL;
11494 struct cert_exts *cert_ext = NULL;
11495 char *filename;
11496 struct cert_key_and_chain *ckch;
11497 int ret;
11498
11499 if (lua_type(L, -1) != LUA_TTABLE)
11500 WILL_LJMP(luaL_error(L, "'CertCache.set' needs a table as argument"));
11501
11502 hlua = hlua_gethlua(L);
11503
11504 /* FIXME: this should not return an error but should come back later */
11505 if (HA_SPIN_TRYLOCK(CKCH_LOCK, &ckch_lock))
11506 WILL_LJMP(luaL_error(L, "CertCache already under lock"));
11507
11508 ret = lua_getfield(L, -1, "filename");
11509 if (ret != LUA_TSTRING) {
11510 memprintf(&err, "%sNo filename specified!\n", err ? err : "");
11511 errcode |= ERR_ALERT | ERR_FATAL;
11512 goto end;
11513 }
11514 filename = (char *)lua_tostring(L, -1);
11515
11516
11517 /* look for the filename in the tree */
11518 old_ckchs = ckchs_lookup(filename);
11519 if (!old_ckchs) {
11520 memprintf(&err, "%sCan't replace a certificate which is not referenced by the configuration!\n", err ? err : "");
11521 errcode |= ERR_ALERT | ERR_FATAL;
11522 goto end;
11523 }
11524 /* TODO: handle extra_files_noext */
11525
11526 new_ckchs = ckchs_dup(old_ckchs);
11527 if (!new_ckchs) {
11528 memprintf(&err, "%sCannot allocate memory!\n", err ? err : "");
11529 errcode |= ERR_ALERT | ERR_FATAL;
11530 goto end;
11531 }
11532
11533 ckch = new_ckchs->ckch;
11534
11535 /* loop on the field in the table, which have the same name as the
11536 * possible extensions of files */
11537 lua_pushnil(L);
11538 while (lua_next(L, 1)) {
11539 int i;
11540 const char *field = lua_tostring(L, -2);
11541 char *payload = (char *)lua_tostring(L, -1);
11542
11543 if (!field || strcmp(field, "filename") == 0) {
11544 lua_pop(L, 1);
11545 continue;
11546 }
11547
11548 for (i = 0; field && cert_exts[i].ext != NULL; i++) {
11549 if (strcmp(field, cert_exts[i].ext) == 0) {
11550 cert_ext = &cert_exts[i];
11551 break;
11552 }
11553 }
11554
11555 /* this is the default type, the field is not supported */
11556 if (cert_ext == NULL) {
11557 memprintf(&err, "%sUnsupported field '%s'\n", err ? err : "", field);
11558 errcode |= ERR_ALERT | ERR_FATAL;
11559 goto end;
11560 }
11561
11562 /* appply the change on the duplicate */
11563 if (cert_exts->load(filename, payload, ckch, &err) != 0) {
11564 memprintf(&err, "%sCan't load the payload\n", err ? err : "");
11565 errcode |= ERR_ALERT | ERR_FATAL;
11566 goto end;
11567 }
11568 lua_pop(L, 1);
11569 }
11570
11571 /* store the pointers on the lua stack */
11572 lua_ckchs = lua_newuserdata(L, sizeof(struct ckch_store *) * 2);
11573 lua_ckchs[0] = old_ckchs;
11574 lua_ckchs[1] = new_ckchs;
11575 lua_ckchi = lua_newuserdata(L, sizeof(struct ckch_inst *));
11576 *lua_ckchi = NULL;
11577
11578 task_wakeup(hlua->task, TASK_WOKEN_MSG);
11579 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_ckch_commit_yield, TICK_ETERNITY, 0));
11580
11581end:
11582 HA_SPIN_UNLOCK(CKCH_LOCK, &ckch_lock);
11583
11584 if (errcode & ERR_CODE) {
11585 ckch_store_free(new_ckchs);
11586 WILL_LJMP(luaL_error(L, "%s", err));
11587 }
11588 free(err);
11589
11590 return 0;
11591}
11592
William Lallemand52139182022-03-30 15:05:42 +020011593#else
11594
11595__LJMP static int hlua_ckch_set(lua_State *L)
11596{
11597 WILL_LJMP(luaL_error(L, "'CertCache.set' needs an HAProxy built with OpenSSL"));
11598
11599 return 0;
11600}
11601#endif /* ! USE_OPENSSL */
11602
11603
11604
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011605/* This function can fail with an abort() due to an Lua critical error.
11606 * We are in the initialisation process of HAProxy, this abort() is
11607 * tolerated.
11608 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011609int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011610{
11611 struct hlua_init_function *init;
11612 const char *msg;
11613 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011614 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011615 const char *kind;
11616 const char *trace;
11617 int return_status = 1;
11618#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11619 int nres;
11620#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011621
Willy Tarreaucdb53462020-12-02 12:12:00 +010011622 /* disable memory limit checks if limit is not set */
11623 if (!hlua_global_allocator.limit)
11624 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11625
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011626 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011627 if (setjmp(safe_ljmp_env) != 0) {
11628 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011629 if (lua_type(L, -1) == LUA_TSTRING)
11630 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011631 else
11632 error = "critical error";
11633 fprintf(stderr, "Lua post-init: %s.\n", error);
11634 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011635 } else {
11636 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011637 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011638
Thierry Fournierb8cef172020-11-28 15:37:17 +010011639 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011640
Thierry Fournierc7492592020-11-28 23:57:24 +010011641 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011642 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011643
11644#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011645 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011646#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011647 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011648#endif
11649 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011650 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011651
11652 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011653 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011654 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011655
11656 case LUA_ERRERR:
11657 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011658 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011659 case LUA_ERRRUN:
11660 if (!kind)
11661 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011662 msg = lua_tostring(L, -1);
11663 lua_settop(L, 0); /* Empty the stack. */
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 if (msg)
11667 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11668 else
11669 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11670 return_status = 0;
11671 break;
11672
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011673 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011674 /* Unknown error */
11675 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011676 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011677 case LUA_YIELD:
11678 /* yield is not configured at this step, this state doesn't happen */
11679 if (!kind)
11680 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011681 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011682 case LUA_ERRMEM:
11683 if (!kind)
11684 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011685 lua_settop(L, 0);
11686 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011687 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011688 ha_alert("Lua init: %s: %s\n", kind, trace);
11689 return_status = 0;
11690 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011691 }
Thierry Fournier670db242020-11-28 10:49:59 +010011692 if (!return_status)
11693 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011694 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011695
11696 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011697 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011698}
11699
Thierry Fournierb8cef172020-11-28 15:37:17 +010011700int hlua_post_init()
11701{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011702 int ret;
11703 int i;
11704 int errors;
11705 char *err = NULL;
11706 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011707 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011708
Willy Tarreaub1310492021-08-30 09:35:18 +020011709#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011710 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011711 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011712 int saved_used_backed = global.ssl_used_backend;
11713 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011714 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011715 global.ssl_used_backend = saved_used_backed;
11716 }
11717#endif
11718
Thierry Fournierc7492592020-11-28 23:57:24 +010011719 /* Perform post init of common thread */
11720 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011721 ha_set_thread(&ha_thread_info[0]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011722 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11723 if (ret == 0)
11724 return 0;
11725
11726 /* init remaining lua states and load files */
11727 for (hlua_state_id = 2; 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 /* Init lua state */
11733 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11734
11735 /* Load lua files */
11736 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11737 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11738 if (ret != 0) {
11739 ha_alert("Lua init: %s\n", err);
11740 return 0;
11741 }
11742 }
11743 }
11744
11745 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011746 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011747
11748 /* Execute post init for all states */
11749 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11750
11751 /* set thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011752 ha_set_thread(&ha_thread_info[hlua_state_id - 1]);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011753
11754 /* run post init */
11755 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11756 if (ret == 0)
11757 return 0;
11758 }
11759
11760 /* Reset thread context */
Willy Tarreau43ab05b2021-09-28 09:43:11 +020011761 ha_set_thread(NULL);
Thierry Fournier59f11be2020-11-29 00:37:41 +010011762
11763 /* control functions registering. Each function must have:
11764 * - only the function_ref[0] set positive and all other to -1
11765 * - only the function_ref[0] set to -1 and all other positive
11766 * This ensure a same reference is not used both in shared
11767 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011768 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011769 * complicated to found for the end user.
11770 */
11771 errors = 0;
11772 list_for_each_entry(fcn, &referenced_functions, l) {
11773 ret = 0;
11774 for (i = 1; i < global.nbthread + 1; i++) {
11775 if (fcn->function_ref[i] == -1)
11776 ret--;
11777 else
11778 ret++;
11779 }
11780 if (abs(ret) != global.nbthread) {
11781 ha_alert("Lua function '%s' is not referenced in all thread. "
11782 "Expect function in all thread or in none thread.\n", fcn->name);
11783 errors++;
11784 continue;
11785 }
11786
11787 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011788 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11789 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011790 "exclusive.\n", fcn->name);
11791 errors++;
11792 }
11793 }
11794
Christopher Faulet69c581a2021-05-31 08:54:04 +020011795 /* Do the same with registered filters */
11796 list_for_each_entry(reg_flt, &referenced_filters, l) {
11797 ret = 0;
11798 for (i = 1; i < global.nbthread + 1; i++) {
11799 if (reg_flt->flt_ref[i] == -1)
11800 ret--;
11801 else
11802 ret++;
11803 }
11804 if (abs(ret) != global.nbthread) {
11805 ha_alert("Lua filter '%s' is not referenced in all thread. "
11806 "Expect function in all thread or in none thread.\n", reg_flt->name);
11807 errors++;
11808 continue;
11809 }
11810
11811 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11812 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11813 "and per-thread Lua context (through lua-load-per-thread). these two context "
11814 "exclusive.\n", fcn->name);
11815 errors++;
11816 }
11817 }
11818
11819
Thierry Fournier59f11be2020-11-29 00:37:41 +010011820 if (errors > 0)
11821 return 0;
11822
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011823 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011824 * -1 in order to have probably a segfault if someone use it
11825 */
11826 hlua_state_id = -1;
11827
11828 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011829}
11830
Willy Tarreau32f61e22015-03-18 17:54:59 +010011831/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11832 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11833 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011834 * allocation. <nsize> is the requested new size. A new allocation is
11835 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011836 * zero. This one verifies that the limits are respected but is optimized
11837 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011838 *
11839 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
11840 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
11841 * that and will simply allocate zero as if it were the result of malloc(0),
11842 * so mapping this onto realloc() will lead to memory leaks on non-glibc
11843 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011844 */
11845static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11846{
11847 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011848 size_t limit, old, new;
11849
11850 /* a limit of ~0 means unlimited and boot complete, so there's no need
11851 * for accounting anymore.
11852 */
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011853 if (likely(~zone->limit == 0)) {
11854 if (!nsize)
11855 ha_free(&ptr);
11856 else
11857 ptr = realloc(ptr, nsize);
11858 return ptr;
11859 }
Willy Tarreau32f61e22015-03-18 17:54:59 +010011860
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011861 if (!ptr)
11862 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011863
Willy Tarreaucdb53462020-12-02 12:12:00 +010011864 /* enforce strict limits across all threads */
11865 limit = zone->limit;
11866 old = _HA_ATOMIC_LOAD(&zone->allocated);
11867 do {
11868 new = old + nsize - osize;
11869 if (unlikely(nsize && limit && new > limit))
11870 return NULL;
11871 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011872
Willy Tarreaua5efdff2021-10-22 16:00:02 +020011873 if (!nsize)
11874 ha_free(&ptr);
11875 else
11876 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011877
11878 if (unlikely(!ptr && nsize)) // failed
11879 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11880
11881 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011882 return ptr;
11883}
11884
Thierry Fournierecb83c22020-11-28 15:49:44 +010011885/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011886 * We are in the initialisation process of HAProxy, this abort() is
11887 * tolerated.
11888 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011889lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011890{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011891 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011892 int idx;
11893 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011894 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011895 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011896 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011897 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011898 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011899 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011900
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011901 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011902 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011903
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011904 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011905 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011906 *context = NULL;
11907
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011908 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011909 * the Lua function can fail with an abort. We are in the initialisation
11910 * process of HAProxy, this abort() is tolerated.
11911 */
11912
Thierry Fournier3c539322020-11-28 16:05:05 +010011913 /* Call post initialisation function in safe environment. */
11914 if (setjmp(safe_ljmp_env) != 0) {
11915 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011916 if (lua_type(L, -1) == LUA_TSTRING)
11917 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011918 else
11919 error_msg = "critical error";
11920 fprintf(stderr, "Lua init: %s.\n", error_msg);
11921 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011922 } else {
11923 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011924 }
11925
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011926 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011927 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011928#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11929#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11930#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011931 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011932#endif
11933#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011934 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011935#endif
11936#undef HLUA_PREPEND_PATH_TOSTRING
11937#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011938
Thierry Fournier59f11be2020-11-29 00:37:41 +010011939 /* Apply configured prepend path */
11940 list_for_each_entry(pp, &prepend_path_list, l)
11941 hlua_prepend_path(L, pp->type, pp->path);
11942
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011943 /*
11944 *
11945 * Create "core" object.
11946 *
11947 */
11948
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011949 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011950 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011951
Thierry Fournierecb83c22020-11-28 15:49:44 +010011952 /* set the thread id */
11953 hlua_class_const_int(L, "thread", thread_num);
11954
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011955 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011956 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011957 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011958
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011959 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011960 hlua_class_function(L, "register_init", hlua_register_init);
11961 hlua_class_function(L, "register_task", hlua_register_task);
11962 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11963 hlua_class_function(L, "register_converters", hlua_register_converters);
11964 hlua_class_function(L, "register_action", hlua_register_action);
11965 hlua_class_function(L, "register_service", hlua_register_service);
11966 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011967 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011968 hlua_class_function(L, "yield", hlua_yield);
11969 hlua_class_function(L, "set_nice", hlua_set_nice);
11970 hlua_class_function(L, "sleep", hlua_sleep);
11971 hlua_class_function(L, "msleep", hlua_msleep);
11972 hlua_class_function(L, "add_acl", hlua_add_acl);
11973 hlua_class_function(L, "del_acl", hlua_del_acl);
11974 hlua_class_function(L, "set_map", hlua_set_map);
11975 hlua_class_function(L, "del_map", hlua_del_map);
11976 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011977 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011978 hlua_class_function(L, "log", hlua_log);
11979 hlua_class_function(L, "Debug", hlua_log_debug);
11980 hlua_class_function(L, "Info", hlua_log_info);
11981 hlua_class_function(L, "Warning", hlua_log_warning);
11982 hlua_class_function(L, "Alert", hlua_log_alert);
11983 hlua_class_function(L, "done", hlua_done);
11984 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011985
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011986 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011987
11988 /*
11989 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011990 * Create "act" object.
11991 *
11992 */
11993
11994 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011995 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011996
11997 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011998 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11999 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
12000 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
12001 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
12002 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
12003 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
12004 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
12005 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012006
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012007 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010012008
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012009 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010012010
12011 /*
12012 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020012013 * Create "Filter" object.
12014 *
12015 */
12016
12017 /* This table entry is the object "filter" base. */
12018 lua_newtable(L);
12019
12020 /* push flags and constants */
12021 hlua_class_const_int(L, "CONTINUE", 1);
12022 hlua_class_const_int(L, "WAIT", 0);
12023 hlua_class_const_int(L, "ERROR", -1);
12024
12025 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
12026
Christopher Fauletc404f112020-02-26 15:03:09 +010012027 hlua_class_function(L, "wake_time", hlua_set_wake_time);
12028 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
12029 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
12030
Christopher Faulet69c581a2021-05-31 08:54:04 +020012031 lua_setglobal(L, "filter");
12032
12033 /*
12034 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012035 * Register class Map
12036 *
12037 */
12038
12039 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012040 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012041
12042 /* register pattern types. */
12043 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012044 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012045 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012046 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012047 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010012048 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012049
12050 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012051 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012052
12053 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012054 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012055
Ilya Shipitsind4259502020-04-08 01:07:56 +050012056 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012057 lua_pushstring(L, "__index");
12058 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012059
12060 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012061 hlua_class_function(L, "lookup", hlua_map_lookup);
12062 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012063
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012064 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012065
Thierry Fournier45e78d72016-02-19 18:34:46 +010012066 /* Register previous table in the registry with reference and named entry.
12067 * The function hlua_register_metatable() pops the stack, so we
12068 * previously create a copy of the table.
12069 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012070 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
12071 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012072
12073 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012074 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012075
12076 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012077 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020012078
12079 /*
12080 *
William Lallemand30fcca12022-03-30 12:03:12 +020012081 * Register "CertCache" class
12082 *
12083 */
12084
12085 /* Create and fill the metatable. */
12086 lua_newtable(L);
12087 /* Register */
12088 hlua_class_function(L, "set", hlua_ckch_set);
12089 lua_setglobal(L, CLASS_CERTCACHE); /* Create global object called Regex */
12090
12091 /*
12092 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012093 * Register class Channel
12094 *
12095 */
12096
12097 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012098 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012099
Ilya Shipitsind4259502020-04-08 01:07:56 +050012100 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012101 lua_pushstring(L, "__index");
12102 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012103
12104 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012105 hlua_class_function(L, "data", hlua_channel_get_data);
12106 hlua_class_function(L, "line", hlua_channel_get_line);
12107 hlua_class_function(L, "set", hlua_channel_set_data);
12108 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012109 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012110 hlua_class_function(L, "prepend", hlua_channel_prepend);
12111 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012112 hlua_class_function(L, "send", hlua_channel_send);
12113 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012114 hlua_class_function(L, "input", hlua_channel_get_in_len);
12115 hlua_class_function(L, "output", hlua_channel_get_out_len);
12116 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012117 hlua_class_function(L, "is_full", hlua_channel_is_full);
12118 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012119
Christopher Faulet6a79fc12021-08-06 16:02:36 +020012120 /* Deprecated API */
12121 hlua_class_function(L, "get", hlua_channel_get);
12122 hlua_class_function(L, "dup", hlua_channel_dup);
12123 hlua_class_function(L, "getline", hlua_channel_getline);
12124 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
12125 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
12126
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012127 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012128
12129 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012130 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010012131
12132 /*
12133 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012134 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012135 *
12136 */
12137
12138 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012139 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012140
Ilya Shipitsind4259502020-04-08 01:07:56 +050012141 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012142 lua_pushstring(L, "__index");
12143 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012144
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012145 /* Browse existing fetches and create the associated
12146 * object method.
12147 */
12148 sf = NULL;
12149 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012150 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12151 * by an underscore.
12152 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012153 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012154 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012155 if (*p == '.' || *p == '-' || *p == '+')
12156 *p = '_';
12157
12158 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012159 lua_pushstring(L, trash.area);
12160 lua_pushlightuserdata(L, sf);
12161 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
12162 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010012163 }
12164
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012165 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012166
12167 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012168 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012169
12170 /*
12171 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012172 * Register class Converters
12173 *
12174 */
12175
12176 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012177 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012178
12179 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012180 lua_pushstring(L, "__index");
12181 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012182
12183 /* Browse existing converters and create the associated
12184 * object method.
12185 */
12186 sc = NULL;
12187 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012188 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
12189 * by an underscore.
12190 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020012191 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020012192 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012193 if (*p == '.' || *p == '-' || *p == '+')
12194 *p = '_';
12195
12196 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012197 lua_pushstring(L, trash.area);
12198 lua_pushlightuserdata(L, sc);
12199 lua_pushcclosure(L, hlua_run_sample_conv, 1);
12200 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012201 }
12202
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012203 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012204
12205 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012206 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010012207
12208 /*
12209 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012210 * Register class HTTP
12211 *
12212 */
12213
12214 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012215 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012216
Ilya Shipitsind4259502020-04-08 01:07:56 +050012217 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012218 lua_pushstring(L, "__index");
12219 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012220
12221 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012222 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
12223 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
12224 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
12225 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
12226 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
12227 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
12228 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
12229 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
12230 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
12231 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012232
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012233 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
12234 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
12235 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
12236 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
12237 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
12238 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
12239 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012240
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012241 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012242
12243 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012244 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012245
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012246 /*
12247 *
12248 * Register class HTTPMessage
12249 *
12250 */
12251
12252 /* Create and fill the metatable. */
12253 lua_newtable(L);
12254
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050012255 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010012256 lua_pushstring(L, "__index");
12257 lua_newtable(L);
12258
12259 /* Register Lua functions. */
12260 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
12261 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
12262 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
12263 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
12264 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
12265 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
12266 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
12267 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
12268 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
12269 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
12270 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
12271 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
12272 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
12273 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
12274 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
12275 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
12276 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
12277 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
12278
12279 hlua_class_function(L, "body", hlua_http_msg_get_body);
12280 hlua_class_function(L, "set", hlua_http_msg_set_data);
12281 hlua_class_function(L, "remove", hlua_http_msg_del_data);
12282 hlua_class_function(L, "append", hlua_http_msg_append);
12283 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
12284 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
12285 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
12286 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
12287
12288 hlua_class_function(L, "send", hlua_http_msg_send);
12289 hlua_class_function(L, "forward", hlua_http_msg_forward);
12290
12291 lua_rawset(L, -3);
12292
12293 /* Register previous table in the registry with reference and named entry. */
12294 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020012295
12296 /*
12297 *
12298 * Register class HTTPClient
12299 *
12300 */
12301
12302 /* Create and fill the metatable. */
12303 lua_newtable(L);
12304 lua_pushstring(L, "__index");
12305 lua_newtable(L);
12306 hlua_class_function(L, "get", hlua_httpclient_get);
William Lallemanddc2cc902021-10-26 11:43:26 +020012307 hlua_class_function(L, "head", hlua_httpclient_head);
12308 hlua_class_function(L, "put", hlua_httpclient_put);
12309 hlua_class_function(L, "post", hlua_httpclient_post);
12310 hlua_class_function(L, "delete", hlua_httpclient_delete);
William Lallemand3956c4e2021-09-21 16:25:15 +020012311 lua_settable(L, -3); /* Sets the __index entry. */
William Lallemandf77f1de2021-09-28 19:10:38 +020012312 /* Register the garbage collector entry. */
12313 lua_pushstring(L, "__gc");
12314 lua_pushcclosure(L, hlua_httpclient_gc, 0);
12315 lua_settable(L, -3); /* Push the last 2 entries in the table at index -3 */
12316
William Lallemand3956c4e2021-09-21 16:25:15 +020012317
12318
12319 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010012320 /*
12321 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012322 * Register class AppletTCP
12323 *
12324 */
12325
12326 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012327 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012328
Ilya Shipitsind4259502020-04-08 01:07:56 +050012329 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012330 lua_pushstring(L, "__index");
12331 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012332
12333 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012334 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
12335 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
12336 hlua_class_function(L, "send", hlua_applet_tcp_send);
12337 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
12338 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
12339 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
12340 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
12341 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012342
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012343 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012344
12345 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012346 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020012347
12348 /*
12349 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012350 * Register class AppletHTTP
12351 *
12352 */
12353
12354 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012355 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012356
Ilya Shipitsind4259502020-04-08 01:07:56 +050012357 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012358 lua_pushstring(L, "__index");
12359 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012360
12361 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012362 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
12363 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
12364 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
12365 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
12366 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
12367 hlua_class_function(L, "getline", hlua_applet_http_getline);
12368 hlua_class_function(L, "receive", hlua_applet_http_recv);
12369 hlua_class_function(L, "send", hlua_applet_http_send);
12370 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
12371 hlua_class_function(L, "set_status", hlua_applet_http_status);
12372 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012373
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012374 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012375
12376 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012377 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020012378
12379 /*
12380 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012381 * Register class TXN
12382 *
12383 */
12384
12385 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012386 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012387
Ilya Shipitsind4259502020-04-08 01:07:56 +050012388 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012389 lua_pushstring(L, "__index");
12390 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010012391
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012392 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012393 hlua_class_function(L, "set_priv", hlua_set_priv);
12394 hlua_class_function(L, "get_priv", hlua_get_priv);
12395 hlua_class_function(L, "set_var", hlua_set_var);
12396 hlua_class_function(L, "unset_var", hlua_unset_var);
12397 hlua_class_function(L, "get_var", hlua_get_var);
12398 hlua_class_function(L, "done", hlua_txn_done);
12399 hlua_class_function(L, "reply", hlua_txn_reply_new);
12400 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
12401 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
12402 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
12403 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
12404 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
12405 hlua_class_function(L, "deflog", hlua_txn_deflog);
12406 hlua_class_function(L, "log", hlua_txn_log);
12407 hlua_class_function(L, "Debug", hlua_txn_log_debug);
12408 hlua_class_function(L, "Info", hlua_txn_log_info);
12409 hlua_class_function(L, "Warning", hlua_txn_log_warning);
12410 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010012411
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012412 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010012413
12414 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012415 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012416
12417 /*
12418 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010012419 * Register class reply
12420 *
12421 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012422 lua_newtable(L);
12423 lua_pushstring(L, "__index");
12424 lua_newtable(L);
12425 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
12426 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
12427 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
12428 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
12429 lua_settable(L, -3); /* Sets the __index entry. */
12430 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010012431
12432
12433 /*
12434 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012435 * Register class Socket
12436 *
12437 */
12438
12439 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012440 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012441
Ilya Shipitsind4259502020-04-08 01:07:56 +050012442 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012443 lua_pushstring(L, "__index");
12444 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012445
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012446#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012447 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010012448#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012449 hlua_class_function(L, "connect", hlua_socket_connect);
12450 hlua_class_function(L, "send", hlua_socket_send);
12451 hlua_class_function(L, "receive", hlua_socket_receive);
12452 hlua_class_function(L, "close", hlua_socket_close);
12453 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
12454 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
12455 hlua_class_function(L, "setoption", hlua_socket_setoption);
12456 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012457
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012458 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012459
12460 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012461 lua_pushstring(L, "__gc");
12462 lua_pushcclosure(L, hlua_socket_gc, 0);
12463 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012464
12465 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010012466 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012467
Thierry Fournieraafc7772020-12-04 11:47:47 +010012468 lua_atpanic(L, hlua_panic_safe);
12469
12470 return L;
12471}
12472
12473void hlua_init(void) {
12474 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012475 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010012476#ifdef USE_OPENSSL
12477 struct srv_kw *kw;
12478 int tmp_error;
12479 char *error;
12480 char *args[] = { /* SSL client configuration. */
12481 "ssl",
12482 "verify",
12483 "none",
12484 NULL
12485 };
12486#endif
12487
12488 /* Init post init function list head */
12489 for (i = 0; i < MAX_THREADS + 1; i++)
12490 LIST_INIT(&hlua_init_functions[i]);
12491
12492 /* Init state for common/shared lua parts */
12493 hlua_state_id = 0;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012494 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012495 hlua_states[0] = hlua_init_state(0);
12496
12497 /* Init state 1 for thread 0. We have at least one thread. */
12498 hlua_state_id = 1;
Willy Tarreau43ab05b2021-09-28 09:43:11 +020012499 ha_set_thread(NULL);
Thierry Fournieraafc7772020-12-04 11:47:47 +010012500 hlua_states[1] = hlua_init_state(1);
12501
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012502 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020012503 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012504 if (!socket_proxy) {
12505 fprintf(stderr, "Lua init: %s\n", errmsg);
12506 exit(1);
12507 }
12508 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012509
12510 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012511 socket_tcp = new_server(socket_proxy);
12512 if (!socket_tcp) {
12513 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
12514 exit(1);
12515 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012516
12517#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012518 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012519 socket_ssl = new_server(socket_proxy);
12520 if (!socket_ssl) {
12521 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
12522 exit(1);
12523 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012524
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012525 socket_ssl->use_ssl = 1;
12526 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012527
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012528 for (i = 0; args[i] != NULL; i++) {
12529 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012530 /*
12531 *
12532 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080012533 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012534 * features like client certificates and ssl_verify.
12535 *
12536 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010012537 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012538 if (tmp_error != 0) {
12539 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
12540 abort(); /* This must be never arrives because the command line
12541 not editable by the user. */
12542 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000012543 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012544 }
12545 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010012546#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010012547
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010012548}
Willy Tarreaubb57d942016-12-21 19:04:56 +010012549
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012550static void hlua_deinit()
12551{
Willy Tarreau186f3762020-12-04 11:48:12 +010012552 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020012553 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
12554
12555 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
12556 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010012557
12558 for (thr = 0; thr < MAX_THREADS+1; thr++) {
12559 if (hlua_states[thr])
12560 lua_close(hlua_states[thr]);
12561 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012562
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012563 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010012564
Willy Tarreau0f143af2021-03-05 10:41:48 +010012565#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020012566 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010012567#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010012568
12569 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020012570}
12571
12572REGISTER_POST_DEINIT(hlua_deinit);
12573
Willy Tarreau80713382018-11-26 10:19:54 +010012574static void hlua_register_build_options(void)
12575{
Willy Tarreaubb57d942016-12-21 19:04:56 +010012576 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010012577
Willy Tarreaubb57d942016-12-21 19:04:56 +010012578 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
12579 hap_register_build_opts(ptr, 1);
12580}
Willy Tarreau80713382018-11-26 10:19:54 +010012581
12582INITCALL0(STG_REGISTER, hlua_register_build_options);