blob: 37f1afa38b57cb9abb9bf19c7896ffe5edd50b10 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020035#include <haproxy/connection.h>
Christopher Faulet69c581a2021-05-31 08:54:04 +020036#include <haproxy/filters.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020037#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020038#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020039#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020040#include <haproxy/http_ana.h>
William Lallemand3956c4e2021-09-21 16:25:15 +020041#include <haproxy/http_client.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020042#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020043#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020044#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020045#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020046#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020047#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020048#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020049#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020050#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020051#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020052#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010053#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020054#include <haproxy/session.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020055#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020056#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020057#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020058#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020059#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020060#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020061#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020062#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020063#include <haproxy/xref.h>
64
Thierry FOURNIER380d0932015-01-23 14:27:52 +010065
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010066/* Lua uses longjmp to perform yield or throwing errors. This
67 * macro is used only for identifying the function that can
68 * not return because a longjmp is executed.
69 * __LJMP marks a prototype of hlua file that can use longjmp.
70 * WILL_LJMP() marks an lua function that will use longjmp.
71 * MAY_LJMP() marks an lua function that may use longjmp.
72 */
73#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020074#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010075#define MAY_LJMP(func) func
76
Thierry FOURNIERbabae282015-09-17 11:36:37 +020077/* This couple of function executes securely some Lua calls outside of
78 * the lua runtime environment. Each Lua call can return a longjmp
79 * if it encounter a memory error.
80 *
81 * Lua documentation extract:
82 *
83 * If an error happens outside any protected environment, Lua calls
84 * a panic function (see lua_atpanic) and then calls abort, thus
85 * exiting the host application. Your panic function can avoid this
86 * exit by never returning (e.g., doing a long jump to your own
87 * recovery point outside Lua).
88 *
89 * The panic function runs as if it were a message handler (see
90 * §2.3); in particular, the error message is at the top of the
91 * stack. However, there is no guarantee about stack space. To push
92 * anything on the stack, the panic function must first check the
93 * available space (see §4.2).
94 *
95 * We must check all the Lua entry point. This includes:
96 * - The include/proto/hlua.h exported functions
97 * - the task wrapper function
98 * - The action wrapper function
99 * - The converters wrapper function
100 * - The sample-fetch wrapper functions
101 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500102 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800103 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200104 *
105 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
106 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
107 * because they must be exists in the program stack when the longjmp
108 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200109 *
110 * Note that the Lua processing is not really thread safe. It provides
111 * heavy system which consists to add our own lock function in the Lua
112 * code and recompile the library. This system will probably not accepted
113 * by maintainers of various distribs.
114 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500115 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200116 * quick looking on the Lua sources displays a lua_lock() a the start
117 * of function and a lua_unlock() at the end of the function. So I
118 * conclude that the Lua thread safe mode just perform a mutex around
119 * all execution. So I prefer to do this in the HAProxy code, it will be
120 * easier for distro maintainers.
121 *
122 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
123 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
124 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200125 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100126__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200127THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200128static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau6a510902021-07-14 19:41:25 +0200129static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200130
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100131/* This is the chained list of struct hlua_function referenced
132 * for haproxy action, sample-fetches, converters, cli and
133 * applet bindings. It is used for a post-initialisation control.
134 */
135static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
136
Thierry Fournierc7492592020-11-28 23:57:24 +0100137/* This variable is used only during initialization to identify the Lua state
138 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
139 * states dedicated to each thread (in this case hlua_state_id==tid+1).
140 */
141static int hlua_state_id;
142
Thierry Fournier59f11be2020-11-29 00:37:41 +0100143/* This is a NULL-terminated list of lua file which are referenced to load per thread */
144static char **per_thread_load = NULL;
145
146lua_State *hlua_init_state(int thread_id);
147
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200148/* This function takes the Lua global lock. Keep this function's visibility
149 * global so that it can appear in stack dumps and performance profiles!
150 */
151void lua_take_global_lock()
152{
153 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
154}
155
156static inline void lua_drop_global_lock()
157{
158 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
159}
160
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100161#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200162 ({ \
163 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100164 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200165 lua_take_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200166 if (setjmp(safe_ljmp_env) != 0) { \
167 lua_atpanic(__L, hlua_panic_safe); \
168 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100169 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200170 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200171 } else { \
172 lua_atpanic(__L, hlua_panic_ljmp); \
173 ret = 1; \
174 } \
175 ret; \
176 })
177
178/* If we are the last function catching Lua errors, we
179 * must reset the panic function.
180 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100181#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200182 do { \
183 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100184 if ((__HLUA)->state_id == 0) \
Willy Tarreau1e7bef12021-08-20 15:47:25 +0200185 lua_drop_global_lock(); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200186 } while(0)
187
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100188#define SET_SAFE_LJMP(__HLUA) \
189 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
190
191#define RESET_SAFE_LJMP(__HLUA) \
192 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
193
194#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100195 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100196
197#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100198 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100199
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200200/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200201#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100202/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200203#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200204/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100205#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100206#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200207
Thierry Fournierafc63e22020-11-28 17:06:51 +0100208/* The main Lua execution context. The 0 index is the
209 * common state shared by all threads.
210 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100211static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100212
Christopher Fauletc404f112020-02-26 15:03:09 +0100213#define HLUA_FLT_CB_FINAL 0x00000001
214#define HLUA_FLT_CB_RETVAL 0x00000002
215#define HLUA_FLT_CB_ARG_CHN 0x00000004
216#define HLUA_FLT_CB_ARG_HTTP_MSG 0x00000008
217
Christopher Faulet9f55a502020-02-25 15:21:02 +0100218#define HLUA_FLT_CTX_FL_PAYLOAD 0x00000001
219
Christopher Faulet69c581a2021-05-31 08:54:04 +0200220struct hlua_reg_filter {
221 char *name;
222 int flt_ref[MAX_THREADS + 1];
223 int fun_ref[MAX_THREADS + 1];
224 struct list l;
225};
226
227struct hlua_flt_config {
228 struct hlua_reg_filter *reg;
229 int ref[MAX_THREADS + 1];
230 char **args;
231};
232
233struct hlua_flt_ctx {
234 int ref; /* ref to the filter lua object */
235 struct hlua *hlua[2]; /* lua runtime context (0: request, 1: response) */
236 unsigned int cur_off[2]; /* current offset (0: request, 1: response) */
237 unsigned int cur_len[2]; /* current forwardable length (0: request, 1: response) */
238 unsigned int flags; /* HLUA_FLT_CTX_FL_* */
239};
240
241DECLARE_STATIC_POOL(pool_head_hlua_flt_ctx, "hlua_flt_ctx", sizeof(struct hlua_flt_ctx));
242
Christopher Faulet9f55a502020-02-25 15:21:02 +0100243static int hlua_filter_from_payload(struct filter *filter);
244
Christopher Faulet69c581a2021-05-31 08:54:04 +0200245/* This is the chained list of struct hlua_flt referenced
246 * for haproxy filters. It is used for a post-initialisation control.
247 */
248static struct list referenced_filters = LIST_HEAD_INIT(referenced_filters);
249
250
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100251/* This is the memory pool containing struct lua for applets
252 * (including cli).
253 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100254DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100255
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100256/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100257static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100258static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100259#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100260static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100261#endif
262
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100263/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100264struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100265
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100266/* The following variables contains the reference of the different
267 * Lua classes. These references are useful for identify metadata
268 * associated with an object.
269 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100270static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100271static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100272static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100273static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100274static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100275static int class_http_ref;
Christopher Fauletdf97ac42020-02-26 16:57:19 +0100276static int class_http_msg_ref;
William Lallemand3956c4e2021-09-21 16:25:15 +0200277static int class_httpclient_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200278static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200279static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200280static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100281static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100282
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100283/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200284 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100285 * short timeout. Lua linked with tasks doesn't have a timeout
286 * because a task may remain alive during all the haproxy execution.
287 */
288static unsigned int hlua_timeout_session = 4000; /* session timeout. */
289static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200290static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100291
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100292/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
293 * it is used for preventing infinite loops.
294 *
295 * I test the scheer with an infinite loop containing one incrementation
296 * and one test. I run this loop between 10 seconds, I raise a ceil of
297 * 710M loops from one interrupt each 9000 instructions, so I fix the value
298 * to one interrupt each 10 000 instructions.
299 *
300 * configured | Number of
301 * instructions | loops executed
302 * between two | in milions
303 * forced yields |
304 * ---------------+---------------
305 * 10 | 160
306 * 500 | 670
307 * 1000 | 680
308 * 5000 | 700
309 * 7000 | 700
310 * 8000 | 700
311 * 9000 | 710 <- ceil
312 * 10000 | 710
313 * 100000 | 710
314 * 1000000 | 710
315 *
316 */
317static unsigned int hlua_nb_instruction = 10000;
318
Willy Tarreaucdb53462020-12-02 12:12:00 +0100319/* Descriptor for the memory allocation state. The limit is pre-initialised to
320 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
321 * is replaced with ~0 during post_init after everything was loaded. This way
322 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
323 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100324 */
325struct hlua_mem_allocator {
326 size_t allocated;
327 size_t limit;
328};
329
Willy Tarreaucdb53462020-12-02 12:12:00 +0100330static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100331
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100332/* These functions converts types between HAProxy internal args or
333 * sample and LUA types. Another function permits to check if the
334 * LUA stack contains arguments according with an required ARG_T
335 * format.
336 */
337static int hlua_arg2lua(lua_State *L, const struct arg *arg);
338static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100339__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100340 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100341static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100342static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100343static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
344
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100345__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200346
Thierry Fournier59f11be2020-11-29 00:37:41 +0100347struct prepend_path {
348 struct list l;
349 char *type;
350 char *path;
351};
352
353static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
354
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200355#define SEND_ERR(__be, __fmt, __args...) \
356 do { \
357 send_log(__be, LOG_ERR, __fmt, ## __args); \
358 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100359 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200360 } while (0)
361
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100362static inline struct hlua_function *new_hlua_function()
363{
364 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100365 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100366
367 fcn = calloc(1, sizeof(*fcn));
368 if (!fcn)
369 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200370 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100371 for (i = 0; i < MAX_THREADS + 1; i++)
372 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100373 return fcn;
374}
375
Christopher Fauletdda44442021-04-12 14:05:43 +0200376static inline void release_hlua_function(struct hlua_function *fcn)
377{
378 if (!fcn)
379 return;
380 if (fcn->name)
381 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200382 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200383 ha_free(&fcn);
384}
385
Thierry Fournierc7492592020-11-28 23:57:24 +0100386/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
387static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
388{
389 if (fcn->function_ref[0] == -1)
390 return tid + 1;
391 return 0;
392}
393
Christopher Faulet69c581a2021-05-31 08:54:04 +0200394/* Create a new registered filter. Only its name is filled */
395static inline struct hlua_reg_filter *new_hlua_reg_filter(const char *name)
396{
397 struct hlua_reg_filter *reg_flt;
398 int i;
399
400 reg_flt = calloc(1, sizeof(*reg_flt));
401 if (!reg_flt)
402 return NULL;
403 reg_flt->name = strdup(name);
404 if (!reg_flt->name) {
405 free(reg_flt);
406 return NULL;
407 }
408 LIST_APPEND(&referenced_filters, &reg_flt->l);
409 for (i = 0; i < MAX_THREADS + 1; i++) {
410 reg_flt->flt_ref[i] = -1;
411 reg_flt->fun_ref[i] = -1;
412 }
413 return reg_flt;
414}
415
416/* Release a registered filter */
417static inline void release_hlua_reg_filter(struct hlua_reg_filter *reg_flt)
418{
419 if (!reg_flt)
420 return;
421 if (reg_flt->name)
422 ha_free(&reg_flt->name);
423 LIST_DELETE(&reg_flt->l);
424 ha_free(&reg_flt);
425}
426
427/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
428static inline int reg_flt_to_stack_id(struct hlua_reg_filter *reg_flt)
429{
430 if (reg_flt->fun_ref[0] == -1)
431 return tid + 1;
432 return 0;
433}
434
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100435/* Used to check an Lua function type in the stack. It creates and
436 * returns a reference of the function. This function throws an
437 * error if the rgument is not a "function".
438 */
439__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
440{
441 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100442 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100443 WILL_LJMP(luaL_argerror(L, argno, msg));
444 }
445 lua_pushvalue(L, argno);
446 return luaL_ref(L, LUA_REGISTRYINDEX);
447}
448
Christopher Fauletba9e21d2020-02-25 10:20:04 +0100449/* Used to check an Lua table type in the stack. It creates and
450 * returns a reference of the table. This function throws an
451 * error if the rgument is not a "table".
452 */
453__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
454{
455 if (!lua_istable(L, argno)) {
456 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
457 WILL_LJMP(luaL_argerror(L, argno, msg));
458 }
459 lua_pushvalue(L, argno);
460 return luaL_ref(L, LUA_REGISTRYINDEX);
461}
462
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200463/* Return the string that is of the top of the stack. */
464const char *hlua_get_top_error_string(lua_State *L)
465{
466 if (lua_gettop(L) < 1)
467 return "unknown error";
468 if (lua_type(L, -1) != LUA_TSTRING)
469 return "unknown error";
470 return lua_tostring(L, -1);
471}
472
Christopher Fauletd09cc512021-03-24 14:48:45 +0100473__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200474{
475 lua_Debug ar;
476 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200477 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200478
479 while (lua_getstack(L, level++, &ar)) {
480
481 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100482 if (b_data(msg))
483 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200484
485 /* Fill fields:
486 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
487 * 'l': fills in the field currentline;
488 * 'n': fills in the field name and namewhat;
489 * 't': fills in the field istailcall;
490 */
491 lua_getinfo(L, "Slnt", &ar);
492
493 /* Append code localisation */
494 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100495 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200496 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100497 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200498
499 /*
500 * Get function name
501 *
502 * if namewhat is no empty, name is defined.
503 * what contains "Lua" for Lua function, "C" for C function,
504 * or "main" for main code.
505 */
506 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100507 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200508
509 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100510 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200511
512 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100513 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200514
515 else /* nothing left... */
516 chunk_appendf(msg, "?");
517
518
519 /* Display tailed call */
520 if (ar.istailcall)
521 chunk_appendf(msg, " ...");
522 }
523
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200524 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200525}
526
527
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100528/* This function check the number of arguments available in the
529 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500530 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100531 */
532__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
533{
534 if (lua_gettop(L) == nb)
535 return;
536 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
537}
538
Mark Lakes22154b42018-01-29 14:38:40 -0800539/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100540 * and the line number where the error is encountered.
541 */
542static int hlua_pusherror(lua_State *L, const char *fmt, ...)
543{
544 va_list argp;
545 va_start(argp, fmt);
546 luaL_where(L, 1);
547 lua_pushvfstring(L, fmt, argp);
548 va_end(argp);
549 lua_concat(L, 2);
550 return 1;
551}
552
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100553/* This functions is used with sample fetch and converters. It
554 * converts the HAProxy configuration argument in a lua stack
555 * values.
556 *
557 * It takes an array of "arg", and each entry of the array is
558 * converted and pushed in the LUA stack.
559 */
560static int hlua_arg2lua(lua_State *L, const struct arg *arg)
561{
562 switch (arg->type) {
563 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100564 case ARGT_TIME:
565 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100566 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100567 break;
568
569 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200570 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100571 break;
572
573 case ARGT_IPV4:
574 case ARGT_IPV6:
575 case ARGT_MSK4:
576 case ARGT_MSK6:
577 case ARGT_FE:
578 case ARGT_BE:
579 case ARGT_TAB:
580 case ARGT_SRV:
581 case ARGT_USR:
582 case ARGT_MAP:
583 default:
584 lua_pushnil(L);
585 break;
586 }
587 return 1;
588}
589
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500590/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100591 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500592 * with sample fetch wrappers. The input arguments are given to the
593 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100594 */
595static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
596{
597 switch (lua_type(L, ud)) {
598
599 case LUA_TNUMBER:
600 case LUA_TBOOLEAN:
601 arg->type = ARGT_SINT;
602 arg->data.sint = lua_tointeger(L, ud);
603 break;
604
605 case LUA_TSTRING:
606 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200607 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200608 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200609 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200610 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100611 break;
612
613 case LUA_TUSERDATA:
614 case LUA_TNIL:
615 case LUA_TTABLE:
616 case LUA_TFUNCTION:
617 case LUA_TTHREAD:
618 case LUA_TLIGHTUSERDATA:
619 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200620 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100621 break;
622 }
623 return 1;
624}
625
626/* the following functions are used to convert a struct sample
627 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500628 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100629 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100630static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100631{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200632 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100633 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100634 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200635 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100636 break;
637
638 case SMP_T_BIN:
639 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200640 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100641 break;
642
643 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200644 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100645 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
646 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
647 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
648 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
649 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
650 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
651 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
652 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
653 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200654 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100655 break;
656 default:
657 lua_pushnil(L);
658 break;
659 }
660 break;
661
662 case SMP_T_IPV4:
663 case SMP_T_IPV6:
664 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200665 if (sample_casts[smp->data.type][SMP_T_STR] &&
666 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200667 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100668 else
669 lua_pushnil(L);
670 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100671 default:
672 lua_pushnil(L);
673 break;
674 }
675 return 1;
676}
677
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100678/* the following functions are used to convert a struct sample
679 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500680 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100681 */
682static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
683{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200684 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100685
686 case SMP_T_BIN:
687 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200688 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100689 break;
690
691 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200692 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100693 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
694 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
695 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
696 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
697 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
698 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
699 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
700 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
701 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200702 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100703 break;
704 default:
705 lua_pushstring(L, "");
706 break;
707 }
708 break;
709
710 case SMP_T_SINT:
711 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100712 case SMP_T_IPV4:
713 case SMP_T_IPV6:
714 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200715 if (sample_casts[smp->data.type][SMP_T_STR] &&
716 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200717 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100718 else
719 lua_pushstring(L, "");
720 break;
721 default:
722 lua_pushstring(L, "");
723 break;
724 }
725 return 1;
726}
727
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100728/* the following functions are used to convert an Lua type in a
729 * struct sample. This is useful to provide data from a converter
730 * to the LUA code.
731 */
732static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
733{
734 switch (lua_type(L, ud)) {
735
736 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200737 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200738 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100739 break;
740
741
742 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200743 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200744 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100745 break;
746
747 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200748 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100749 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200750 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200751 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200752 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200753 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100754 break;
755
756 case LUA_TUSERDATA:
757 case LUA_TNIL:
758 case LUA_TTABLE:
759 case LUA_TFUNCTION:
760 case LUA_TTHREAD:
761 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200762 case LUA_TNONE:
763 default:
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 = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100766 break;
767 }
768 return 1;
769}
770
Ilya Shipitsind4259502020-04-08 01:07:56 +0500771/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800772 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100773 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100774 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500775 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Willy Tarreauee0d7272021-07-16 10:26:56 +0200776 * entries and that there is at least one stop at the last position.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100777 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100778__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100779 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780{
781 int min_arg;
Willy Tarreauee0d7272021-07-16 10:26:56 +0200782 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100783 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200784 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200785 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200786 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200787 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100788
789 idx = 0;
790 min_arg = ARGM(mask);
791 mask >>= ARGM_BITS;
792
793 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200794 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100795
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100796 /* Check for mandatory arguments. */
797 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100798 if (idx < min_arg) {
799
800 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200801 if (idx > 0) {
802 msg = "Mandatory argument expected";
803 goto error;
804 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100805
806 /* If first argument have a certain type, some default values
807 * may be used. See the function smp_resolve_args().
808 */
809 switch (mask & ARGT_MASK) {
810
811 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200812 if (!(p->cap & PR_CAP_FE)) {
813 msg = "Mandatory argument expected";
814 goto error;
815 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100816 argp[idx].data.prx = p;
817 argp[idx].type = ARGT_FE;
818 argp[idx+1].type = ARGT_STOP;
819 break;
820
821 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200822 if (!(p->cap & PR_CAP_BE)) {
823 msg = "Mandatory argument expected";
824 goto error;
825 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100826 argp[idx].data.prx = p;
827 argp[idx].type = ARGT_BE;
828 argp[idx+1].type = ARGT_STOP;
829 break;
830
831 case ARGT_TAB:
832 argp[idx].data.prx = p;
833 argp[idx].type = ARGT_TAB;
834 argp[idx+1].type = ARGT_STOP;
835 break;
836
837 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200838 msg = "Mandatory argument expected";
839 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100840 break;
841 }
842 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200843 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100844 }
845
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500846 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100847 if ((mask & ARGT_MASK) == ARGT_STOP &&
848 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200849 msg = "Last argument expected";
850 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100851 }
852
853 if ((mask & ARGT_MASK) == ARGT_STOP &&
854 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200855 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100856 }
857
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200858 /* Convert some argument types. All string in argp[] are for not
859 * duplicated yet.
860 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100861 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100862 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200863 if (argp[idx].type != ARGT_SINT) {
864 msg = "integer expected";
865 goto error;
866 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100867 argp[idx].type = ARGT_SINT;
868 break;
869
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100870 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200871 if (argp[idx].type != ARGT_SINT) {
872 msg = "integer expected";
873 goto error;
874 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200875 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100876 break;
877
878 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200879 if (argp[idx].type != ARGT_SINT) {
880 msg = "integer expected";
881 goto error;
882 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200883 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100884 break;
885
886 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200887 if (argp[idx].type != ARGT_STR) {
888 msg = "string expected";
889 goto error;
890 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200891 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200892 if (!argp[idx].data.prx) {
893 msg = "frontend doesn't exist";
894 goto error;
895 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100896 argp[idx].type = ARGT_FE;
897 break;
898
899 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200900 if (argp[idx].type != ARGT_STR) {
901 msg = "string expected";
902 goto error;
903 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200904 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200905 if (!argp[idx].data.prx) {
906 msg = "backend doesn't exist";
907 goto error;
908 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100909 argp[idx].type = ARGT_BE;
910 break;
911
912 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200913 if (argp[idx].type != ARGT_STR) {
914 msg = "string expected";
915 goto error;
916 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200917 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200918 if (!argp[idx].data.t) {
919 msg = "table doesn't exist";
920 goto error;
921 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100922 argp[idx].type = ARGT_TAB;
923 break;
924
925 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200926 if (argp[idx].type != ARGT_STR) {
927 msg = "string expected";
928 goto error;
929 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200930 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100931 if (sname) {
932 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200933 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200934 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200935 if (!px) {
936 msg = "backend doesn't exist";
937 goto error;
938 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100939 }
940 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200941 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100942 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100943 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100944 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200945 if (!argp[idx].data.srv) {
946 msg = "server doesn't exist";
947 goto error;
948 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100949 argp[idx].type = ARGT_SRV;
950 break;
951
952 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200953 if (argp[idx].type != ARGT_STR) {
954 msg = "string expected";
955 goto error;
956 }
957 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
958 msg = "invalid IPv4 address";
959 goto error;
960 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100961 argp[idx].type = ARGT_IPV4;
962 break;
963
964 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200965 if (argp[idx].type == ARGT_SINT)
966 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
967 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200968 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
969 msg = "invalid IPv4 mask";
970 goto error;
971 }
972 }
973 else {
974 msg = "integer or string expected";
975 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200976 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100977 argp[idx].type = ARGT_MSK4;
978 break;
979
980 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200981 if (argp[idx].type != ARGT_STR) {
982 msg = "string expected";
983 goto error;
984 }
985 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
986 msg = "invalid IPv6 address";
987 goto error;
988 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100989 argp[idx].type = ARGT_IPV6;
990 break;
991
992 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200993 if (argp[idx].type == ARGT_SINT)
994 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
995 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200996 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
997 msg = "invalid IPv6 mask";
998 goto error;
999 }
1000 }
1001 else {
1002 msg = "integer or string expected";
1003 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001004 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001005 argp[idx].type = ARGT_MSK6;
1006 break;
1007
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001008 case ARGT_REG:
1009 if (argp[idx].type != ARGT_STR) {
1010 msg = "string expected";
1011 goto error;
1012 }
1013 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1014 if (!reg) {
1015 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
1016 argp[idx].data.str.area, err);
1017 free(err);
1018 goto error;
1019 }
1020 argp[idx].type = ARGT_REG;
1021 argp[idx].data.reg = reg;
1022 break;
1023
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001024 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001025 if (argp[idx].type != ARGT_STR) {
1026 msg = "string expected";
1027 goto error;
1028 }
1029 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001030 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001031 ul = p->uri_auth->userlist;
1032 else
1033 ul = auth_find_userlist(argp[idx].data.str.area);
1034
1035 if (!ul) {
1036 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
1037 goto error;
1038 }
1039 argp[idx].type = ARGT_USR;
1040 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001041 break;
1042
1043 case ARGT_STR:
1044 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1045 msg = "unable to duplicate string arg";
1046 goto error;
1047 }
1048 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001049 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001050
Christopher Fauletd25d9262020-08-06 11:04:46 +02001051 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001052 msg = "type not yet supported";
1053 goto error;
1054 break;
1055
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001056 }
1057
1058 /* Check for type of argument. */
1059 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001060 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
1061 arg_type_names[(mask & ARGT_MASK)],
1062 arg_type_names[argp[idx].type & ARGT_MASK]);
1063 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001064 }
1065
1066 /* Next argument. */
1067 mask >>= ARGT_BITS;
1068 idx++;
1069 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001070 return 0;
1071
1072 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02001073 free_args(argp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001074 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1075 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001076}
1077
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001078/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001079 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001080 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001081 *
1082 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001083 * - hlua_sethlua : create the association between hlua context and lua_state.
1084 */
1085static inline struct hlua *hlua_gethlua(lua_State *L)
1086{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001087 struct hlua **hlua = lua_getextraspace(L);
1088 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001089}
1090static inline void hlua_sethlua(struct hlua *hlua)
1091{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001092 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1093 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001094}
1095
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001096/* This function is used to send logs. It try to send on screen (stderr)
1097 * and on the default syslog server.
1098 */
1099static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1100{
1101 struct tm tm;
1102 char *p;
1103
1104 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001105 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001106 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001107 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001108 /* Break the message if exceed the buffer size. */
1109 *(p-4) = ' ';
1110 *(p-3) = '.';
1111 *(p-2) = '.';
1112 *(p-1) = '.';
1113 break;
1114 }
Willy Tarreau90807112020-02-25 08:16:33 +01001115 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001116 *p = *msg;
1117 else
1118 *p = '.';
1119 }
1120 *p = '\0';
1121
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001122 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001123 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001124 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1125 return;
1126
Willy Tarreaua678b432015-08-28 10:14:59 +02001127 get_localtime(date.tv_sec, &tm);
1128 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001129 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001130 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001131 fflush(stderr);
1132 }
1133}
1134
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001135/* This function just ensure that the yield will be always
1136 * returned with a timeout and permit to set some flags
1137 */
1138__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001139 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001140{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001141 struct hlua *hlua;
1142
1143 /* Get hlua struct, or NULL if we execute from main lua state */
1144 hlua = hlua_gethlua(L);
1145 if (!hlua) {
1146 return;
1147 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001148
1149 /* Set the wake timeout. If timeout is required, we set
1150 * the expiration time.
1151 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001152 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001153
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001154 hlua->flags |= flags;
1155
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001156 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001157 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001158}
1159
Willy Tarreau87b09662015-04-03 00:22:06 +02001160/* This function initialises the Lua environment stored in the stream.
1161 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001162 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001163 *
1164 * This function is particular. it initialises a new Lua thread. If the
1165 * initialisation fails (example: out of memory error), the lua function
1166 * throws an error (longjmp).
1167 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001168 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001169 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001170 * threads appear, the safe environment set a lock to ensure only one
1171 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001172 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001173 *
1174 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001175 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001176 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001177 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001178 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001179 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001180 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001181 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001182int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001183{
1184 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001185 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001186 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001187 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001188 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001189 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001190 if (!already_safe) {
1191 if (!SET_SAFE_LJMP_PARENT(lua)) {
1192 lua->Tref = LUA_REFNIL;
1193 return 0;
1194 }
1195 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001196 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001197 if (!lua->T) {
1198 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001199 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001200 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001201 return 0;
1202 }
1203 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001204 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001205 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001206 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001207 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001208 return 1;
1209}
1210
Willy Tarreau87b09662015-04-03 00:22:06 +02001211/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001212 * is destroyed. The destroy also the memory context. The struct "lua"
1213 * is not freed.
1214 */
1215void hlua_ctx_destroy(struct hlua *lua)
1216{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001217 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001218 return;
1219
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001220 if (!lua->T)
1221 goto end;
1222
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001223 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001224 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001225
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001226 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001227 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001228 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001229 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001230
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001231 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001232 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001233 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001234 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001235 /* Forces a garbage collecting process. If the Lua program is finished
1236 * without error, we run the GC on the thread pointer. Its freed all
1237 * the unused memory.
1238 * If the thread is finnish with an error or is currently yielded,
1239 * it seems that the GC applied on the thread doesn't clean anything,
1240 * so e run the GC on the main thread.
1241 * NOTE: maybe this action locks all the Lua threads untiml the en of
1242 * the garbage collection.
1243 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001244 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001245 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001246 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001247 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001248 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001249 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001250
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001251 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001252
1253end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001254 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001255}
1256
1257/* This function is used to restore the Lua context when a coroutine
1258 * fails. This function copy the common memory between old coroutine
1259 * and the new coroutine. The old coroutine is destroyed, and its
1260 * replaced by the new coroutine.
1261 * If the flag "keep_msg" is set, the last entry of the old is assumed
1262 * as string error message and it is copied in the new stack.
1263 */
1264static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1265{
1266 lua_State *T;
1267 int new_ref;
1268
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001269 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001270 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001271 if (!T)
1272 return 0;
1273
1274 /* Copy last error message. */
1275 if (keep_msg)
1276 lua_xmove(lua->T, T, 1);
1277
1278 /* Copy data between the coroutines. */
1279 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1280 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001281 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001282
1283 /* Destroy old data. */
1284 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1285
1286 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001287 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001288
1289 /* Fill the struct with the new coroutine values. */
1290 lua->Mref = new_ref;
1291 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001292 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001293
1294 /* Set context. */
1295 hlua_sethlua(lua);
1296
1297 return 1;
1298}
1299
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001300void hlua_hook(lua_State *L, lua_Debug *ar)
1301{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001302 struct hlua *hlua;
1303
1304 /* Get hlua struct, or NULL if we execute from main lua state */
1305 hlua = hlua_gethlua(L);
1306 if (!hlua)
1307 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001308
1309 /* Lua cannot yield when its returning from a function,
1310 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001311 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001312 */
1313 if (lua_gethookmask(L) & LUA_MASKRET) {
1314 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1315 return;
1316 }
1317
1318 /* restore the interrupt condition. */
1319 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1320
1321 /* If we interrupt the Lua processing in yieldable state, we yield.
1322 * If the state is not yieldable, trying yield causes an error.
1323 */
1324 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001325 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001326
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001327 /* If we cannot yield, update the clock and check the timeout. */
1328 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001329 hlua->run_time += now_ms - hlua->start_time;
1330 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001331 lua_pushfstring(L, "execution timeout");
1332 WILL_LJMP(lua_error(L));
1333 }
1334
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001335 /* Update the start time. */
1336 hlua->start_time = now_ms;
1337
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001338 /* Try to interrupt the process at the end of the current
1339 * unyieldable function.
1340 */
1341 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001342}
1343
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001344/* This function start or resumes the Lua stack execution. If the flag
1345 * "yield_allowed" if no set and the LUA stack execution returns a yield
1346 * The function return an error.
1347 *
1348 * The function can returns 4 values:
1349 * - HLUA_E_OK : The execution is terminated without any errors.
1350 * - HLUA_E_AGAIN : The execution must continue at the next associated
1351 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001352 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001353 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001354 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001355 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001356 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001357 * LUA code.
1358 */
1359static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1360{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001361#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1362 int nres;
1363#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001364 int ret;
1365 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001366 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001367
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001368 /* Initialise run time counter. */
1369 if (!HLUA_IS_RUNNING(lua))
1370 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001371
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001372 /* Lock the whole Lua execution. This lock must be before the
1373 * label "resume_execution".
1374 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001375 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001376 lua_take_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001377
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001378resume_execution:
1379
1380 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1381 * instructions. it is used for preventing infinite loops.
1382 */
1383 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1384
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001385 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001386 HLUA_SET_RUN(lua);
1387 HLUA_CLR_CTRLYIELD(lua);
1388 HLUA_CLR_WAKERESWR(lua);
1389 HLUA_CLR_WAKEREQWR(lua);
Christopher Faulet1f43a342021-08-04 17:58:21 +02001390 HLUA_CLR_NOYIELD(lua);
1391 if (!yield_allowed)
1392 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001393
Christopher Fauletbc275a92020-02-26 14:55:16 +01001394 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001395 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001396 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001397
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001398 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001399#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001400 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001401#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001402 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001403#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001404 switch (ret) {
1405
1406 case LUA_OK:
1407 ret = HLUA_E_OK;
1408 break;
1409
1410 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001411 /* Check if the execution timeout is expired. It it is the case, we
1412 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001413 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001414 tv_update_date(0, 1);
1415 lua->run_time += now_ms - lua->start_time;
1416 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001417 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001418 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001419 break;
1420 }
1421 /* Process the forced yield. if the general yield is not allowed or
1422 * if no task were associated this the current Lua execution
1423 * coroutine, we resume the execution. Else we want to return in the
1424 * scheduler and we want to be waked up again, to continue the
1425 * current Lua execution. So we schedule our own task.
1426 */
1427 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001428 if (!yield_allowed || !lua->task)
1429 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001430 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001431 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001432 if (!yield_allowed) {
1433 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001434 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001435 break;
1436 }
1437 ret = HLUA_E_AGAIN;
1438 break;
1439
1440 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001441
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001442 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001443 * because the errors ares the only one mean to return immediately
1444 * from and lua execution.
1445 */
1446 if (lua->flags & HLUA_EXIT) {
1447 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001448 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001449 break;
1450 }
1451
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001452 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001453 if (!lua_checkstack(lua->T, 1)) {
1454 ret = HLUA_E_ERR;
1455 break;
1456 }
1457 msg = lua_tostring(lua->T, -1);
1458 lua_settop(lua->T, 0); /* Empty the stack. */
1459 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001460 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001461 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001462 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001463 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001464 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001465 ret = HLUA_E_ERRMSG;
1466 break;
1467
1468 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001469 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001470 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001471 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001472 break;
1473
1474 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001475 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001476 if (!lua_checkstack(lua->T, 1)) {
1477 ret = HLUA_E_ERR;
1478 break;
1479 }
1480 msg = lua_tostring(lua->T, -1);
1481 lua_settop(lua->T, 0); /* Empty the stack. */
1482 lua_pop(lua->T, 1);
1483 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001484 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001485 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001486 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001487 ret = HLUA_E_ERRMSG;
1488 break;
1489
1490 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001491 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001492 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001493 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001494 break;
1495 }
1496
1497 switch (ret) {
1498 case HLUA_E_AGAIN:
1499 break;
1500
1501 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001502 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001503 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001504 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001505 break;
1506
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001507 case HLUA_E_ETMOUT:
1508 case HLUA_E_NOMEM:
1509 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001510 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001511 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001512 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001513 hlua_ctx_renew(lua, 0);
1514 break;
1515
1516 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001517 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001518 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001519 break;
1520 }
1521
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001522 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001523 if (lua->state_id == 0)
Willy Tarreau1e7bef12021-08-20 15:47:25 +02001524 lua_drop_global_lock();
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001525
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001526 return ret;
1527}
1528
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001529/* This function exit the current code. */
1530__LJMP static int hlua_done(lua_State *L)
1531{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001532 struct hlua *hlua;
1533
1534 /* Get hlua struct, or NULL if we execute from main lua state */
1535 hlua = hlua_gethlua(L);
1536 if (!hlua)
1537 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001538
1539 hlua->flags |= HLUA_EXIT;
1540 WILL_LJMP(lua_error(L));
1541
1542 return 0;
1543}
1544
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001545/* This function is an LUA binding. It provides a function
1546 * for deleting ACL from a referenced ACL file.
1547 */
1548__LJMP static int hlua_del_acl(lua_State *L)
1549{
1550 const char *name;
1551 const char *key;
1552 struct pat_ref *ref;
1553
1554 MAY_LJMP(check_args(L, 2, "del_acl"));
1555
1556 name = MAY_LJMP(luaL_checkstring(L, 1));
1557 key = MAY_LJMP(luaL_checkstring(L, 2));
1558
1559 ref = pat_ref_lookup(name);
1560 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001561 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001562
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001563 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001564 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001565 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001566 return 0;
1567}
1568
1569/* This function is an LUA binding. It provides a function
1570 * for deleting map entry from a referenced map file.
1571 */
1572static int hlua_del_map(lua_State *L)
1573{
1574 const char *name;
1575 const char *key;
1576 struct pat_ref *ref;
1577
1578 MAY_LJMP(check_args(L, 2, "del_map"));
1579
1580 name = MAY_LJMP(luaL_checkstring(L, 1));
1581 key = MAY_LJMP(luaL_checkstring(L, 2));
1582
1583 ref = pat_ref_lookup(name);
1584 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001585 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001586
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001587 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001588 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001589 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001590 return 0;
1591}
1592
1593/* This function is an LUA binding. It provides a function
1594 * for adding ACL pattern from a referenced ACL file.
1595 */
1596static int hlua_add_acl(lua_State *L)
1597{
1598 const char *name;
1599 const char *key;
1600 struct pat_ref *ref;
1601
1602 MAY_LJMP(check_args(L, 2, "add_acl"));
1603
1604 name = MAY_LJMP(luaL_checkstring(L, 1));
1605 key = MAY_LJMP(luaL_checkstring(L, 2));
1606
1607 ref = pat_ref_lookup(name);
1608 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001609 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001610
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001611 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001612 if (pat_ref_find_elt(ref, key) == NULL)
1613 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001614 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001615 return 0;
1616}
1617
1618/* This function is an LUA binding. It provides a function
1619 * for setting map pattern and sample from a referenced map
1620 * file.
1621 */
1622static int hlua_set_map(lua_State *L)
1623{
1624 const char *name;
1625 const char *key;
1626 const char *value;
1627 struct pat_ref *ref;
1628
1629 MAY_LJMP(check_args(L, 3, "set_map"));
1630
1631 name = MAY_LJMP(luaL_checkstring(L, 1));
1632 key = MAY_LJMP(luaL_checkstring(L, 2));
1633 value = MAY_LJMP(luaL_checkstring(L, 3));
1634
1635 ref = pat_ref_lookup(name);
1636 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001637 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001638
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001639 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001640 if (pat_ref_find_elt(ref, key) != NULL)
1641 pat_ref_set(ref, key, value, NULL);
1642 else
1643 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001644 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001645 return 0;
1646}
1647
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001648/* A class is a lot of memory that contain data. This data can be a table,
1649 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001650 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001651 * the name of the object (_G[<name>] = <metable> ).
1652 *
1653 * A metable is a table that modify the standard behavior of a standard
1654 * access to the associated data. The entries of this new metatable are
1655 * defined as is:
1656 *
1657 * http://lua-users.org/wiki/MetatableEvents
1658 *
1659 * __index
1660 *
1661 * we access an absent field in a table, the result is nil. This is
1662 * true, but it is not the whole truth. Actually, such access triggers
1663 * the interpreter to look for an __index metamethod: If there is no
1664 * such method, as usually happens, then the access results in nil;
1665 * otherwise, the metamethod will provide the result.
1666 *
1667 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1668 * the key does not appear in the table, but the metatable has an __index
1669 * property:
1670 *
1671 * - if the value is a function, the function is called, passing in the
1672 * table and the key; the return value of that function is returned as
1673 * the result.
1674 *
1675 * - if the value is another table, the value of the key in that table is
1676 * asked for and returned (and if it doesn't exist in that table, but that
1677 * table's metatable has an __index property, then it continues on up)
1678 *
1679 * - Use "rawget(myTable,key)" to skip this metamethod.
1680 *
1681 * http://www.lua.org/pil/13.4.1.html
1682 *
1683 * __newindex
1684 *
1685 * Like __index, but control property assignment.
1686 *
1687 * __mode - Control weak references. A string value with one or both
1688 * of the characters 'k' and 'v' which specifies that the the
1689 * keys and/or values in the table are weak references.
1690 *
1691 * __call - Treat a table like a function. When a table is followed by
1692 * parenthesis such as "myTable( 'foo' )" and the metatable has
1693 * a __call key pointing to a function, that function is invoked
1694 * (passing any specified arguments) and the return value is
1695 * returned.
1696 *
1697 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1698 * called, if the metatable for myTable has a __metatable
1699 * key, the value of that key is returned instead of the
1700 * actual metatable.
1701 *
1702 * __tostring - Control string representation. When the builtin
1703 * "tostring( myTable )" function is called, if the metatable
1704 * for myTable has a __tostring property set to a function,
1705 * that function is invoked (passing myTable to it) and the
1706 * return value is used as the string representation.
1707 *
1708 * __len - Control table length. When the table length is requested using
1709 * the length operator ( '#' ), if the metatable for myTable has
1710 * a __len key pointing to a function, that function is invoked
1711 * (passing myTable to it) and the return value used as the value
1712 * of "#myTable".
1713 *
1714 * __gc - Userdata finalizer code. When userdata is set to be garbage
1715 * collected, if the metatable has a __gc field pointing to a
1716 * function, that function is first invoked, passing the userdata
1717 * to it. The __gc metamethod is not called for tables.
1718 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1719 *
1720 * Special metamethods for redefining standard operators:
1721 * http://www.lua.org/pil/13.1.html
1722 *
1723 * __add "+"
1724 * __sub "-"
1725 * __mul "*"
1726 * __div "/"
1727 * __unm "!"
1728 * __pow "^"
1729 * __concat ".."
1730 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001731 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001732 * http://www.lua.org/pil/13.2.html
1733 *
1734 * __eq "=="
1735 * __lt "<"
1736 * __le "<="
1737 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001738
1739/*
1740 *
1741 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001742 * Class Map
1743 *
1744 *
1745 */
1746
1747/* Returns a struct hlua_map if the stack entry "ud" is
1748 * a class session, otherwise it throws an error.
1749 */
1750__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1751{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001752 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001753}
1754
1755/* This function is the map constructor. It don't need
1756 * the class Map object. It creates and return a new Map
1757 * object. It must be called only during "body" or "init"
1758 * context because it process some filesystem accesses.
1759 */
1760__LJMP static int hlua_map_new(struct lua_State *L)
1761{
1762 const char *fn;
1763 int match = PAT_MATCH_STR;
1764 struct sample_conv conv;
1765 const char *file = "";
1766 int line = 0;
1767 lua_Debug ar;
1768 char *err = NULL;
1769 struct arg args[2];
1770
1771 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1772 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1773
1774 fn = MAY_LJMP(luaL_checkstring(L, 1));
1775
1776 if (lua_gettop(L) >= 2) {
1777 match = MAY_LJMP(luaL_checkinteger(L, 2));
1778 if (match < 0 || match >= PAT_MATCH_NUM)
1779 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1780 }
1781
1782 /* Get Lua filename and line number. */
1783 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1784 lua_getinfo(L, "Sl", &ar); /* get info about it */
1785 if (ar.currentline > 0) { /* is there info? */
1786 file = ar.short_src;
1787 line = ar.currentline;
1788 }
1789 }
1790
1791 /* fill fake sample_conv struct. */
1792 conv.kw = ""; /* unused. */
1793 conv.process = NULL; /* unused. */
1794 conv.arg_mask = 0; /* unused. */
1795 conv.val_args = NULL; /* unused. */
1796 conv.out_type = SMP_T_STR;
1797 conv.private = (void *)(long)match;
1798 switch (match) {
1799 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1800 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1801 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1802 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1803 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1804 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1805 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001806 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001807 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1808 default:
1809 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1810 }
1811
1812 /* fill fake args. */
1813 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001814 args[0].data.str.area = strdup(fn);
1815 args[0].data.str.data = strlen(fn);
1816 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001817 args[1].type = ARGT_STOP;
1818
1819 /* load the map. */
1820 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001821 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001822 * free the err variable.
1823 */
1824 luaL_where(L, 1);
1825 lua_pushfstring(L, "'new': %s.", err);
1826 lua_concat(L, 2);
1827 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001828 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001829 WILL_LJMP(lua_error(L));
1830 }
1831
1832 /* create the lua object. */
1833 lua_newtable(L);
1834 lua_pushlightuserdata(L, args[0].data.map);
1835 lua_rawseti(L, -2, 0);
1836
1837 /* Pop a class Map metatable and affect it to the userdata. */
1838 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1839 lua_setmetatable(L, -2);
1840
1841
1842 return 1;
1843}
1844
1845__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1846{
1847 struct map_descriptor *desc;
1848 struct pattern *pat;
1849 struct sample smp;
1850
1851 MAY_LJMP(check_args(L, 2, "lookup"));
1852 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001853 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001854 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001855 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001856 }
1857 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001858 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001859 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001860 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 +01001861 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001862 }
1863
1864 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001865 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001866 if (str)
1867 lua_pushstring(L, "");
1868 else
1869 lua_pushnil(L);
1870 return 1;
1871 }
1872
1873 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001874 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001875 return 1;
1876}
1877
1878__LJMP static int hlua_map_lookup(struct lua_State *L)
1879{
1880 return _hlua_map_lookup(L, 0);
1881}
1882
1883__LJMP static int hlua_map_slookup(struct lua_State *L)
1884{
1885 return _hlua_map_lookup(L, 1);
1886}
1887
1888/*
1889 *
1890 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001891 * Class Socket
1892 *
1893 *
1894 */
1895
1896__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1897{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001898 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899}
1900
1901/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001902 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001903 * received.
1904 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001905static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001906{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001907 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001908
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001909 if (appctx->ctx.hlua_cosocket.die) {
1910 si_shutw(si);
1911 si_shutr(si);
1912 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001913 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1914 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001915 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1916 }
1917
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001918 /* If we can't write, wakeup the pending write signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001919 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001920 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001921
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001922 /* If we can't read, wakeup the pending read signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001923 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001924 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001925
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001926 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001927 * to be notified whenever the connection completes.
1928 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001929 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001930 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001931 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001932 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001933 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001934 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001935
1936 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001937 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001938
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001939 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001940 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001941 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001942
1943 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001944 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001945 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001946
1947 /* Some data were injected in the buffer, notify the stream
1948 * interface.
1949 */
1950 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001951 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001952
1953 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001954 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001955 */
1956 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001957 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001958}
1959
Willy Tarreau87b09662015-04-03 00:22:06 +02001960/* This function is called when the "struct stream" is destroyed.
1961 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001962 * Wake all the pending signals.
1963 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001964static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001966 struct xref *peer;
1967
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001968 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001969 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1970 if (peer)
1971 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001972
1973 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001974 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1975 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001976}
1977
1978/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001979 * uses this object. If the stream does not exists, just quit.
1980 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001981 * pending signal can rest in the read and write lists. destroy
1982 * it.
1983 */
1984__LJMP static int hlua_socket_gc(lua_State *L)
1985{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001986 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001987 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001988 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001989
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001990 MAY_LJMP(check_args(L, 1, "__gc"));
1991
1992 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001993 peer = xref_get_peer_and_lock(&socket->xref);
1994 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001996 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001998 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001999 appctx->ctx.hlua_cosocket.die = 1;
2000 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002001
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002002 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002003 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002004 return 0;
2005}
2006
2007/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002008 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002009 */
sada05ed3302018-05-11 11:48:18 -07002010__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002011{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002012 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002013 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002014 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002015 struct hlua *hlua;
2016
2017 /* Get hlua struct, or NULL if we execute from main lua state */
2018 hlua = hlua_gethlua(L);
2019 if (!hlua)
2020 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002021
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002022 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002023
2024 /* Check if we run on the same thread than the xreator thread.
2025 * We cannot access to the socket if the thread is different.
2026 */
2027 if (socket->tid != tid)
2028 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2029
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002030 peer = xref_get_peer_and_lock(&socket->xref);
2031 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002032 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002033
2034 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002035 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002036
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002037 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002038 appctx->ctx.hlua_cosocket.die = 1;
2039 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002040
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002041 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002042 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043 return 0;
2044}
2045
sada05ed3302018-05-11 11:48:18 -07002046/* The close function calls close_helper.
2047 */
2048__LJMP static int hlua_socket_close(lua_State *L)
2049{
2050 MAY_LJMP(check_args(L, 1, "close"));
2051 return hlua_socket_close_helper(L);
2052}
2053
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002054/* This Lua function assumes that the stack contain three parameters.
2055 * 1 - USERDATA containing a struct socket
2056 * 2 - INTEGER with values of the macro defined below
2057 * If the integer is -1, we must read at most one line.
2058 * If the integer is -2, we ust read all the data until the
2059 * end of the stream.
2060 * If the integer is positive value, we must read a number of
2061 * bytes corresponding to this value.
2062 */
2063#define HLSR_READ_LINE (-1)
2064#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002065__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066{
2067 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2068 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002069 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002070 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002071 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002073 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002074 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002075 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002076 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002077 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002078 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002079 struct stream_interface *si;
2080 struct stream *s;
2081 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002082 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002083
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002084 /* Get hlua struct, or NULL if we execute from main lua state */
2085 hlua = hlua_gethlua(L);
2086
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087 /* Check if this lua stack is schedulable. */
2088 if (!hlua || !hlua->task)
2089 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2090 "'frontend', 'backend' or 'task'"));
2091
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002092 /* Check if we run on the same thread than the xreator thread.
2093 * We cannot access to the socket if the thread is different.
2094 */
2095 if (socket->tid != tid)
2096 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2097
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002098 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002099 peer = xref_get_peer_and_lock(&socket->xref);
2100 if (!peer)
2101 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002102 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2103 si = appctx->owner;
2104 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002105
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002106 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002108 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002109 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002110 if (nblk < 0) /* Connection close. */
2111 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002112 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002113 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002114
2115 /* remove final \r\n. */
2116 if (nblk == 1) {
2117 if (blk1[len1-1] == '\n') {
2118 len1--;
2119 skip_at_end++;
2120 if (blk1[len1-1] == '\r') {
2121 len1--;
2122 skip_at_end++;
2123 }
2124 }
2125 }
2126 else {
2127 if (blk2[len2-1] == '\n') {
2128 len2--;
2129 skip_at_end++;
2130 if (blk2[len2-1] == '\r') {
2131 len2--;
2132 skip_at_end++;
2133 }
2134 }
2135 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002136 }
2137
2138 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002139 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002140 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 if (nblk < 0) /* Connection close. */
2142 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002143 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144 goto connection_empty;
2145 }
2146
2147 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002149 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150 if (nblk < 0) /* Connection close. */
2151 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002152 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002153 goto connection_empty;
2154
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002155 missing_bytes = wanted - socket->b.n;
2156 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002157 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002158 len1 = missing_bytes;
2159 } if (nblk == 2 && len1 + len2 > missing_bytes)
2160 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 }
2162
2163 len = len1;
2164
2165 luaL_addlstring(&socket->b, blk1, len1);
2166 if (nblk == 2) {
2167 len += len2;
2168 luaL_addlstring(&socket->b, blk2, len2);
2169 }
2170
2171 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002172 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173
2174 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002175 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176
2177 /* If the pattern reclaim to read all the data
2178 * in the connection, got out.
2179 */
2180 if (wanted == HLSR_READ_ALL)
2181 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002182 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183 goto connection_empty;
2184
2185 /* Return result. */
2186 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002187 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188 return 1;
2189
2190connection_closed:
2191
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002192 xref_unlock(&socket->xref, peer);
2193
2194no_peer:
2195
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196 /* If the buffer containds data. */
2197 if (socket->b.n > 0) {
2198 luaL_pushresult(&socket->b);
2199 return 1;
2200 }
2201 lua_pushnil(L);
2202 lua_pushstring(L, "connection closed.");
2203 return 2;
2204
2205connection_empty:
2206
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002207 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
2208 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002209 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002210 }
2211 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002212 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002213 return 0;
2214}
2215
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002216/* This Lua function gets two parameters. The first one can be string
2217 * or a number. If the string is "*l", the user requires one line. If
2218 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219 * If the value is a number, the user require a number of bytes equal
2220 * to the value. The default value is "*l" (a line).
2221 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002222 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002223 * integer takes this values:
2224 * -1 : read a line
2225 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002226 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002228 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229 * concatenated with the read data.
2230 */
2231__LJMP static int hlua_socket_receive(struct lua_State *L)
2232{
2233 int wanted = HLSR_READ_LINE;
2234 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002235 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236 char *error;
2237 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002238 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239
2240 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2241 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2242
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002243 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002245 /* Check if we run on the same thread than the xreator thread.
2246 * We cannot access to the socket if the thread is different.
2247 */
2248 if (socket->tid != tid)
2249 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2250
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251 /* check for pattern. */
2252 if (lua_gettop(L) >= 2) {
2253 type = lua_type(L, 2);
2254 if (type == LUA_TSTRING) {
2255 pattern = lua_tostring(L, 2);
2256 if (strcmp(pattern, "*a") == 0)
2257 wanted = HLSR_READ_ALL;
2258 else if (strcmp(pattern, "*l") == 0)
2259 wanted = HLSR_READ_LINE;
2260 else {
2261 wanted = strtoll(pattern, &error, 10);
2262 if (*error != '\0')
2263 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2264 }
2265 }
2266 else if (type == LUA_TNUMBER) {
2267 wanted = lua_tointeger(L, 2);
2268 if (wanted < 0)
2269 WILL_LJMP(luaL_error(L, "Unsupported size."));
2270 }
2271 }
2272
2273 /* Set pattern. */
2274 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002275
2276 /* Check if we would replace the top by itself. */
2277 if (lua_gettop(L) != 2)
2278 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279
Christopher Fauletc31b2002021-05-03 10:11:13 +02002280 /* Save index of the top of the stack because since buffers are used, it
2281 * may change
2282 */
2283 lastarg = lua_gettop(L);
2284
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002285 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286 luaL_buffinit(L, &socket->b);
2287
2288 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002289 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290 if (lua_type(L, 3) != LUA_TSTRING)
2291 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2292 pattern = lua_tolstring(L, 3, &len);
2293 luaL_addlstring(&socket->b, pattern, len);
2294 }
2295
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002296 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002297}
2298
2299/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002300 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002302static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002303{
2304 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002305 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 struct appctx *appctx;
2307 size_t buf_len;
2308 const char *buf;
2309 int len;
2310 int send_len;
2311 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002312 struct xref *peer;
2313 struct stream_interface *si;
2314 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002316 /* Get hlua struct, or NULL if we execute from main lua state */
2317 hlua = hlua_gethlua(L);
2318
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 /* Check if this lua stack is schedulable. */
2320 if (!hlua || !hlua->task)
2321 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2322 "'frontend', 'backend' or 'task'"));
2323
2324 /* Get object */
2325 socket = MAY_LJMP(hlua_checksocket(L, 1));
2326 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002327 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002329 /* Check if we run on the same thread than the xreator thread.
2330 * We cannot access to the socket if the thread is different.
2331 */
2332 if (socket->tid != tid)
2333 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2334
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002335 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002336 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002337 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002338 lua_pushinteger(L, -1);
2339 return 1;
2340 }
2341 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2342 si = appctx->owner;
2343 s = si_strm(si);
2344
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002346 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002347 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348 lua_pushinteger(L, -1);
2349 return 1;
2350 }
2351
2352 /* Update the input buffer data. */
2353 buf += sent;
2354 send_len = buf_len - sent;
2355
2356 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002357 if (sent >= buf_len) {
2358 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002360 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002362 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002363 * the request buffer if its not required.
2364 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002365 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002366 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002367 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002368 }
2369
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002370 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002371 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002372 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002374 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375
2376 /* send data */
2377 if (len < send_len)
2378 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002379 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002380
2381 /* "Not enough space" (-1), "Buffer too little to contain
2382 * the data" (-2) are not expected because the available length
2383 * is tested.
2384 * Other unknown error are also not expected.
2385 */
2386 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002387 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002388 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002389
sada05ed3302018-05-11 11:48:18 -07002390 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002391 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002392 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002393 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 return 1;
2395 }
2396
2397 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002398 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002399
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002400 s->req.rex = TICK_ETERNITY;
2401 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002402
2403 /* Update length sent. */
2404 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002405 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002406
2407 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002408 if (sent + len >= buf_len) {
2409 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002410 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002411 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412
2413hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002414 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2415 xref_unlock(&socket->xref, peer);
2416 WILL_LJMP(luaL_error(L, "out of memory"));
2417 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002418 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002419 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002420 return 0;
2421}
2422
2423/* This function initiate the send of data. It just check the input
2424 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002425 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002426 * "hlua_socket_write_yield" that can yield.
2427 *
2428 * The Lua function gets between 3 and 4 parameters. The first one is
2429 * the associated object. The second is a string buffer. The third is
2430 * a facultative integer that represents where is the buffer position
2431 * of the start of the data that can send. The first byte is the
2432 * position "1". The default value is "1". The fourth argument is a
2433 * facultative integer that represents where is the buffer position
2434 * of the end of the data that can send. The default is the last byte.
2435 */
2436static int hlua_socket_send(struct lua_State *L)
2437{
2438 int i;
2439 int j;
2440 const char *buf;
2441 size_t buf_len;
2442
2443 /* Check number of arguments. */
2444 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2445 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2446
2447 /* Get the string. */
2448 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2449
2450 /* Get and check j. */
2451 if (lua_gettop(L) == 4) {
2452 j = MAY_LJMP(luaL_checkinteger(L, 4));
2453 if (j < 0)
2454 j = buf_len + j + 1;
2455 if (j > buf_len)
2456 j = buf_len + 1;
2457 lua_pop(L, 1);
2458 }
2459 else
2460 j = buf_len;
2461
2462 /* Get and check i. */
2463 if (lua_gettop(L) == 3) {
2464 i = MAY_LJMP(luaL_checkinteger(L, 3));
2465 if (i < 0)
2466 i = buf_len + i + 1;
2467 if (i > buf_len)
2468 i = buf_len + 1;
2469 lua_pop(L, 1);
2470 } else
2471 i = 1;
2472
2473 /* Check bth i and j. */
2474 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002475 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002476 return 1;
2477 }
2478 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002479 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002480 return 1;
2481 }
2482 if (i == 0)
2483 i = 1;
2484 if (j == 0)
2485 j = 1;
2486
2487 /* Pop the string. */
2488 lua_pop(L, 1);
2489
2490 /* Update the buffer length. */
2491 buf += i - 1;
2492 buf_len = j - i + 1;
2493 lua_pushlstring(L, buf, buf_len);
2494
2495 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002496 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002497
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002498 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002499}
2500
Willy Tarreau22b0a682015-06-17 19:43:49 +02002501#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2503{
2504 static char buffer[SOCKET_INFO_MAX_LEN];
2505 int ret;
2506 int len;
2507 char *p;
2508
2509 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2510 if (ret <= 0) {
2511 lua_pushnil(L);
2512 return 1;
2513 }
2514
2515 if (ret == AF_UNIX) {
2516 lua_pushstring(L, buffer+1);
2517 return 1;
2518 }
2519 else if (ret == AF_INET6) {
2520 buffer[0] = '[';
2521 len = strlen(buffer);
2522 buffer[len] = ']';
2523 len++;
2524 buffer[len] = ':';
2525 len++;
2526 p = buffer;
2527 }
2528 else if (ret == AF_INET) {
2529 p = buffer + 1;
2530 len = strlen(p);
2531 p[len] = ':';
2532 len++;
2533 }
2534 else {
2535 lua_pushnil(L);
2536 return 1;
2537 }
2538
2539 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2540 lua_pushnil(L);
2541 return 1;
2542 }
2543
2544 lua_pushstring(L, p);
2545 return 1;
2546}
2547
2548/* Returns information about the peer of the connection. */
2549__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2550{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002551 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002552 struct xref *peer;
2553 struct appctx *appctx;
2554 struct stream_interface *si;
2555 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002556 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002557
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002558 MAY_LJMP(check_args(L, 1, "getpeername"));
2559
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002560 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002561
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002562 /* Check if we run on the same thread than the xreator thread.
2563 * We cannot access to the socket if the thread is different.
2564 */
2565 if (socket->tid != tid)
2566 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2567
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002568 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002569 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002570 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002571 lua_pushnil(L);
2572 return 1;
2573 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002574 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2575 si = appctx->owner;
2576 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002577
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002578 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002579 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002580 lua_pushnil(L);
2581 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002582 }
2583
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002584 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002585 xref_unlock(&socket->xref, peer);
2586 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002587}
2588
2589/* Returns information about my connection side. */
2590static int hlua_socket_getsockname(struct lua_State *L)
2591{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002592 struct hlua_socket *socket;
2593 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002594 struct appctx *appctx;
2595 struct xref *peer;
2596 struct stream_interface *si;
2597 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002598 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002599
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002600 MAY_LJMP(check_args(L, 1, "getsockname"));
2601
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002602 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002603
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002604 /* Check if we run on the same thread than the xreator thread.
2605 * We cannot access to the socket if the thread is different.
2606 */
2607 if (socket->tid != tid)
2608 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2609
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002610 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002611 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002612 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002613 lua_pushnil(L);
2614 return 1;
2615 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002616 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2617 si = appctx->owner;
2618 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002619
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002620 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002621 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002622 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002623 lua_pushnil(L);
2624 return 1;
2625 }
2626
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002627 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002628 xref_unlock(&socket->xref, peer);
2629 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002630}
2631
2632/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002633static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634 .obj_type = OBJ_TYPE_APPLET,
2635 .name = "<LUA_TCP>",
2636 .fct = hlua_socket_handler,
2637 .release = hlua_socket_release,
2638};
2639
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002640__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002641{
2642 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002643 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002644 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002645 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002646 struct stream_interface *si;
2647 struct stream *s;
2648
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002649 /* Get hlua struct, or NULL if we execute from main lua state */
2650 hlua = hlua_gethlua(L);
2651 if (!hlua)
2652 return 0;
2653
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002654 /* Check if we run on the same thread than the xreator thread.
2655 * We cannot access to the socket if the thread is different.
2656 */
2657 if (socket->tid != tid)
2658 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2659
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002660 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002661 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002662 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002663 lua_pushnil(L);
2664 lua_pushstring(L, "Can't connect");
2665 return 2;
2666 }
2667 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2668 si = appctx->owner;
2669 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002670
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002671 /* Check if we run on the same thread than the xreator thread.
2672 * We cannot access to the socket if the thread is different.
2673 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002674 if (socket->tid != tid) {
2675 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002676 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002677 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002678
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002679 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002680 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002681 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002682 lua_pushnil(L);
2683 lua_pushstring(L, "Can't connect");
2684 return 2;
2685 }
2686
Willy Tarreaue09101e2018-10-16 17:37:12 +02002687 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002688
2689 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002690 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002691 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002692 lua_pushinteger(L, 1);
2693 return 1;
2694 }
2695
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002696 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2697 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002698 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002699 }
2700 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002701 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002702 return 0;
2703}
2704
2705/* This function fail or initite the connection. */
2706__LJMP static int hlua_socket_connect(struct lua_State *L)
2707{
2708 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002709 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002710 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002711 struct hlua *hlua;
2712 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002713 int low, high;
2714 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002715 struct xref *peer;
2716 struct stream_interface *si;
2717 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002718
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002719 if (lua_gettop(L) < 2)
2720 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002721
2722 /* Get args. */
2723 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002724
2725 /* Check if we run on the same thread than the xreator thread.
2726 * We cannot access to the socket if the thread is different.
2727 */
2728 if (socket->tid != tid)
2729 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2730
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002731 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002732 if (lua_gettop(L) >= 3) {
2733 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002734 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002735
Tim Duesterhus6edab862018-01-06 19:04:45 +01002736 /* Force the ip to end with a colon, to support IPv6 addresses
2737 * that are not enclosed within square brackets.
2738 */
2739 if (port > 0) {
2740 luaL_buffinit(L, &b);
2741 luaL_addstring(&b, ip);
2742 luaL_addchar(&b, ':');
2743 luaL_pushresult(&b);
2744 ip = lua_tolstring(L, lua_gettop(L), NULL);
2745 }
2746 }
2747
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002748 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002749 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002750 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002751 lua_pushnil(L);
2752 return 1;
2753 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002754
2755 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002756 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 +02002757 if (!addr) {
2758 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002759 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002760 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002761
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002762 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002763 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002764 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002765 if (port == -1) {
2766 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002767 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002768 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002769 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2770 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002771 if (port == -1) {
2772 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002773 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002774 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002775 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002776 }
2777 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002778
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002779 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2780 si = appctx->owner;
2781 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002782
Willy Tarreau9b7587a2020-10-15 07:32:10 +02002783 if (!sockaddr_alloc(&s->target_addr, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002784 xref_unlock(&socket->xref, peer);
2785 WILL_LJMP(luaL_error(L, "connect: internal error"));
2786 }
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002787 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002788
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002789 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002790 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002791 if (!hlua)
2792 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002793
2794 /* inform the stream that we want to be notified whenever the
2795 * connection completes.
2796 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002797 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002798 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002799 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002800
Willy Tarreauf31af932020-01-14 09:59:38 +01002801 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002802
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002803 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2804 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002805 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002806 }
2807 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002808
2809 task_wakeup(s->task, TASK_WOKEN_INIT);
2810 /* Return yield waiting for connection. */
2811
Willy Tarreau9635e032018-10-16 17:52:55 +02002812 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002813
2814 return 0;
2815}
2816
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002817#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002818__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2819{
2820 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002821 struct xref *peer;
2822 struct appctx *appctx;
2823 struct stream_interface *si;
2824 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002825
2826 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2827 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002828
2829 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002830 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002831 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002832 lua_pushnil(L);
2833 return 1;
2834 }
2835 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2836 si = appctx->owner;
2837 s = si_strm(si);
2838
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002839 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002840 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002841 return MAY_LJMP(hlua_socket_connect(L));
2842}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002843#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002844
2845__LJMP static int hlua_socket_setoption(struct lua_State *L)
2846{
2847 return 0;
2848}
2849
2850__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2851{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002852 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002853 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002854 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002855 struct xref *peer;
2856 struct appctx *appctx;
2857 struct stream_interface *si;
2858 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002859
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002860 MAY_LJMP(check_args(L, 2, "settimeout"));
2861
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002862 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002863
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002864 /* convert the timeout to millis */
2865 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002866
Thierry Fournier17a921b2018-03-08 09:59:02 +01002867 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002868 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002869 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2870
Mark Lakes56cc1252018-03-27 09:48:06 +02002871 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002872 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002873
2874 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002875 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002876 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002877
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002878 /* Check if we run on the same thread than the xreator thread.
2879 * We cannot access to the socket if the thread is different.
2880 */
2881 if (socket->tid != tid)
2882 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2883
Mark Lakes56cc1252018-03-27 09:48:06 +02002884 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002885 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002886 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002887 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2888 WILL_LJMP(lua_error(L));
2889 return 0;
2890 }
2891 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2892 si = appctx->owner;
2893 s = si_strm(si);
2894
Cyril Bonté7bb63452018-08-17 23:51:02 +02002895 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002896 s->req.rto = tmout;
2897 s->req.wto = tmout;
2898 s->res.rto = tmout;
2899 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002900 s->req.rex = tick_add_ifset(now_ms, tmout);
2901 s->req.wex = tick_add_ifset(now_ms, tmout);
2902 s->res.rex = tick_add_ifset(now_ms, tmout);
2903 s->res.wex = tick_add_ifset(now_ms, tmout);
2904
2905 s->task->expire = tick_add_ifset(now_ms, tmout);
2906 task_queue(s->task);
2907
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002908 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002909
Thierry Fourniere9636f12018-03-08 09:54:32 +01002910 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002911 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002912}
2913
2914__LJMP static int hlua_socket_new(lua_State *L)
2915{
2916 struct hlua_socket *socket;
2917 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002918 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002919 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002920
2921 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002922 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002923 hlua_pusherror(L, "socket: full stack");
2924 goto out_fail_conf;
2925 }
2926
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002927 /* Create the object: obj[0] = userdata. */
2928 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002929 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002930 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002931 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002932 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002933
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002934 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002935 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002936 hlua_pusherror(L, "socket: uninitialized pools.");
2937 goto out_fail_conf;
2938 }
2939
Willy Tarreau87b09662015-04-03 00:22:06 +02002940 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002941 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2942 lua_setmetatable(L, -2);
2943
Willy Tarreaud420a972015-04-06 00:39:18 +02002944 /* Create the applet context */
Willy Tarreaue6124462021-09-13 10:07:38 +02002945 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002946 if (!appctx) {
2947 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002948 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002949 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002950
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002951 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002952 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002953 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2954 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002955
Willy Tarreaud420a972015-04-06 00:39:18 +02002956 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002957 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002958 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002959 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002960 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002961 }
2962
Christopher Faulet26256f82020-09-14 11:40:13 +02002963 strm = stream_new(sess, &appctx->obj_type, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002964 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002965 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002966 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002967 }
2968
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002969 /* Initialise cross reference between stream and Lua socket object. */
2970 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002971
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002972 /* Configure "right" stream interface. this "si" is used to connect
2973 * and retrieve data from the server. The connection is initialized
2974 * with the "struct server".
2975 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002976 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002977
2978 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002979 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002980 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002981
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002982 return 1;
2983
Willy Tarreaud420a972015-04-06 00:39:18 +02002984 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002985 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002986 out_fail_sess:
2987 appctx_free(appctx);
2988 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002989 WILL_LJMP(lua_error(L));
2990 return 0;
2991}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002992
2993/*
2994 *
2995 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002996 * Class Channel
2997 *
2998 *
2999 */
3000
3001/* Returns the struct hlua_channel join to the class channel in the
3002 * stack entry "ud" or throws an argument error.
3003 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003004__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003005{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003006 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003007}
3008
Willy Tarreau47860ed2015-03-10 14:07:50 +01003009/* Pushes the channel onto the top of the stack. If the stask does not have a
3010 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003011 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003012static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003013{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003014 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003015 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003016 return 0;
3017
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003018 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003019 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003020 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003021
3022 /* Pop a class sesison metatable and affect it to the userdata. */
3023 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3024 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003025 return 1;
3026}
3027
Christopher Faulet9f55a502020-02-25 15:21:02 +01003028/* Helper function returning a filter attached to a channel at the position <ud>
3029 * in the stack, filling the current offset and length of the filter. If no
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05003030 * filter is attached, NULL is returned and <offset> and <len> are not
Christopher Faulet9f55a502020-02-25 15:21:02 +01003031 * initialized.
3032 */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003033static 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 +01003034{
3035 struct filter *filter = NULL;
3036
3037 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
3038 struct hlua_flt_ctx *flt_ctx;
3039
3040 filter = lua_touserdata (L, -1);
3041 flt_ctx = filter->ctx;
3042 if (hlua_filter_from_payload(filter)) {
3043 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
3044 *len = flt_ctx->cur_len[CHN_IDX(chn)];
3045 }
3046 }
3047
3048 lua_pop(L, 1);
3049 return filter;
3050}
3051
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003052/* Copies <len> bytes of data present in the channel's buffer, starting at the
3053* offset <offset>, and put it in a LUA string variable. It is the caller
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003054* responsibility to ensure <len> and <offset> are valid. It always return the
3055* length of the built string. <len> may be 0, in this case, an empty string is
3056* created and 0 is returned.
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003057*/
3058static inline int _hlua_channel_dup(struct channel *chn, lua_State *L, size_t offset, size_t len)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003059{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003060 size_t block1, block2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003061 luaL_Buffer b;
3062
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003063 block1 = len;
3064 if (block1 > b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset)))
3065 block1 = b_contig_data(&chn->buf, b_peek_ofs(&chn->buf, offset));
3066 block2 = len - block1;
3067
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003068 luaL_buffinit(L, &b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003069 luaL_addlstring(&b, b_peek(&chn->buf, offset), block1);
3070 if (block2)
3071 luaL_addlstring(&b, b_orig(&chn->buf), block2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003072 luaL_pushresult(&b);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003073 return len;
3074}
3075
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003076/* Inserts the string <str> to the channel's buffer at the offset <offset>. This
3077 * function returns -1 if data cannot be copied. Otherwise, it returns the
3078 * number of bytes copied.
3079 */
3080static int _hlua_channel_insert(struct channel *chn, lua_State *L, struct ist str, size_t offset)
3081{
3082 int ret = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003083
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003084 /* Nothing to do, just return */
3085 if (unlikely(istlen(str) == 0))
3086 goto end;
3087
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003088 if (istlen(str) > c_room(chn)) {
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003089 ret = -1;
3090 goto end;
3091 }
3092 ret = b_insert_blk(&chn->buf, offset, istptr(str), istlen(str));
3093
3094 end:
3095 return ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003096}
3097
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003098/* Removes <len> bytes of data at the absolute position <offset>.
3099 */
3100static void _hlua_channel_delete(struct channel *chn, size_t offset, size_t len)
3101{
3102 size_t end = offset + len;
3103
3104 if (b_peek(&chn->buf, end) != b_tail(&chn->buf))
3105 b_move(&chn->buf, b_peek_ofs(&chn->buf, end),
3106 b_data(&chn->buf) - end, -len);
3107 b_sub(&chn->buf, len);
3108}
3109
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003110/* Copies input data in the channel's buffer. It is possible to set a specific
3111 * offset (0 by default) and a length (all remaining input data starting for the
3112 * offset by default). If there is not enough input data and more data can be
3113 * received, this function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003114 *
3115 * From an action, All input data are considered. For a filter, the offset and
3116 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003117 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003118__LJMP static int hlua_channel_get_data_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003119{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003120 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003121 struct filter *filter;
3122 size_t input, output;
3123 int offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003124
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003125 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003126
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003127 output = co_data(chn);
3128 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003129
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003130 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3131 if (filter && !hlua_filter_from_payload(filter))
3132 WILL_LJMP(lua_error(L));
3133
3134 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003135 if (lua_gettop(L) > 1) {
3136 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3137 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003138 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003139 offset += output;
3140 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003141 lua_pushfstring(L, "offset out of range.");
3142 WILL_LJMP(lua_error(L));
3143 }
3144 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003145 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003146 if (lua_gettop(L) == 3) {
3147 len = MAY_LJMP(luaL_checkinteger(L, 3));
3148 if (!len)
3149 goto dup;
3150 if (len == -1)
3151 len = global.tune.bufsize;
3152 if (len < 0) {
3153 lua_pushfstring(L, "length out of range.");
3154 WILL_LJMP(lua_error(L));
3155 }
3156 }
3157
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003158 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003159 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3160 /* Yield waiting for more data, as requested */
3161 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_data_yield, TICK_ETERNITY, 0));
3162 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003163 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003164 }
3165
3166 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003167 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003168 return 1;
3169}
3170
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003171/* Copies the first line (including the trailing LF) of input data in the
3172 * channel's buffer. It is possible to set a specific offset (0 by default) and
3173 * a length (all remaining input data starting for the offset by default). If
3174 * there is not enough input data and more data can be received, the function
3175 * yields. If a length is explicitly specified, no more data are
3176 * copied. Otherwise, if no LF is found and more data can be received, this
3177 * function yields.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003178 *
3179 * From an action, All input data are considered. For a filter, the offset and
3180 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003181 */
3182__LJMP static int hlua_channel_get_line_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003183{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003184 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003185 struct filter *filter;
3186 size_t l, input, output;
3187 int offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003188
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003189 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003190 output = co_data(chn);
3191 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003192
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003193 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3194 if (filter && !hlua_filter_from_payload(filter))
3195 WILL_LJMP(lua_error(L));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003196
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003197 offset = output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003198 if (lua_gettop(L) > 1) {
3199 offset = MAY_LJMP(luaL_checkinteger(L, 2));
3200 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003201 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003202 offset += output;
3203 if (offset < output || offset > input + output) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003204 lua_pushfstring(L, "offset out of range.");
3205 WILL_LJMP(lua_error(L));
3206 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003207 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003208
3209 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003210 if (lua_gettop(L) == 3) {
3211 len = MAY_LJMP(luaL_checkinteger(L, 3));
3212 if (!len)
3213 goto dup;
3214 if (len == -1)
3215 len = global.tune.bufsize;
3216 if (len < 0) {
3217 lua_pushfstring(L, "length out of range.");
3218 WILL_LJMP(lua_error(L));
3219 }
3220 }
3221
3222 for (l = 0; l < len; l++) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003223 if (l + offset >= output + input)
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003224 break;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003225 if (*(b_peek(&chn->buf, offset + l)) == '\n') {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003226 len = l+1;
3227 goto dup;
3228 }
3229 }
3230
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003231 if (offset + len > output + input) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003232 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3233 /* Yield waiting for more data */
3234 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_line_yield, TICK_ETERNITY, 0));
3235 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003236 len = output + input - offset;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003237 }
3238
3239 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003240 _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003241 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003242}
3243
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003244/* [ DEPRECATED ]
3245 *
3246 * Duplicate all input data foud in the channel's buffer. The data are not
3247 * removed from the buffer. This function relies on _hlua_channel_dup().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003248 *
3249 * From an action, All input data are considered. For a filter, the offset and
3250 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003251 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003252__LJMP static int hlua_channel_dup(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003253{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003254 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003255 struct filter *filter;
3256 size_t offset, len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003257
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003258 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003259 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003260 if (IS_HTX_STRM(chn_strm(chn))) {
3261 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3262 WILL_LJMP(lua_error(L));
3263 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003264
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003265 offset = co_data(chn);
3266 len = ci_data(chn);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003267
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003268 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3269 if (filter && !hlua_filter_from_payload(filter))
3270 WILL_LJMP(lua_error(L));
3271
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003272 if (!ci_data(chn) && channel_input_closed(chn)) {
3273 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003274 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003275 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003276
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003277 _hlua_channel_dup(chn, L, offset, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003278 return 1;
3279}
3280
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003281/* [ DEPRECATED ]
3282 *
3283 * Get all input data foud in the channel's buffer. The data are removed from
3284 * the buffer after the copy. This function relies on _hlua_channel_dup() and
3285 * _hlua_channel_delete().
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003286 *
3287 * From an action, All input data are considered. For a filter, the offset and
3288 * the length of input data to consider are retrieved from the filter context.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003289 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003290__LJMP static int hlua_channel_get(lua_State *L)
3291{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003292 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003293 struct filter *filter;
3294 size_t offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003295 int ret;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003296
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003297 MAY_LJMP(check_args(L, 1, "get"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003298 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3299 if (IS_HTX_STRM(chn_strm(chn))) {
3300 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3301 WILL_LJMP(lua_error(L));
3302 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003303
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003304 offset = co_data(chn);
3305 len = ci_data(chn);
3306
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003307 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3308 if (filter && !hlua_filter_from_payload(filter))
3309 WILL_LJMP(lua_error(L));
3310
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003311 if (!ci_data(chn) && channel_input_closed(chn)) {
3312 lua_pushnil(L);
3313 return 1;
3314 }
3315
3316 ret = _hlua_channel_dup(chn, L, offset, len);
3317 _hlua_channel_delete(chn, offset, ret);
3318 return 1;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003319}
3320
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003321/* This functions consumes and returns one line. If the channel is closed,
3322 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003323 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003324 * value.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003325 *
3326 * From an action, All input data are considered. For a filter, the offset and
3327 * the length of input data to consider are retrieved from the filter context.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003328 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003329__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003330{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003331 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003332 struct filter *filter;
3333 size_t l, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003334 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003335
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003336 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003337
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003338 offset = co_data(chn);
3339 len = ci_data(chn);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003340
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003341 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3342 if (filter && !hlua_filter_from_payload(filter))
3343 WILL_LJMP(lua_error(L));
3344
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003345 if (!ci_data(chn) && channel_input_closed(chn)) {
3346 lua_pushnil(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003347 return 1;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003348 }
3349
3350 for (l = 0; l < len; l++) {
3351 if (*(b_peek(&chn->buf, offset+l)) == '\n') {
3352 len = l+1;
3353 goto dup;
3354 }
3355 }
3356
3357 if (!HLUA_CANT_YIELD(hlua_gethlua(L)) && !channel_input_closed(chn) && channel_may_recv(chn)) {
3358 /* Yield waiting for more data */
3359 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
3360 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003361
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003362 dup:
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003363 ret = _hlua_channel_dup(chn, L, offset, len);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003364 _hlua_channel_delete(chn, offset, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003365 return 1;
3366}
3367
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003368/* [ DEPRECATED ]
3369 *
3370 * Check arguments for the function "hlua_channel_getline_yield".
3371 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003372__LJMP static int hlua_channel_getline(lua_State *L)
3373{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003374 struct channel *chn;
3375
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003376 MAY_LJMP(check_args(L, 1, "getline"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003377 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3378 if (IS_HTX_STRM(chn_strm(chn))) {
3379 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3380 WILL_LJMP(lua_error(L));
3381 }
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003382 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3383}
3384
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003385/* Retrieves a given amount of input data at the given offset. By default all
3386 * available input data are returned. The offset may be negactive to start from
3387 * the end of input data. The length may be -1 to set it to the maximum buffer
3388 * size.
3389 */
3390__LJMP static int hlua_channel_get_data(lua_State *L)
3391{
3392 struct channel *chn;
3393
3394 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3395 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
3396 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3397 if (IS_HTX_STRM(chn_strm(chn))) {
3398 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3399 WILL_LJMP(lua_error(L));
3400 }
3401 return MAY_LJMP(hlua_channel_get_data_yield(L, 0, 0));
3402}
3403
3404/* Retrieves a given amount of input data at the given offset. By default all
3405 * available input data are returned. The offset may be negactive to start from
3406 * the end of input data. The length may be -1 to set it to the maximum buffer
3407 * size.
3408 */
3409__LJMP static int hlua_channel_get_line(lua_State *L)
3410{
3411 struct channel *chn;
3412
3413 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3414 WILL_LJMP(luaL_error(L, "'line' expects at most 2 arguments"));
3415 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3416 if (IS_HTX_STRM(chn_strm(chn))) {
3417 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3418 WILL_LJMP(lua_error(L));
3419 }
3420 return MAY_LJMP(hlua_channel_get_line_yield(L, 0, 0));
3421}
3422
3423/* Appends a string into the input side of channel. It returns the length of the
3424 * written string, or -1 if the channel is closed or if the buffer size is too
3425 * little for the data. 0 may be returned if nothing is copied. This function
3426 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003427 *
3428 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003429 */
Christopher Faulet23976d92021-08-06 09:59:49 +02003430__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003431{
Christopher Faulet23976d92021-08-06 09:59:49 +02003432 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003433 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003434 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003435 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003436 int ret;
Christopher Faulet23976d92021-08-06 09:59:49 +02003437
3438 MAY_LJMP(check_args(L, 2, "append"));
3439 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003440 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003441 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003442 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003443 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003444 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003445
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003446 offset = co_data(chn);
3447 len = ci_data(chn);
3448
3449 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3450 if (filter && !hlua_filter_from_payload(filter))
3451 WILL_LJMP(lua_error(L));
3452
3453 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3454 if (ret > 0 && filter) {
3455 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3456
3457 flt_update_offsets(filter, chn, ret);
3458 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3459 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003460 lua_pushinteger(L, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003461 return 1;
3462}
3463
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003464/* Prepends a string into the input side of channel. It returns the length of the
3465 * written string, or -1 if the channel is closed or if the buffer size is too
3466 * little for the data. 0 may be returned if nothing is copied. This function
3467 * does not yield.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003468 *
3469 * For a filter, the context is updated on success.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003470 */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003471__LJMP static int hlua_channel_prepend(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003472{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003473 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003474 struct filter *filter;
Christopher Faulet23976d92021-08-06 09:59:49 +02003475 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003476 size_t sz, offset, len;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003477 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003478
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003479 MAY_LJMP(check_args(L, 2, "prepend"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003480 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003481 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3482 if (IS_HTX_STRM(chn_strm(chn))) {
3483 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3484 WILL_LJMP(lua_error(L));
3485 }
3486
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003487 offset = co_data(chn);
3488 len = ci_data(chn);
3489
3490 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3491 if (filter && !hlua_filter_from_payload(filter))
3492 WILL_LJMP(lua_error(L));
3493
3494 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3495 if (ret > 0 && filter) {
3496 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3497
3498 flt_update_offsets(filter, chn, ret);
3499 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
3500 }
3501
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003502 lua_pushinteger(L, ret);
3503 return 1;
3504}
3505
3506/* Inserts a given amount of input data at the given offset by a string
3507 * content. By default the string is appended at the end of input data. It
3508 * returns the length of the written string, or -1 if the channel is closed or
3509 * if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003510 *
3511 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003512 */
3513__LJMP static int hlua_channel_insert_data(lua_State *L)
3514{
3515 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003516 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003517 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003518 size_t sz, input, output;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003519 int ret, offset;
3520
3521 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
3522 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
3523 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3524 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003525
3526 output = co_data(chn);
3527 input = ci_data(chn);
3528
3529 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3530 if (filter && !hlua_filter_from_payload(filter))
3531 WILL_LJMP(lua_error(L));
3532
3533 offset = input + output;
3534 if (lua_gettop(L) > 2) {
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003535 offset = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003536 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003537 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003538 offset += output;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003539 if (offset < output || offset > output + input) {
3540 lua_pushfstring(L, "offset out of range.");
3541 WILL_LJMP(lua_error(L));
3542 }
3543 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003544 if (IS_HTX_STRM(chn_strm(chn))) {
3545 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3546 WILL_LJMP(lua_error(L));
3547 }
3548
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003549 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3550 if (ret > 0 && filter) {
3551 struct hlua_flt_ctx *flt_ctx = filter->ctx;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003552
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003553 flt_update_offsets(filter, chn, ret);
3554 flt_ctx->cur_len[CHN_IDX(chn)] += ret;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003555 }
3556
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003557 lua_pushinteger(L, ret);
3558 return 1;
3559}
3560/* Replaces a given amount of input data at the given offset by a string
3561 * content. By default all remaining data are removed (offset = 0 and len =
3562 * -1). It returns the length of the written string, or -1 if the channel is
3563 * closed or if the buffer size is too little for the data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003564 *
3565 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003566 */
3567__LJMP static int hlua_channel_set_data(lua_State *L)
3568{
3569 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003570 struct filter *filter;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003571 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003572 size_t sz, input, output;
3573 int ret, offset, len;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003574
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003575 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
3576 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
3577 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3578 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003579
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003580 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003581 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003582 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003583 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003584
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003585 output = co_data(chn);
3586 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003587
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003588 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3589 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003590 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003591
3592 offset = output;
3593 if (lua_gettop(L) > 2) {
3594 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3595 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003596 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003597 offset += output;
3598 if (offset < output || offset > input + output) {
3599 lua_pushfstring(L, "offset out of range.");
3600 WILL_LJMP(lua_error(L));
3601 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003602 }
3603
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003604 len = output + input - offset;
3605 if (lua_gettop(L) == 4) {
3606 len = MAY_LJMP(luaL_checkinteger(L, 4));
3607 if (!len)
3608 goto set;
3609 if (len == -1)
3610 len = output + input - offset;
3611 if (len < 0 || offset + len > output + input) {
3612 lua_pushfstring(L, "length out of range.");
3613 WILL_LJMP(lua_error(L));
3614 }
3615 }
3616
3617 set:
Christopher Faulet23976d92021-08-06 09:59:49 +02003618 /* Be sure we can copied the string once input data will be removed. */
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003619 if (sz > c_room(chn) + len)
Christopher Faulet23976d92021-08-06 09:59:49 +02003620 lua_pushinteger(L, -1);
3621 else {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003622 _hlua_channel_delete(chn, offset, len);
3623 ret = _hlua_channel_insert(chn, L, ist2(str, sz), offset);
3624 if (filter) {
3625 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3626
3627 len -= (ret > 0 ? ret : 0);
3628 flt_update_offsets(filter, chn, -len);
3629 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3630 }
3631
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003632 lua_pushinteger(L, ret);
Christopher Faulet23976d92021-08-06 09:59:49 +02003633 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003634 return 1;
3635}
3636
3637/* Removes a given amount of input data at the given offset. By default all
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003638 * input data are removed (offset = 0 and len = -1). It returns the amount of
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003639 * the removed data.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003640 *
3641 * For a filter, the context is updated on success.
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003642 */
3643__LJMP static int hlua_channel_del_data(lua_State *L)
3644{
3645 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003646 struct filter *filter;
3647 size_t input, output;
3648 int offset, len;
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003649
3650 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
3651 WILL_LJMP(luaL_error(L, "'remove' expects at most 2 arguments"));
3652 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003653
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003654 if (IS_HTX_STRM(chn_strm(chn))) {
3655 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3656 WILL_LJMP(lua_error(L));
3657 }
3658
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003659 output = co_data(chn);
3660 input = ci_data(chn);
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003661
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003662 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3663 if (filter && !hlua_filter_from_payload(filter))
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003664 WILL_LJMP(lua_error(L));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003665
3666 offset = output;
3667 if (lua_gettop(L) > 2) {
3668 offset = MAY_LJMP(luaL_checkinteger(L, 3));
3669 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02003670 offset = MAX(0, (int)input + offset);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003671 offset += output;
3672 if (offset < output || offset > input + output) {
3673 lua_pushfstring(L, "offset out of range.");
3674 WILL_LJMP(lua_error(L));
3675 }
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003676 }
3677
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003678 len = output + input - offset;
3679 if (lua_gettop(L) == 4) {
3680 len = MAY_LJMP(luaL_checkinteger(L, 4));
3681 if (!len)
3682 goto end;
3683 if (len == -1)
3684 len = output + input - offset;
3685 if (len < 0 || offset + len > output + input) {
3686 lua_pushfstring(L, "length out of range.");
3687 WILL_LJMP(lua_error(L));
3688 }
3689 }
3690
3691 _hlua_channel_delete(chn, offset, len);
3692 if (filter) {
3693 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3694
3695 flt_update_offsets(filter, chn, -len);
3696 flt_ctx->cur_len[CHN_IDX(chn)] -= len;
3697 }
3698
3699 end:
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003700 lua_pushinteger(L, len);
Christopher Faulet23976d92021-08-06 09:59:49 +02003701 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003702}
3703
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003704/* Append data in the output side of the buffer. This data is immediately
3705 * sent. The function returns the amount of data written. If the buffer
3706 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003707 * if the channel is closed.
3708 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003709__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003710{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003711 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003712 struct filter *filter;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003713 const char *str;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003714 size_t offset, len, sz;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003715 int l, ret;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003716 struct hlua *hlua;
3717
3718 /* Get hlua struct, or NULL if we execute from main lua state */
3719 hlua = hlua_gethlua(L);
3720 if (!hlua) {
3721 lua_pushnil(L);
3722 return 1;
3723 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003724
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003725 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3726 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
3727 l = MAY_LJMP(luaL_checkinteger(L, 3));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003728
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003729 offset = co_data(chn);
3730 len = ci_data(chn);
3731
3732 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3733 if (filter && !hlua_filter_from_payload(filter))
3734 WILL_LJMP(lua_error(L));
3735
3736
Willy Tarreau47860ed2015-03-10 14:07:50 +01003737 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003738 lua_pushinteger(L, -1);
3739 return 1;
3740 }
3741
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003742 len = c_room(chn);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003743 if (len > sz -l) {
3744 if (filter) {
3745 lua_pushinteger(L, -1);
3746 return 1;
3747 }
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003748 len = sz - l;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003749 }
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003750
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003751 ret = _hlua_channel_insert(chn, L, ist2(str, len), offset);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003752 if (ret == -1) {
3753 lua_pop(L, 1);
3754 lua_pushinteger(L, -1);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003755 return 1;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003756 }
3757 if (ret) {
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003758 if (filter) {
3759 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3760
3761
3762 flt_update_offsets(filter, chn, ret);
3763 FLT_OFF(filter, chn) += ret;
3764 flt_ctx->cur_off[CHN_IDX(chn)] += ret;
3765 }
3766 else
3767 c_adv(chn, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003768
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003769 l += ret;
3770 lua_pop(L, 1);
3771 lua_pushinteger(L, l);
3772 }
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003773
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003774 if (l < sz) {
3775 /* Yield only if the channel's output is not empty.
3776 * Otherwise it means we cannot add more data. */
3777 if (co_data(chn) == 0 || HLUA_CANT_YIELD(hlua_gethlua(L)))
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003778 return 1;
3779
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003780 /* If we are waiting for space in the response buffer, we
3781 * must set the flag WAKERESWR. This flag required the task
3782 * wake up if any activity is detected on the response buffer.
3783 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003784 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003785 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003786 else
3787 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003788 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003789 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003790
3791 return 1;
3792}
3793
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003794/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003795 * yield the LUA process, and resume it without checking the
3796 * input arguments.
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003797 *
3798 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003799 */
3800__LJMP static int hlua_channel_send(lua_State *L)
3801{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003802 struct channel *chn;
3803
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003804 MAY_LJMP(check_args(L, 2, "send"));
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003805 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3806 if (IS_HTX_STRM(chn_strm(chn))) {
3807 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3808 WILL_LJMP(lua_error(L));
3809 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003810 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003811 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003812}
3813
3814/* This function forward and amount of butes. The data pass from
3815 * the input side of the buffer to the output side, and can be
3816 * forwarded. This function never fails.
3817 *
3818 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003819 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003820 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003821__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003822{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003823 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003824 struct filter *filter;
3825 size_t offset, len, fwd;
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003826 int l, max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003827 struct hlua *hlua;
3828
3829 /* Get hlua struct, or NULL if we execute from main lua state */
3830 hlua = hlua_gethlua(L);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003831 if (!hlua) {
3832 lua_pushnil(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003833 return 1;
Thierry Fournier77016da2020-08-15 14:35:51 +02003834 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003835
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003836 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003837 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003838 l = MAY_LJMP(luaL_checkinteger(L, -1));
3839
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003840 offset = co_data(chn);
3841 len = ci_data(chn);
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003842
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003843 filter = hlua_channel_filter(L, 1, chn, &offset, &len);
3844 if (filter && !hlua_filter_from_payload(filter))
3845 WILL_LJMP(lua_error(L));
3846
3847 max = fwd - l;
3848 if (max > len)
3849 max = len;
3850
3851 if (filter) {
3852 struct hlua_flt_ctx *flt_ctx = filter->ctx;
3853
3854 FLT_OFF(filter, chn) += max;
3855 flt_ctx->cur_off[CHN_IDX(chn)] += max;
3856 flt_ctx->cur_len[CHN_IDX(chn)] -= max;
3857 }
3858 else
3859 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003860
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003861 l += max;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003862 lua_pop(L, 1);
3863 lua_pushinteger(L, l);
3864
3865 /* Check if it miss bytes to forward. */
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003866 if (l < fwd) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003867 /* The the input channel or the output channel are closed, we
3868 * must return the amount of data forwarded.
3869 */
Christopher Faulet2e60aa42021-08-05 11:58:37 +02003870 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003871 return 1;
3872
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003873 /* If we are waiting for space data in the response buffer, we
3874 * must set the flag WAKERESWR. This flag required the task
3875 * wake up if any activity is detected on the response buffer.
3876 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003877 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003878 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003879 else
3880 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003881
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003882 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003883 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003884 }
3885
3886 return 1;
3887}
3888
3889/* Just check the input and prepare the stack for the previous
3890 * function "hlua_channel_forward_yield"
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003891 *
3892 * This function cannot be called from a filter.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003893 */
3894__LJMP static int hlua_channel_forward(lua_State *L)
3895{
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003896 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003897
Christopher Faulet9a6ffda2021-08-06 13:49:54 +02003898 MAY_LJMP(check_args(L, 2, "forward"));
3899 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3900 if (IS_HTX_STRM(chn_strm(chn))) {
3901 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
3902 WILL_LJMP(lua_error(L));
3903 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003904 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003905 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003906}
3907
3908/* Just returns the number of bytes available in the input
3909 * side of the buffer. This function never fails.
3910 */
3911__LJMP static int hlua_channel_get_in_len(lua_State *L)
3912{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003913 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003914 struct filter *filter;
3915 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003916
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003917 MAY_LJMP(check_args(L, 1, "input"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003918 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003919
3920 output = co_data(chn);
3921 input = ci_data(chn);
3922 filter = hlua_channel_filter(L, 1, chn, &output, &input);
3923 if (filter || !IS_HTX_STRM(chn_strm(chn)))
3924 lua_pushinteger(L, input);
3925 else {
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003926 struct htx *htx = htxbuf(&chn->buf);
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003927
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003928 lua_pushinteger(L, htx->data - co_data(chn));
3929 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003930 return 1;
3931}
3932
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003933/* Returns true if the channel is full. */
3934__LJMP static int hlua_channel_is_full(lua_State *L)
3935{
3936 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003937
3938 MAY_LJMP(check_args(L, 1, "is_full"));
3939 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003940 /* ignore the reserve, we are not on a producer side (ie in an
3941 * applet).
3942 */
3943 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003944 return 1;
3945}
3946
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003947/* Returns true if the channel may still receive data. */
3948__LJMP static int hlua_channel_may_recv(lua_State *L)
3949{
3950 struct channel *chn;
3951
3952 MAY_LJMP(check_args(L, 1, "may_recv"));
3953 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3954 lua_pushboolean(L, (!channel_input_closed(chn) && channel_may_recv(chn)));
3955 return 1;
3956}
3957
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003958/* Returns true if the channel is the response channel. */
3959__LJMP static int hlua_channel_is_resp(lua_State *L)
3960{
3961 struct channel *chn;
3962
3963 MAY_LJMP(check_args(L, 1, "is_resp"));
3964 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3965
3966 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3967 return 1;
3968}
3969
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003970/* Just returns the number of bytes available in the output
3971 * side of the buffer. This function never fails.
3972 */
3973__LJMP static int hlua_channel_get_out_len(lua_State *L)
3974{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003975 struct channel *chn;
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003976 size_t output, input;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003977
Christopher Faulet6a79fc12021-08-06 16:02:36 +02003978 MAY_LJMP(check_args(L, 1, "output"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003979 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta1ac5fb2021-08-09 10:22:46 +02003980
3981 output = co_data(chn);
3982 input = ci_data(chn);
3983 hlua_channel_filter(L, 1, chn, &output, &input);
3984
3985 lua_pushinteger(L, output);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003986 return 1;
3987}
3988
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003989/*
3990 *
3991 *
3992 * Class Fetches
3993 *
3994 *
3995 */
3996
3997/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003998 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003999 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004000__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004001{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004002 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004003}
4004
4005/* This function creates and push in the stack a fetch object according
4006 * with a current TXN.
4007 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004008static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004009{
Willy Tarreau7073c472015-04-06 11:15:40 +02004010 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004011
4012 /* Check stack size. */
4013 if (!lua_checkstack(L, 3))
4014 return 0;
4015
4016 /* Create the object: obj[0] = userdata.
4017 * Note that the base of the Fetches object is the
4018 * transaction object.
4019 */
4020 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004021 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004022 lua_rawseti(L, -2, 0);
4023
Willy Tarreau7073c472015-04-06 11:15:40 +02004024 hsmp->s = txn->s;
4025 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004026 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004027 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004028
4029 /* Pop a class sesison metatable and affect it to the userdata. */
4030 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
4031 lua_setmetatable(L, -2);
4032
4033 return 1;
4034}
4035
4036/* This function is an LUA binding. It is called with each sample-fetch.
4037 * It uses closure argument to store the associated sample-fetch. It
4038 * returns only one argument or throws an error. An error is thrown
4039 * only if an error is encountered during the argument parsing. If
4040 * the "sample-fetch" function fails, nil is returned.
4041 */
4042__LJMP static int hlua_run_sample_fetch(lua_State *L)
4043{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004044 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01004045 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004046 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004047 int i;
4048 struct sample smp;
4049
4050 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004051 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004052
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004053 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004054 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004055
Thierry FOURNIERca988662015-12-20 18:43:03 +01004056 /* Check execution authorization. */
4057 if (f->use & SMP_USE_HTTP_ANY &&
4058 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
4059 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
4060 "is not available in Lua services", f->kw);
4061 WILL_LJMP(lua_error(L));
4062 }
4063
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004064 /* Get extra arguments. */
4065 for (i = 0; i < lua_gettop(L) - 1; i++) {
4066 if (i >= ARGM_NBARGS)
4067 break;
4068 hlua_lua2arg(L, i + 2, &args[i]);
4069 }
4070 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004071 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004072
4073 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004074 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004075
4076 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01004077 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004078 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004079 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004080 }
4081
4082 /* Initialise the sample. */
4083 memset(&smp, 0, sizeof(smp));
4084
4085 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01004086 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004087 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004088 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004089 lua_pushstring(L, "");
4090 else
4091 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004092 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004093 }
4094
4095 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004096 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004097 hlua_smp2lua_str(L, &smp);
4098 else
4099 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004100
4101 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004102 free_args(args);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004103 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004104
4105 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004106 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004107 WILL_LJMP(lua_error(L));
4108 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004109}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004110
4111/*
4112 *
4113 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004114 * Class Converters
4115 *
4116 *
4117 */
4118
4119/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004120 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004121 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004122__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004123{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004124 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004125}
4126
4127/* This function creates and push in the stack a Converters object
4128 * according with a current TXN.
4129 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004130static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004131{
Willy Tarreau7073c472015-04-06 11:15:40 +02004132 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004133
4134 /* Check stack size. */
4135 if (!lua_checkstack(L, 3))
4136 return 0;
4137
4138 /* Create the object: obj[0] = userdata.
4139 * Note that the base of the Converters object is the
4140 * same than the TXN object.
4141 */
4142 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02004143 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004144 lua_rawseti(L, -2, 0);
4145
Willy Tarreau7073c472015-04-06 11:15:40 +02004146 hsmp->s = txn->s;
4147 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004148 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004149 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004150
Willy Tarreau87b09662015-04-03 00:22:06 +02004151 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004152 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
4153 lua_setmetatable(L, -2);
4154
4155 return 1;
4156}
4157
4158/* This function is an LUA binding. It is called with each converter.
4159 * It uses closure argument to store the associated converter. It
4160 * returns only one argument or throws an error. An error is thrown
4161 * only if an error is encountered during the argument parsing. If
4162 * the converter function function fails, nil is returned.
4163 */
4164__LJMP static int hlua_run_sample_conv(lua_State *L)
4165{
Willy Tarreauda5f1082015-04-06 11:17:13 +02004166 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004167 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02004168 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004169 int i;
4170 struct sample smp;
4171
4172 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004173 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004174
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004175 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004176 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004177
4178 /* Get extra arguments. */
4179 for (i = 0; i < lua_gettop(L) - 2; i++) {
4180 if (i >= ARGM_NBARGS)
4181 break;
4182 hlua_lua2arg(L, i + 3, &args[i]);
4183 }
4184 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004185 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004186
4187 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02004188 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004189
4190 /* Run the special args checker. */
4191 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
4192 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004193 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004194 }
4195
4196 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004197 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004198 if (!hlua_lua2smp(L, 2, &smp)) {
4199 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004200 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004201 }
4202
Willy Tarreau1777ea62016-03-10 16:15:46 +01004203 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
4204
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004205 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004206 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004207 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004208 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004209 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004210 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02004211 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
4212 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004213 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004214 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004215 }
4216
4217 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004218 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004219 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004220 lua_pushstring(L, "");
4221 else
Willy Tarreaua678b432015-08-28 10:14:59 +02004222 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004223 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004224 }
4225
4226 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004227 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004228 hlua_smp2lua_str(L, &smp);
4229 else
4230 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004231 end:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004232 free_args(args);
Willy Tarreaua678b432015-08-28 10:14:59 +02004233 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004234
4235 error:
Willy Tarreauee0d7272021-07-16 10:26:56 +02004236 free_args(args);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02004237 WILL_LJMP(lua_error(L));
4238 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004239}
4240
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004241/*
4242 *
4243 *
4244 * Class AppletTCP
4245 *
4246 *
4247 */
4248
4249/* Returns a struct hlua_txn if the stack entry "ud" is
4250 * a class stream, otherwise it throws an error.
4251 */
4252__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
4253{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004254 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004255}
4256
4257/* This function creates and push in the stack an Applet object
4258 * according with a current TXN.
4259 */
4260static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
4261{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004262 struct hlua_appctx *luactx;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004263 struct stream_interface *si = ctx->owner;
4264 struct stream *s = si_strm(si);
4265 struct proxy *p = s->be;
4266
4267 /* Check stack size. */
4268 if (!lua_checkstack(L, 3))
4269 return 0;
4270
4271 /* Create the object: obj[0] = userdata.
4272 * Note that the base of the Converters object is the
4273 * same than the TXN object.
4274 */
4275 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004276 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004277 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004278 luactx->appctx = ctx;
4279 luactx->htxn.s = s;
4280 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004281
4282 /* Create the "f" field that contains a list of fetches. */
4283 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004284 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004285 return 0;
4286 lua_settable(L, -3);
4287
4288 /* Create the "sf" field that contains a list of stringsafe fetches. */
4289 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004290 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004291 return 0;
4292 lua_settable(L, -3);
4293
4294 /* Create the "c" field that contains a list of converters. */
4295 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004296 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004297 return 0;
4298 lua_settable(L, -3);
4299
4300 /* Create the "sc" field that contains a list of stringsafe converters. */
4301 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004302 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004303 return 0;
4304 lua_settable(L, -3);
4305
4306 /* Pop a class stream metatable and affect it to the table. */
4307 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4308 lua_setmetatable(L, -2);
4309
4310 return 1;
4311}
4312
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004313__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4314{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004315 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004316 struct stream *s;
4317 const char *name;
4318 size_t len;
4319 struct sample smp;
4320
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004321 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4322 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004323
4324 /* It is useles to retrieve the stream, but this function
4325 * runs only in a stream context.
4326 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004327 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004328 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004329 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004330
4331 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004332 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004333 hlua_lua2smp(L, 3, &smp);
4334
4335 /* Store the sample in a variable. */
4336 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004337
4338 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4339 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4340 else
4341 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4342
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004343 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004344}
4345
4346__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4347{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004348 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004349 struct stream *s;
4350 const char *name;
4351 size_t len;
4352 struct sample smp;
4353
4354 MAY_LJMP(check_args(L, 2, "unset_var"));
4355
4356 /* It is useles to retrieve the stream, but this function
4357 * runs only in a stream context.
4358 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004359 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004360 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004361 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004362
4363 /* Unset the variable. */
4364 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004365 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4366 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004367}
4368
4369__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4370{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004371 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004372 struct stream *s;
4373 const char *name;
4374 size_t len;
4375 struct sample smp;
4376
4377 MAY_LJMP(check_args(L, 2, "get_var"));
4378
4379 /* It is useles to retrieve the stream, but this function
4380 * runs only in a stream context.
4381 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004382 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004383 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004384 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004385
4386 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004387 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004388 lua_pushnil(L);
4389 return 1;
4390 }
4391
4392 return hlua_smp2lua(L, &smp);
4393}
4394
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004395__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4396{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004397 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4398 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004399 struct hlua *hlua;
4400
4401 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004402 if (!s->hlua)
4403 return 0;
4404 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004405
4406 MAY_LJMP(check_args(L, 2, "set_priv"));
4407
4408 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004409 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004410
4411 /* Get and store new value. */
4412 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4413 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4414
4415 return 0;
4416}
4417
4418__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4419{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004420 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4421 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004422 struct hlua *hlua;
4423
4424 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004425 if (!s->hlua) {
4426 lua_pushnil(L);
4427 return 1;
4428 }
4429 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004430
4431 /* Push configuration index in the stack. */
4432 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4433
4434 return 1;
4435}
4436
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004437/* If expected data not yet available, it returns a yield. This function
4438 * consumes the data in the buffer. It returns a string containing the
4439 * data. This string can be empty.
4440 */
4441__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4442{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004443 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4444 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004445 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004446 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004447 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004448 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004449 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004450
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004451 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004452 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004453
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004454 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004455 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004456 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004457 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004458 }
4459
4460 /* End of data: commit the total strings and return. */
4461 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004462 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004463 return 1;
4464 }
4465
4466 /* Ensure that the block 2 length is usable. */
4467 if (ret == 1)
4468 len2 = 0;
4469
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004470 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004471 luaL_addlstring(&luactx->b, blk1, len1);
4472 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004473
4474 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004475 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004476 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004477 return 1;
4478}
4479
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004480/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004481__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4482{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004483 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004484
4485 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004487
4488 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4489}
4490
4491/* If expected data not yet available, it returns a yield. This function
4492 * consumes the data in the buffer. It returns a string containing the
4493 * data. This string can be empty.
4494 */
4495__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4496{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004497 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4498 struct stream_interface *si = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004499 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004500 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004501 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004502 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004503 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004504 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004505
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004506 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004507 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004508
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004509 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004510 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004511 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004512 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004513 }
4514
4515 /* End of data: commit the total strings and return. */
4516 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004517 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004518 return 1;
4519 }
4520
4521 /* Ensure that the block 2 length is usable. */
4522 if (ret == 1)
4523 len2 = 0;
4524
4525 if (len == -1) {
4526
4527 /* If len == -1, catenate all the data avalaile and
4528 * yield because we want to get all the data until
4529 * the end of data stream.
4530 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004531 luaL_addlstring(&luactx->b, blk1, len1);
4532 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004533 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004534 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004535 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004536
4537 } else {
4538
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004539 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004540 if (len1 > len)
4541 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004542 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004543 len -= len1;
4544
4545 /* Copy the second block. */
4546 if (len2 > len)
4547 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004548 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004549 len -= len2;
4550
4551 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004552 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004553
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004554 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004555 if (len > 0) {
4556 lua_pushinteger(L, len);
4557 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004558 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004559 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004560 }
4561
4562 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004563 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004564 return 1;
4565 }
4566
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004567 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004568 hlua_pusherror(L, "Lua: internal error");
4569 WILL_LJMP(lua_error(L));
4570 return 0;
4571}
4572
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004573/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004574__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4575{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004576 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004577 int len = -1;
4578
4579 if (lua_gettop(L) > 2)
4580 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4581 if (lua_gettop(L) >= 2) {
4582 len = MAY_LJMP(luaL_checkinteger(L, 2));
4583 lua_pop(L, 1);
4584 }
4585
4586 /* Confirm or set the required length */
4587 lua_pushinteger(L, len);
4588
4589 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004590 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004591
4592 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4593}
4594
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004595/* Append data in the output side of the buffer. This data is immediately
4596 * sent. The function returns the amount of data written. If the buffer
4597 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004598 * if the channel is closed.
4599 */
4600__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4601{
4602 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004603 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004604 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4605 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004606 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004607 struct channel *chn = si_ic(si);
4608 int max;
4609
4610 /* Get the max amount of data which can write as input in the channel. */
4611 max = channel_recv_max(chn);
4612 if (max > (len - l))
4613 max = len - l;
4614
4615 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004616 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004617
4618 /* update counters. */
4619 l += max;
4620 lua_pop(L, 1);
4621 lua_pushinteger(L, l);
4622
4623 /* If some data is not send, declares the situation to the
4624 * applet, and returns a yield.
4625 */
4626 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004627 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004628 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004629 }
4630
4631 return 1;
4632}
4633
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004634/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004635 * yield the LUA process, and resume it without checking the
4636 * input arguments.
4637 */
4638__LJMP static int hlua_applet_tcp_send(lua_State *L)
4639{
4640 MAY_LJMP(check_args(L, 2, "send"));
4641 lua_pushinteger(L, 0);
4642
4643 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4644}
4645
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004646/*
4647 *
4648 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004649 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004650 *
4651 *
4652 */
4653
4654/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004655 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004656 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004657__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004658{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004659 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004660}
4661
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004662/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004663 * according with a current TXN.
4664 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004665static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004666{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004667 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004668 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004669 struct stream_interface *si = ctx->owner;
4670 struct stream *s = si_strm(si);
4671 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004672 struct htx *htx;
4673 struct htx_blk *blk;
4674 struct htx_sl *sl;
4675 struct ist path;
4676 unsigned long long len = 0;
4677 int32_t pos;
Amaury Denoyellec453f952021-07-06 11:40:12 +02004678 struct http_uri_parser parser;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004679
4680 /* Check stack size. */
4681 if (!lua_checkstack(L, 3))
4682 return 0;
4683
4684 /* Create the object: obj[0] = userdata.
4685 * Note that the base of the Converters object is the
4686 * same than the TXN object.
4687 */
4688 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004689 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004690 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004691 luactx->appctx = ctx;
4692 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4693 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4694 luactx->htxn.s = s;
4695 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004696
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004697 /* Create the "f" field that contains a list of fetches. */
4698 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004699 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004700 return 0;
4701 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004702
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004703 /* Create the "sf" field that contains a list of stringsafe fetches. */
4704 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004705 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004706 return 0;
4707 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004708
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004709 /* Create the "c" field that contains a list of converters. */
4710 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004711 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004712 return 0;
4713 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004714
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004715 /* Create the "sc" field that contains a list of stringsafe converters. */
4716 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004717 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004718 return 0;
4719 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004720
Christopher Fauleta2097962019-07-15 16:25:33 +02004721 htx = htxbuf(&s->req.buf);
4722 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004723 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004724 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004725
Christopher Fauleta2097962019-07-15 16:25:33 +02004726 /* Stores the request method. */
4727 lua_pushstring(L, "method");
4728 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4729 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004730
Christopher Fauleta2097962019-07-15 16:25:33 +02004731 /* Stores the http version. */
4732 lua_pushstring(L, "version");
4733 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4734 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004735
Christopher Fauleta2097962019-07-15 16:25:33 +02004736 /* creates an array of headers. hlua_http_get_headers() crates and push
4737 * the array on the top of the stack.
4738 */
4739 lua_pushstring(L, "headers");
4740 htxn.s = s;
4741 htxn.p = px;
4742 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004743 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004744 return 0;
4745 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004746
Amaury Denoyellec453f952021-07-06 11:40:12 +02004747 parser = http_uri_parser_init(htx_sl_req_uri(sl));
4748 path = http_parse_path(&parser);
Tim Duesterhused526372020-03-05 17:56:33 +01004749 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004750 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004751
Christopher Fauleta2097962019-07-15 16:25:33 +02004752 p = path.ptr;
4753 end = path.ptr + path.len;
4754 q = p;
4755 while (q < end && *q != '?')
4756 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004757
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004758 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004759 lua_pushstring(L, "path");
4760 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004761 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004762
Christopher Fauleta2097962019-07-15 16:25:33 +02004763 /* Stores the query string. */
4764 lua_pushstring(L, "qs");
4765 if (*q == '?')
4766 q++;
4767 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004768 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004769 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004770
Christopher Fauleta2097962019-07-15 16:25:33 +02004771 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4772 struct htx_blk *blk = htx_get_blk(htx, pos);
4773 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004774
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004775 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004776 break;
4777 if (type == HTX_BLK_DATA)
4778 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004779 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004780 if (htx->extra != ULLONG_MAX)
4781 len += htx->extra;
4782
4783 /* Stores the request path. */
4784 lua_pushstring(L, "length");
4785 lua_pushinteger(L, len);
4786 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004787
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004788 /* Create an empty array of HTTP request headers. */
4789 lua_pushstring(L, "response");
4790 lua_newtable(L);
4791 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004792
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004793 /* Pop a class stream metatable and affect it to the table. */
4794 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4795 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004796
4797 return 1;
4798}
4799
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004800__LJMP static int hlua_applet_http_set_var(lua_State *L)
4801{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004802 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004803 struct stream *s;
4804 const char *name;
4805 size_t len;
4806 struct sample smp;
4807
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004808 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4809 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004810
4811 /* It is useles to retrieve the stream, but this function
4812 * runs only in a stream context.
4813 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004814 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004815 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004816 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004817
4818 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004819 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004820 hlua_lua2smp(L, 3, &smp);
4821
4822 /* Store the sample in a variable. */
4823 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004824
4825 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4826 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4827 else
4828 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4829
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004830 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004831}
4832
4833__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4834{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004835 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004836 struct stream *s;
4837 const char *name;
4838 size_t len;
4839 struct sample smp;
4840
4841 MAY_LJMP(check_args(L, 2, "unset_var"));
4842
4843 /* It is useles to retrieve the stream, but this function
4844 * runs only in a stream context.
4845 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004846 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004847 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004848 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004849
4850 /* Unset the variable. */
4851 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004852 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4853 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004854}
4855
4856__LJMP static int hlua_applet_http_get_var(lua_State *L)
4857{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004858 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004859 struct stream *s;
4860 const char *name;
4861 size_t len;
4862 struct sample smp;
4863
4864 MAY_LJMP(check_args(L, 2, "get_var"));
4865
4866 /* It is useles to retrieve the stream, but this function
4867 * runs only in a stream context.
4868 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004869 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004870 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004871 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004872
4873 smp_set_owner(&smp, s->be, s->sess, s, 0);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02004874 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004875 lua_pushnil(L);
4876 return 1;
4877 }
4878
4879 return hlua_smp2lua(L, &smp);
4880}
4881
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004882__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4883{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004884 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4885 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004886 struct hlua *hlua;
4887
4888 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004889 if (!s->hlua)
4890 return 0;
4891 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004892
4893 MAY_LJMP(check_args(L, 2, "set_priv"));
4894
4895 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004896 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004897
4898 /* Get and store new value. */
4899 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4900 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4901
4902 return 0;
4903}
4904
4905__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4906{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004907 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4908 struct stream *s = luactx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004909 struct hlua *hlua;
4910
4911 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004912 if (!s->hlua) {
4913 lua_pushnil(L);
4914 return 1;
4915 }
4916 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004917
4918 /* Push configuration index in the stack. */
4919 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4920
4921 return 1;
4922}
4923
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004924/* If expected data not yet available, it returns a yield. This function
4925 * consumes the data in the buffer. It returns a string containing the
4926 * data. This string can be empty.
4927 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004928__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004929{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004930 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4931 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004932 struct channel *req = si_oc(si);
4933 struct htx *htx;
4934 struct htx_blk *blk;
4935 size_t count;
4936 int stop = 0;
4937
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004938 htx = htx_from_buf(&req->buf);
4939 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004940 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004941
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004942 while (count && !stop && blk) {
4943 enum htx_blk_type type = htx_get_blk_type(blk);
4944 uint32_t sz = htx_get_blksz(blk);
4945 struct ist v;
4946 uint32_t vlen;
4947 char *nl;
4948
4949 vlen = sz;
4950 if (vlen > count) {
4951 if (type != HTX_BLK_DATA)
4952 break;
4953 vlen = count;
4954 }
4955
4956 switch (type) {
4957 case HTX_BLK_UNUSED:
4958 break;
4959
4960 case HTX_BLK_DATA:
4961 v = htx_get_blk_value(htx, blk);
4962 v.len = vlen;
4963 nl = istchr(v, '\n');
4964 if (nl != NULL) {
4965 stop = 1;
4966 vlen = nl - v.ptr + 1;
4967 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004968 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004969 break;
4970
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004971 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004972 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004973 stop = 1;
4974 break;
4975
4976 default:
4977 break;
4978 }
4979
4980 co_set_data(req, co_data(req) - vlen);
4981 count -= vlen;
4982 if (sz == vlen)
4983 blk = htx_remove_blk(htx, blk);
4984 else {
4985 htx_cut_data_blk(htx, blk, vlen);
4986 break;
4987 }
4988 }
4989
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004990 /* The message was fully consumed and no more data are expected
4991 * (EOM flag set).
4992 */
4993 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
4994 stop = 1;
4995
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004996 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004997 if (!stop) {
4998 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004999 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005000 }
5001
5002 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005003 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005004 return 1;
5005}
5006
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005007
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005008/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005009__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005010{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005011 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005012
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005013 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005014 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005015
Christopher Fauleta2097962019-07-15 16:25:33 +02005016 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005017}
5018
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005019/* If expected data not yet available, it returns a yield. This function
5020 * consumes the data in the buffer. It returns a string containing the
5021 * data. This string can be empty.
5022 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005023__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005024{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005025 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5026 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005027 struct channel *req = si_oc(si);
5028 struct htx *htx;
5029 struct htx_blk *blk;
5030 size_t count;
5031 int len;
5032
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005033 htx = htx_from_buf(&req->buf);
5034 len = MAY_LJMP(luaL_checkinteger(L, 2));
5035 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02005036 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005037 while (count && len && blk) {
5038 enum htx_blk_type type = htx_get_blk_type(blk);
5039 uint32_t sz = htx_get_blksz(blk);
5040 struct ist v;
5041 uint32_t vlen;
5042
5043 vlen = sz;
5044 if (len > 0 && vlen > len)
5045 vlen = len;
5046 if (vlen > count) {
5047 if (type != HTX_BLK_DATA)
5048 break;
5049 vlen = count;
5050 }
5051
5052 switch (type) {
5053 case HTX_BLK_UNUSED:
5054 break;
5055
5056 case HTX_BLK_DATA:
5057 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02005058 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005059 break;
5060
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005061 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005062 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005063 len = 0;
5064 break;
5065
5066 default:
5067 break;
5068 }
5069
5070 co_set_data(req, co_data(req) - vlen);
5071 count -= vlen;
5072 if (len > 0)
5073 len -= vlen;
5074 if (sz == vlen)
5075 blk = htx_remove_blk(htx, blk);
5076 else {
5077 htx_cut_data_blk(htx, blk, vlen);
5078 break;
5079 }
5080 }
5081
Christopher Fauleteccb31c2021-04-02 14:24:56 +02005082 /* The message was fully consumed and no more data are expected
5083 * (EOM flag set).
5084 */
5085 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
5086 len = 0;
5087
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005088 htx_to_buf(htx, &req->buf);
5089
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005090 /* If we are no other data available, yield waiting for new data. */
5091 if (len) {
5092 if (len > 0) {
5093 lua_pushinteger(L, len);
5094 lua_replace(L, 2);
5095 }
5096 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005097 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005098 }
5099
5100 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005101 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005102 return 1;
5103}
5104
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005105/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005106__LJMP static int hlua_applet_http_recv(lua_State *L)
5107{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005108 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005109 int len = -1;
5110
5111 /* Check arguments. */
5112 if (lua_gettop(L) > 2)
5113 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
5114 if (lua_gettop(L) >= 2) {
5115 len = MAY_LJMP(luaL_checkinteger(L, 2));
5116 lua_pop(L, 1);
5117 }
5118
Christopher Fauleta2097962019-07-15 16:25:33 +02005119 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005120
Christopher Fauleta2097962019-07-15 16:25:33 +02005121 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005122 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005123
Christopher Fauleta2097962019-07-15 16:25:33 +02005124 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005125}
5126
5127/* Append data in the output side of the buffer. This data is immediately
5128 * sent. The function returns the amount of data written. If the buffer
5129 * cannot contain the data, the function yields. The function returns -1
5130 * if the channel is closed.
5131 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005132__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005133{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005134 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5135 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005136 struct channel *res = si_ic(si);
5137 struct htx *htx = htx_from_buf(&res->buf);
5138 const char *data;
5139 size_t len;
5140 int l = MAY_LJMP(luaL_checkinteger(L, 3));
5141 int max;
5142
Christopher Faulet9060fc02019-07-03 11:39:30 +02005143 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005144 if (!max)
5145 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005146
5147 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
5148
5149 /* Get the max amount of data which can write as input in the channel. */
5150 if (max > (len - l))
5151 max = len - l;
5152
5153 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02005154 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005155 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005156
5157 /* update counters. */
5158 l += max;
5159 lua_pop(L, 1);
5160 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005161
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005162 /* If some data is not send, declares the situation to the
5163 * applet, and returns a yield.
5164 */
5165 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01005166 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01005167 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005168 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005169 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005170 }
5171
Christopher Fauleta2097962019-07-15 16:25:33 +02005172 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005173 return 1;
5174}
5175
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005176/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005177 * yield the LUA process, and resume it without checking the
5178 * input arguments.
5179 */
5180__LJMP static int hlua_applet_http_send(lua_State *L)
5181{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005182 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005183
5184 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005185 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005186 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
5187 WILL_LJMP(lua_error(L));
5188 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005189
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005190 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02005191 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005192
Christopher Fauleta2097962019-07-15 16:25:33 +02005193 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005194}
5195
5196__LJMP static int hlua_applet_http_addheader(lua_State *L)
5197{
5198 const char *name;
5199 int ret;
5200
5201 MAY_LJMP(hlua_checkapplet_http(L, 1));
5202 name = MAY_LJMP(luaL_checkstring(L, 2));
5203 MAY_LJMP(luaL_checkstring(L, 3));
5204
5205 /* Push in the stack the "response" entry. */
5206 ret = lua_getfield(L, 1, "response");
5207 if (ret != LUA_TTABLE) {
5208 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
5209 "is expected as an array. %s found", lua_typename(L, ret));
5210 WILL_LJMP(lua_error(L));
5211 }
5212
5213 /* check if the header is already registered if it is not
5214 * the case, register it.
5215 */
5216 ret = lua_getfield(L, -1, name);
5217 if (ret == LUA_TNIL) {
5218
5219 /* Entry not found. */
5220 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
5221
5222 /* Insert the new header name in the array in the top of the stack.
5223 * It left the new array in the top of the stack.
5224 */
5225 lua_newtable(L);
5226 lua_pushvalue(L, 2);
5227 lua_pushvalue(L, -2);
5228 lua_settable(L, -4);
5229
5230 } else if (ret != LUA_TTABLE) {
5231
5232 /* corruption error. */
5233 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
5234 "is expected as an array. %s found", name, lua_typename(L, ret));
5235 WILL_LJMP(lua_error(L));
5236 }
5237
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005238 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005239 * the header value as new entry.
5240 */
5241 lua_pushvalue(L, 3);
5242 ret = lua_rawlen(L, -2);
5243 lua_rawseti(L, -2, ret + 1);
5244 lua_pushboolean(L, 1);
5245 return 1;
5246}
5247
5248__LJMP static int hlua_applet_http_status(lua_State *L)
5249{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005250 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005251 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005252 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005253
5254 if (status < 100 || status > 599) {
5255 lua_pushboolean(L, 0);
5256 return 1;
5257 }
5258
Willy Tarreau7e702d12021-04-28 17:59:21 +02005259 luactx->appctx->ctx.hlua_apphttp.status = status;
5260 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005261 lua_pushboolean(L, 1);
5262 return 1;
5263}
5264
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005265
Christopher Fauleta2097962019-07-15 16:25:33 +02005266__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005267{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005268 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5269 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005270 struct channel *res = si_ic(si);
5271 struct htx *htx;
5272 struct htx_sl *sl;
5273 struct h1m h1m;
5274 const char *status, *reason;
5275 const char *name, *value;
5276 size_t nlen, vlen;
5277 unsigned int flags;
5278
5279 /* Send the message at once. */
5280 htx = htx_from_buf(&res->buf);
5281 h1m_init_res(&h1m);
5282
5283 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005284 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5285 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005286 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005287 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5288 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005289 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5290 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5291 }
5292 else {
5293 flags = HTX_SL_F_IS_RESP;
5294 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5295 }
5296 if (!sl) {
5297 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005298 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005299 WILL_LJMP(lua_error(L));
5300 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005301 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005302
5303 /* Get the array associated to the field "response" in the object AppletHTTP. */
5304 lua_pushvalue(L, 0);
5305 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5306 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005307 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005308 WILL_LJMP(lua_error(L));
5309 }
5310
5311 /* Browse the list of headers. */
5312 lua_pushnil(L);
5313 while(lua_next(L, -2) != 0) {
5314 /* We expect a string as -2. */
5315 if (lua_type(L, -2) != LUA_TSTRING) {
5316 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005317 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005318 lua_typename(L, lua_type(L, -2)));
5319 WILL_LJMP(lua_error(L));
5320 }
5321 name = lua_tolstring(L, -2, &nlen);
5322
5323 /* We expect an array as -1. */
5324 if (lua_type(L, -1) != LUA_TTABLE) {
5325 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 +02005326 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005327 name,
5328 lua_typename(L, lua_type(L, -1)));
5329 WILL_LJMP(lua_error(L));
5330 }
5331
5332 /* Browse the table who is on the top of the stack. */
5333 lua_pushnil(L);
5334 while(lua_next(L, -2) != 0) {
5335 int id;
5336
5337 /* We expect a number as -2. */
5338 if (lua_type(L, -2) != LUA_TNUMBER) {
5339 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 +02005340 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005341 name,
5342 lua_typename(L, lua_type(L, -2)));
5343 WILL_LJMP(lua_error(L));
5344 }
5345 id = lua_tointeger(L, -2);
5346
5347 /* We expect a string as -2. */
5348 if (lua_type(L, -1) != LUA_TSTRING) {
5349 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 +02005350 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005351 name, id,
5352 lua_typename(L, lua_type(L, -1)));
5353 WILL_LJMP(lua_error(L));
5354 }
5355 value = lua_tolstring(L, -1, &vlen);
5356
5357 /* Simple Protocol checks. */
5358 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01005359 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005360 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5361 struct ist v = ist2(value, vlen);
5362 int ret;
5363
5364 ret = h1_parse_cont_len_header(&h1m, &v);
5365 if (ret < 0) {
5366 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005367 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005368 name);
5369 WILL_LJMP(lua_error(L));
5370 }
5371 else if (ret == 0)
5372 goto next; /* Skip it */
5373 }
5374
5375 /* Add a new header */
5376 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5377 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005378 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005379 name);
5380 WILL_LJMP(lua_error(L));
5381 }
5382 next:
5383 /* Remove the array from the stack, and get next element with a remaining string. */
5384 lua_pop(L, 1);
5385 }
5386
5387 /* Remove the array from the stack, and get next element with a remaining string. */
5388 lua_pop(L, 1);
5389 }
5390
5391 if (h1m.flags & H1_MF_CHNK)
5392 h1m.flags &= ~H1_MF_CLEN;
5393 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5394 h1m.flags |= H1_MF_XFER_LEN;
5395
5396 /* Uset HTX start-line flags */
5397 if (h1m.flags & H1_MF_XFER_ENC)
5398 flags |= HTX_SL_F_XFER_ENC;
5399 if (h1m.flags & H1_MF_XFER_LEN) {
5400 flags |= HTX_SL_F_XFER_LEN;
5401 if (h1m.flags & H1_MF_CHNK)
5402 flags |= HTX_SL_F_CHNK;
5403 else if (h1m.flags & H1_MF_CLEN)
5404 flags |= HTX_SL_F_CLEN;
5405 if (h1m.body_len == 0)
5406 flags |= HTX_SL_F_BODYLESS;
5407 }
5408 sl->flags |= flags;
5409
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005410 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005411 * and the status code implies the presence of a message body, we must
5412 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005413 * for the keepalive compliance. If the applet announces a transfer-encoding
5414 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005415 */
5416 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005417 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5418 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5419 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005420 /* Add a new header */
5421 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5422 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5423 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005424 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005425 WILL_LJMP(lua_error(L));
5426 }
5427 }
5428
5429 /* Finalize headers. */
5430 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5431 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005432 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005433 WILL_LJMP(lua_error(L));
5434 }
5435
5436 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5437 b_reset(&res->buf);
5438 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5439 WILL_LJMP(lua_error(L));
5440 }
5441
5442 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005443 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005444
5445 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005446 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005447 return 0;
5448
5449}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005450/* We will build the status line and the headers of the HTTP response.
5451 * We will try send at once if its not possible, we give back the hand
5452 * waiting for more room.
5453 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005454__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005455{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005456 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5457 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005458 struct channel *res = si_ic(si);
5459
5460 if (co_data(res)) {
5461 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005462 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005463 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005464 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005465}
5466
5467
Christopher Fauleta2097962019-07-15 16:25:33 +02005468__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005469{
Christopher Fauleta2097962019-07-15 16:25:33 +02005470 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005471}
5472
Christopher Fauleta2097962019-07-15 16:25:33 +02005473/*
5474 *
5475 *
5476 * Class HTTP
5477 *
5478 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005479 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005480
5481/* Returns a struct hlua_txn if the stack entry "ud" is
5482 * a class stream, otherwise it throws an error.
5483 */
5484__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005485{
Christopher Fauleta2097962019-07-15 16:25:33 +02005486 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5487}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005488
Christopher Fauleta2097962019-07-15 16:25:33 +02005489/* This function creates and push in the stack a HTTP object
5490 * according with a current TXN.
5491 */
5492static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5493{
5494 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005495
Christopher Fauleta2097962019-07-15 16:25:33 +02005496 /* Check stack size. */
5497 if (!lua_checkstack(L, 3))
5498 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005499
Christopher Fauleta2097962019-07-15 16:25:33 +02005500 /* Create the object: obj[0] = userdata.
5501 * Note that the base of the Converters object is the
5502 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005503 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005504 lua_newtable(L);
5505 htxn = lua_newuserdata(L, sizeof(*htxn));
5506 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005507
5508 htxn->s = txn->s;
5509 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005510 htxn->dir = txn->dir;
5511 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005512
5513 /* Pop a class stream metatable and affect it to the table. */
5514 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5515 lua_setmetatable(L, -2);
5516
5517 return 1;
5518}
5519
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005520/* This function creates and returns an array containing the status-line
5521 * elements. This function does not fails.
5522 */
5523__LJMP static int hlua_http_get_stline(lua_State *L, struct htx_sl *sl)
5524{
5525 /* Create the table. */
5526 lua_newtable(L);
5527
5528 if (sl->flags & HTX_SL_F_IS_RESP) {
5529 lua_pushstring(L, "version");
5530 lua_pushlstring(L, HTX_SL_RES_VPTR(sl), HTX_SL_RES_VLEN(sl));
5531 lua_settable(L, -3);
5532 lua_pushstring(L, "code");
5533 lua_pushlstring(L, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));
5534 lua_settable(L, -3);
5535 lua_pushstring(L, "reason");
5536 lua_pushlstring(L, HTX_SL_RES_RPTR(sl), HTX_SL_RES_RLEN(sl));
5537 lua_settable(L, -3);
5538 }
5539 else {
5540 lua_pushstring(L, "method");
5541 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
5542 lua_settable(L, -3);
5543 lua_pushstring(L, "uri");
5544 lua_pushlstring(L, HTX_SL_REQ_UPTR(sl), HTX_SL_REQ_ULEN(sl));
5545 lua_settable(L, -3);
5546 lua_pushstring(L, "version");
5547 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
5548 lua_settable(L, -3);
5549 }
5550 return 1;
5551}
5552
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005553/* This function creates ans returns an array of HTTP headers.
5554 * This function does not fails. It is used as wrapper with the
5555 * 2 following functions.
5556 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005557__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005558{
Christopher Fauleta2097962019-07-15 16:25:33 +02005559 struct htx *htx;
5560 int32_t pos;
5561
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005562 /* Create the table. */
5563 lua_newtable(L);
5564
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005565
Christopher Fauleta2097962019-07-15 16:25:33 +02005566 htx = htxbuf(&msg->chn->buf);
5567 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5568 struct htx_blk *blk = htx_get_blk(htx, pos);
5569 enum htx_blk_type type = htx_get_blk_type(blk);
5570 struct ist n, v;
5571 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005572
Christopher Fauleta2097962019-07-15 16:25:33 +02005573 if (type == HTX_BLK_HDR) {
5574 n = htx_get_blk_name(htx,blk);
5575 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005576 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005577 else if (type == HTX_BLK_EOH)
5578 break;
5579 else
5580 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005581
Christopher Fauleta2097962019-07-15 16:25:33 +02005582 /* Check for existing entry:
5583 * assume that the table is on the top of the stack, and
5584 * push the key in the stack, the function lua_gettable()
5585 * perform the lookup.
5586 */
5587 lua_pushlstring(L, n.ptr, n.len);
5588 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005589
Christopher Fauleta2097962019-07-15 16:25:33 +02005590 switch (lua_type(L, -1)) {
5591 case LUA_TNIL:
5592 /* Table not found, create it. */
5593 lua_pop(L, 1); /* remove the nil value. */
5594 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5595 lua_newtable(L); /* create and push empty table. */
5596 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5597 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5598 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005599 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005600
Christopher Fauleta2097962019-07-15 16:25:33 +02005601 case LUA_TTABLE:
5602 /* Entry found: push the value in the table. */
5603 len = lua_rawlen(L, -1);
5604 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5605 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5606 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5607 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005608
Christopher Fauleta2097962019-07-15 16:25:33 +02005609 default:
5610 /* Other cases are errors. */
5611 hlua_pusherror(L, "internal error during the parsing of headers.");
5612 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005613 }
5614 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005615 return 1;
5616}
5617
5618__LJMP static int hlua_http_req_get_headers(lua_State *L)
5619{
5620 struct hlua_txn *htxn;
5621
5622 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5623 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5624
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005625 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005626 WILL_LJMP(lua_error(L));
5627
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005628 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005629}
5630
5631__LJMP static int hlua_http_res_get_headers(lua_State *L)
5632{
5633 struct hlua_txn *htxn;
5634
5635 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5636 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5637
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005638 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005639 WILL_LJMP(lua_error(L));
5640
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005641 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005642}
5643
5644/* This function replace full header, or just a value in
5645 * the request or in the response. It is a wrapper fir the
5646 * 4 following functions.
5647 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005648__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005649{
5650 size_t name_len;
5651 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5652 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5653 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005654 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005655 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005656
Dragan Dosen26743032019-04-30 15:54:36 +02005657 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005658 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5659
Christopher Fauleta2097962019-07-15 16:25:33 +02005660 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005661 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005662 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005663 return 0;
5664}
5665
5666__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5667{
5668 struct hlua_txn *htxn;
5669
5670 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5671 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5672
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005673 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005674 WILL_LJMP(lua_error(L));
5675
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005676 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005677}
5678
5679__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5680{
5681 struct hlua_txn *htxn;
5682
5683 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5684 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5685
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005686 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005687 WILL_LJMP(lua_error(L));
5688
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005689 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005690}
5691
5692__LJMP static int hlua_http_req_rep_val(lua_State *L)
5693{
5694 struct hlua_txn *htxn;
5695
5696 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5697 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5698
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005699 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005700 WILL_LJMP(lua_error(L));
5701
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005702 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005703}
5704
5705__LJMP static int hlua_http_res_rep_val(lua_State *L)
5706{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005707 struct hlua_txn *htxn;
5708
5709 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5710 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5711
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005712 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005713 WILL_LJMP(lua_error(L));
5714
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005715 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005716}
5717
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005718/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005719 * It is a wrapper for the 2 following functions.
5720 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005721__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005722{
5723 size_t len;
5724 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005725 struct htx *htx = htxbuf(&msg->chn->buf);
5726 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005727
Christopher Fauleta2097962019-07-15 16:25:33 +02005728 ctx.blk = NULL;
5729 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5730 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005731 return 0;
5732}
5733
5734__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5735{
5736 struct hlua_txn *htxn;
5737
5738 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5739 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5740
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005741 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005742 WILL_LJMP(lua_error(L));
5743
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005744 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005745}
5746
5747__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5748{
5749 struct hlua_txn *htxn;
5750
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005751 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005752 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5753
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005754 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005755 WILL_LJMP(lua_error(L));
5756
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005757 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005758}
5759
5760/* This function adds an header. It is a wrapper used by
5761 * the 2 following functions.
5762 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005763__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005764{
5765 size_t name_len;
5766 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5767 size_t value_len;
5768 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005769 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005770
Christopher Fauleta2097962019-07-15 16:25:33 +02005771 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5772 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005773 return 0;
5774}
5775
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005776__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5777{
5778 struct hlua_txn *htxn;
5779
5780 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5781 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5782
5783 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5784 WILL_LJMP(lua_error(L));
5785
5786 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5787}
5788
5789__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5790{
5791 struct hlua_txn *htxn;
5792
5793 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5794 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5795
5796 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5797 WILL_LJMP(lua_error(L));
5798
5799 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5800}
5801
5802static int hlua_http_req_set_hdr(lua_State *L)
5803{
5804 struct hlua_txn *htxn;
5805
5806 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5807 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5808
5809 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5810 WILL_LJMP(lua_error(L));
5811
5812 hlua_http_del_hdr(L, &htxn->s->txn->req);
5813 return hlua_http_add_hdr(L, &htxn->s->txn->req);
5814}
5815
5816static int hlua_http_res_set_hdr(lua_State *L)
5817{
5818 struct hlua_txn *htxn;
5819
5820 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5821 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5822
5823 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5824 WILL_LJMP(lua_error(L));
5825
5826 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5827 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
5828}
5829
5830/* This function set the method. */
5831static int hlua_http_req_set_meth(lua_State *L)
5832{
5833 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5834 size_t name_len;
5835 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5836
5837 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5838 WILL_LJMP(lua_error(L));
5839
5840 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
5841 return 1;
5842}
5843
5844/* This function set the method. */
5845static int hlua_http_req_set_path(lua_State *L)
5846{
5847 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5848 size_t name_len;
5849 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5850
5851 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5852 WILL_LJMP(lua_error(L));
5853
5854 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
5855 return 1;
5856}
5857
5858/* This function set the query-string. */
5859static int hlua_http_req_set_query(lua_State *L)
5860{
5861 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5862 size_t name_len;
5863 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5864
5865 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5866 WILL_LJMP(lua_error(L));
5867
5868 /* Check length. */
5869 if (name_len > trash.size - 1) {
5870 lua_pushboolean(L, 0);
5871 return 1;
5872 }
5873
5874 /* Add the mark question as prefix. */
5875 chunk_reset(&trash);
5876 trash.area[trash.data++] = '?';
5877 memcpy(trash.area + trash.data, name, name_len);
5878 trash.data += name_len;
5879
5880 lua_pushboolean(L,
5881 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
5882 return 1;
5883}
5884
5885/* This function set the uri. */
5886static int hlua_http_req_set_uri(lua_State *L)
5887{
5888 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5889 size_t name_len;
5890 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5891
5892 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
5893 WILL_LJMP(lua_error(L));
5894
5895 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
5896 return 1;
5897}
5898
5899/* This function set the response code & optionally reason. */
5900static int hlua_http_res_set_status(lua_State *L)
5901{
5902 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5903 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
5904 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5905 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
5906
5907 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
5908 WILL_LJMP(lua_error(L));
5909
5910 http_res_set_status(code, reason, htxn->s);
5911 return 0;
5912}
5913
5914/*
5915 *
5916 *
5917 * Class HTTPMessage
5918 *
5919 *
5920 */
5921
5922/* Returns a struct http_msg if the stack entry "ud" is a class HTTPMessage,
5923 * otherwise it throws an error.
5924 */
5925__LJMP static struct http_msg *hlua_checkhttpmsg(lua_State *L, int ud)
5926{
5927 return MAY_LJMP(hlua_checkudata(L, ud, class_http_msg_ref));
5928}
5929
5930/* Creates and pushes on the stack a HTTP object according with a current TXN.
5931 */
Christopher Faulet78c35472020-02-26 17:14:08 +01005932static int hlua_http_msg_new(lua_State *L, struct http_msg *msg)
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005933{
5934 /* Check stack size. */
5935 if (!lua_checkstack(L, 3))
5936 return 0;
5937
5938 lua_newtable(L);
5939 lua_pushlightuserdata(L, msg);
5940 lua_rawseti(L, -2, 0);
5941
5942 /* Create the "channel" field that contains the request channel object. */
5943 lua_pushstring(L, "channel");
5944 if (!hlua_channel_new(L, msg->chn))
5945 return 0;
5946 lua_rawset(L, -3);
5947
5948 /* Pop a class stream metatable and affect it to the table. */
5949 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_msg_ref);
5950 lua_setmetatable(L, -2);
5951
5952 return 1;
5953}
5954
5955/* Helper function returning a filter attached to the HTTP message at the
5956 * position <ud> in the stack, filling the current offset and length of the
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05005957 * filter. If no filter is attached, NULL is returned and <offset> and <len> are
Christopher Fauletdf97ac42020-02-26 16:57:19 +01005958 * filled with output and input length respectively.
5959 */
5960static struct filter *hlua_http_msg_filter(lua_State *L, int ud, struct http_msg *msg, size_t *offset, size_t *len)
5961{
5962 struct channel *chn = msg->chn;
5963 struct htx *htx = htxbuf(&chn->buf);
5964 struct filter *filter = NULL;
5965
5966 *offset = co_data(msg->chn);
5967 *len = htx->data - co_data(msg->chn);
5968
5969 if (lua_getfield(L, ud, "__filter") == LUA_TLIGHTUSERDATA) {
5970 filter = lua_touserdata (L, -1);
5971 if (msg->msg_state >= HTTP_MSG_DATA) {
5972 struct hlua_flt_ctx *flt_ctx = filter->ctx;
5973
5974 *offset = flt_ctx->cur_off[CHN_IDX(chn)];
5975 *len = flt_ctx->cur_len[CHN_IDX(chn)];
5976 }
5977 }
5978
5979 lua_pop(L, 1);
5980 return filter;
5981}
5982
5983/* Returns true if the channel attached to the HTTP message is the response
5984 * channel.
5985 */
5986__LJMP static int hlua_http_msg_is_resp(lua_State *L)
5987{
5988 struct http_msg *msg;
5989
5990 MAY_LJMP(check_args(L, 1, "is_resp"));
5991 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
5992
5993 lua_pushboolean(L, !!(msg->chn->flags & CF_ISRESP));
5994 return 1;
5995}
5996
5997/* Returns an array containing the elements status-line of the HTTP message. It relies
5998 * on hlua_http_get_stline().
5999 */
6000__LJMP static int hlua_http_msg_get_stline(lua_State *L)
6001{
6002 struct http_msg *msg;
6003 struct htx *htx;
6004 struct htx_sl *sl;
6005
6006 MAY_LJMP(check_args(L, 1, "get_stline"));
6007 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6008
6009 if (msg->msg_state > HTTP_MSG_BODY)
6010 WILL_LJMP(lua_error(L));
6011
6012 htx = htxbuf(&msg->chn->buf);
6013 sl = http_get_stline(htx);
6014 if (!sl)
6015 return 0;
6016 return hlua_http_get_stline(L, sl);
6017}
6018
6019/* Returns an array containing all headers of the HTTP message. it relies on
6020 * hlua_http_get_headers().
6021 */
6022__LJMP static int hlua_http_msg_get_headers(lua_State *L)
6023{
6024 struct http_msg *msg;
6025
6026 MAY_LJMP(check_args(L, 1, "get_headers"));
6027 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6028
6029 if (msg->msg_state > HTTP_MSG_BODY)
6030 WILL_LJMP(lua_error(L));
6031
6032 return hlua_http_get_headers(L, msg);
6033}
6034
6035/* Deletes all occurrences of an header in the HTTP message matching on its
6036 * name. It relies on hlua_http_del_hdr().
6037 */
6038__LJMP static int hlua_http_msg_del_hdr(lua_State *L)
6039{
6040 struct http_msg *msg;
6041
6042 MAY_LJMP(check_args(L, 2, "del_header"));
6043 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6044
6045 if (msg->msg_state > HTTP_MSG_BODY)
6046 WILL_LJMP(lua_error(L));
6047
6048 return hlua_http_del_hdr(L, msg);
6049}
6050
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006051/* Matches the full value line of all occurrences of an header in the HTTP
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006052 * message given its name against a regex and replaces it if it matches. It
6053 * relies on hlua_http_rep_hdr().
6054 */
6055__LJMP static int hlua_http_msg_rep_hdr(lua_State *L)
6056{
6057 struct http_msg *msg;
6058
6059 MAY_LJMP(check_args(L, 4, "rep_header"));
6060 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6061
6062 if (msg->msg_state > HTTP_MSG_BODY)
6063 WILL_LJMP(lua_error(L));
6064
6065 return hlua_http_rep_hdr(L, msg, 1);
6066}
6067
6068/* Matches all comma-separated values of all occurences of an header in the HTTP
6069 * message given its name against a regex and replaces it if it matches. It
6070 * relies on hlua_http_rep_hdr().
6071 */
6072__LJMP static int hlua_http_msg_rep_val(lua_State *L)
6073{
6074 struct http_msg *msg;
6075
6076 MAY_LJMP(check_args(L, 4, "rep_value"));
6077 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6078
6079 if (msg->msg_state > HTTP_MSG_BODY)
6080 WILL_LJMP(lua_error(L));
6081
6082 return hlua_http_rep_hdr(L, msg, 0);
6083}
6084
6085/* Add an header in the HTTP message. It relies on hlua_http_add_hdr() */
6086__LJMP static int hlua_http_msg_add_hdr(lua_State *L)
6087{
6088 struct http_msg *msg;
6089
6090 MAY_LJMP(check_args(L, 3, "add_header"));
6091 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6092
6093 if (msg->msg_state > HTTP_MSG_BODY)
6094 WILL_LJMP(lua_error(L));
6095
6096 return hlua_http_add_hdr(L, msg);
6097}
6098
6099/* Add an header in the HTTP message removing existing headers with the same
6100 * name. It relies on hlua_http_del_hdr() and hlua_http_add_hdr().
6101 */
6102__LJMP static int hlua_http_msg_set_hdr(lua_State *L)
6103{
6104 struct http_msg *msg;
6105
6106 MAY_LJMP(check_args(L, 3, "set_header"));
6107 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6108
6109 if (msg->msg_state > HTTP_MSG_BODY)
6110 WILL_LJMP(lua_error(L));
6111
6112 hlua_http_del_hdr(L, msg);
6113 return hlua_http_add_hdr(L, msg);
6114}
6115
6116/* Rewrites the request method. It relies on http_req_replace_stline(). */
6117__LJMP static int hlua_http_msg_set_meth(lua_State *L)
6118{
6119 struct stream *s;
6120 struct http_msg *msg;
6121 const char *name;
6122 size_t name_len;
6123
6124 MAY_LJMP(check_args(L, 2, "set_method"));
6125 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6126 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6127
6128 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6129 WILL_LJMP(lua_error(L));
6130
6131 s = chn_strm(msg->chn);
6132 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, s->be, s) != -1);
6133 return 1;
6134}
6135
6136/* Rewrites the request path. It relies on http_req_replace_stline(). */
6137__LJMP static int hlua_http_msg_set_path(lua_State *L)
6138{
6139 struct stream *s;
6140 struct http_msg *msg;
6141 const char *name;
6142 size_t name_len;
6143
6144 MAY_LJMP(check_args(L, 2, "set_path"));
6145 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6146 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6147
6148 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6149 WILL_LJMP(lua_error(L));
6150
6151 s = chn_strm(msg->chn);
6152 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, s->be, s) != -1);
6153 return 1;
6154}
6155
6156/* Rewrites the request query-string. It relies on http_req_replace_stline(). */
6157__LJMP static int hlua_http_msg_set_query(lua_State *L)
6158{
6159 struct stream *s;
6160 struct http_msg *msg;
6161 const char *name;
6162 size_t name_len;
6163
6164 MAY_LJMP(check_args(L, 2, "set_query"));
6165 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6166 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6167
6168 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6169 WILL_LJMP(lua_error(L));
6170
6171 /* Check length. */
6172 if (name_len > trash.size - 1) {
6173 lua_pushboolean(L, 0);
6174 return 1;
6175 }
6176
6177 /* Add the mark question as prefix. */
6178 chunk_reset(&trash);
6179 trash.area[trash.data++] = '?';
6180 memcpy(trash.area + trash.data, name, name_len);
6181 trash.data += name_len;
6182
6183 s = chn_strm(msg->chn);
6184 lua_pushboolean(L, http_req_replace_stline(2, trash.area, trash.data, s->be, s) != -1);
6185 return 1;
6186}
6187
6188/* Rewrites the request URI. It relies on http_req_replace_stline(). */
6189__LJMP static int hlua_http_msg_set_uri(lua_State *L)
6190{
6191 struct stream *s;
6192 struct http_msg *msg;
6193 const char *name;
6194 size_t name_len;
6195
6196 MAY_LJMP(check_args(L, 2, "set_uri"));
6197 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6198 name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
6199
6200 if ((msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6201 WILL_LJMP(lua_error(L));
6202
6203 s = chn_strm(msg->chn);
6204 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, s->be, s) != -1);
6205 return 1;
6206}
6207
6208/* Rewrites the response status code. It relies on http_res_set_status(). */
6209__LJMP static int hlua_http_msg_set_status(lua_State *L)
6210{
6211 struct http_msg *msg;
6212 unsigned int code;
6213 const char *reason;
6214 size_t reason_len;
6215
6216 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6217 code = MAY_LJMP(luaL_checkinteger(L, 2));
6218 reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, &reason_len));
6219
6220 if (!(msg->chn->flags & CF_ISRESP) || msg->msg_state > HTTP_MSG_BODY)
6221 WILL_LJMP(lua_error(L));
6222
6223 lua_pushboolean(L, http_res_set_status(code, ist2(reason, reason_len), chn_strm(msg->chn)) != -1);
6224 return 1;
6225}
6226
6227/* Returns true if the HTTP message is full. */
6228__LJMP static int hlua_http_msg_is_full(lua_State *L)
6229{
6230 struct http_msg *msg;
6231
6232 MAY_LJMP(check_args(L, 1, "is_full"));
6233 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6234 lua_pushboolean(L, channel_full(msg->chn, 0));
6235 return 1;
6236}
6237
6238/* Returns true if the HTTP message may still receive data. */
6239__LJMP static int hlua_http_msg_may_recv(lua_State *L)
6240{
6241 struct http_msg *msg;
6242 struct htx *htx;
6243
6244 MAY_LJMP(check_args(L, 1, "may_recv"));
6245 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6246 htx = htxbuf(&msg->chn->buf);
6247 lua_pushboolean(L, (htx_expect_more(htx) && !channel_input_closed(msg->chn) && channel_may_recv(msg->chn)));
6248 return 1;
6249}
6250
6251/* Returns true if the HTTP message EOM was received */
6252__LJMP static int hlua_http_msg_is_eom(lua_State *L)
6253{
6254 struct http_msg *msg;
6255 struct htx *htx;
6256
6257 MAY_LJMP(check_args(L, 1, "may_recv"));
6258 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6259 htx = htxbuf(&msg->chn->buf);
6260 lua_pushboolean(L, !htx_expect_more(htx));
6261 return 1;
6262}
6263
6264/* Returns the number of bytes available in the input side of the HTTP
6265 * message. This function never fails.
6266 */
6267__LJMP static int hlua_http_msg_get_in_len(lua_State *L)
6268{
6269 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006270 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006271
6272 MAY_LJMP(check_args(L, 1, "input"));
6273 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006274 hlua_http_msg_filter(L, 1, msg, &output, &input);
6275 lua_pushinteger(L, input);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006276 return 1;
6277}
6278
6279/* Returns the number of bytes available in the output side of the HTTP
6280 * message. This function never fails.
6281 */
6282__LJMP static int hlua_http_msg_get_out_len(lua_State *L)
6283{
6284 struct http_msg *msg;
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006285 size_t output, input;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006286
6287 MAY_LJMP(check_args(L, 1, "output"));
6288 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Christopher Fauleteae8afa2020-02-26 17:15:48 +01006289 hlua_http_msg_filter(L, 1, msg, &output, &input);
6290 lua_pushinteger(L, output);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006291 return 1;
6292}
6293
6294/* Copies at most <len> bytes of DATA blocks from the HTTP message <msg>
6295 * starting at the offset <offset> and put it in a string LUA variables. It
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006296 * returns the built string length. It stops on the first non-DATA HTX
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006297 * block. This function is called during the payload filtering, so the headers
6298 * are already scheduled for output (from the filter point of view).
6299 */
6300static int _hlua_http_msg_dup(struct http_msg *msg, lua_State *L, size_t offset, size_t len)
6301{
6302 struct htx *htx = htxbuf(&msg->chn->buf);
6303 struct htx_blk *blk;
6304 struct htx_ret htxret;
6305 luaL_Buffer b;
6306 int ret = 0;
6307
6308 luaL_buffinit(L, &b);
6309 htxret = htx_find_offset(htx, offset);
6310 for (blk = htxret.blk, offset = htxret.ret; blk && len; blk = htx_get_next_blk(htx, blk)) {
6311 enum htx_blk_type type = htx_get_blk_type(blk);
6312 struct ist v;
6313
6314 switch (type) {
6315 case HTX_BLK_UNUSED:
6316 break;
6317
6318 case HTX_BLK_DATA:
6319 v = htx_get_blk_value(htx, blk);
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006320 v = istadv(v, offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006321 if (v.len > len)
6322 v.len = len;
6323
6324 luaL_addlstring(&b, v.ptr, v.len);
6325 ret += v.len;
6326 break;
6327
6328 default:
6329 if (!ret) {
6330 /* Remove the empty string and push nil on the stack */
6331 lua_pop(L, 1);
6332 lua_pushnil(L);
6333 }
6334 goto end;
6335 }
6336 offset = 0;
6337 }
6338
6339 luaL_pushresult(&b);
6340
6341end:
6342 return ret;
6343}
6344
6345/* Copies the string <str> to the HTTP message <msg> at the offset
6346 * <offset>. This function returns -1 if data cannot be copied. Otherwise, it
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006347 * returns the amount of data written. This function is responsible to update
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006348 * the filter context.
6349 */
6350static int _hlua_http_msg_insert(struct http_msg *msg, struct filter *filter, struct ist str, size_t offset)
6351{
6352 struct htx *htx = htx_from_buf(&msg->chn->buf);
6353 struct htx_ret htxret;
6354 int /*max, */ret = 0;
6355
6356 /* Nothing to do, just return */
6357 if (unlikely(istlen(str) == 0))
6358 goto end;
6359
6360 if (istlen(str) > htx_free_data_space(htx)) {
6361 ret = -1;
6362 goto end;
6363 }
6364
6365 htxret = htx_find_offset(htx, offset);
6366 if (!htxret.blk || htx_get_blk_type(htxret.blk) != HTX_BLK_DATA) {
6367 if (!htx_add_last_data(htx, str))
6368 goto end;
6369 }
6370 else {
6371 struct ist v = htx_get_blk_value(htx, htxret.blk);
6372 v.ptr += htxret.ret;
6373 v.len = 0;
6374 if (!htx_replace_blk_value(htx, htxret.blk, v, str))
6375 goto end;
6376 }
6377 ret = str.len;
6378 if (ret) {
6379 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6380 flt_update_offsets(filter, msg->chn, ret);
6381 flt_ctx->cur_len[CHN_IDX(msg->chn)] += ret;
6382 }
6383
6384 end:
6385 htx_to_buf(htx, &msg->chn->buf);
6386 return ret;
6387}
6388
6389/* Helper function removing at most <len> bytes of DATA blocks at the absolute
6390 * position <offset>. It stops on the first non-DATA HTX block. This function is
6391 * called during the payload filtering, so the headers are already scheduled for
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006392 * output (from the filter point of view). This function is responsible to
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006393 * update the filter context.
6394 */
6395static void _hlua_http_msg_delete(struct http_msg *msg, struct filter *filter, size_t offset, size_t len)
6396{
6397 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6398 struct htx *htx = htx_from_buf(&msg->chn->buf);
6399 struct htx_blk *blk;
6400 struct htx_ret htxret;
6401 size_t ret = 0;
6402
6403 /* Be sure <len> is always the amount of DATA to remove */
6404 if (htx->data == offset+len && htx_get_tail_type(htx) == HTX_BLK_DATA) {
6405 htx_truncate(htx, offset);
6406 ret = len;
6407 goto end;
6408 }
6409
6410 htxret = htx_find_offset(htx, offset);
6411 blk = htxret.blk;
6412 if (htxret.ret) {
6413 struct ist v;
6414
6415 if (htx_get_blk_type(blk) != HTX_BLK_DATA)
6416 goto end;
6417 v = htx_get_blk_value(htx, blk);
6418 v.ptr += htxret.ret;
6419 if (v.len > len)
6420 v.len = len;
Tim Duesterhusb113b5c2021-09-15 13:58:44 +02006421 blk = htx_replace_blk_value(htx, blk, v, IST_NULL);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006422 len -= v.len;
6423 ret += v.len;
6424 }
6425
6426
6427 while (blk && len) {
6428 enum htx_blk_type type = htx_get_blk_type(blk);
6429 uint32_t sz = htx_get_blksz(blk);
6430
6431 switch (type) {
6432 case HTX_BLK_UNUSED:
6433 break;
6434
6435 case HTX_BLK_DATA:
6436 if (len < sz) {
6437 htx_cut_data_blk(htx, blk, len);
6438 ret += len;
6439 goto end;
6440 }
6441 break;
6442
6443 default:
6444 goto end;
6445 }
6446
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006447 /* Remove all the data block */
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006448 len -= sz;
6449 ret += sz;
6450 blk = htx_remove_blk(htx, blk);
6451 }
6452
6453end:
6454 flt_update_offsets(filter, msg->chn, -ret);
6455 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6456 /* WARNING: we don't call htx_to_buf() on purpose, because we don't want
6457 * to loose the EOM flag if the message is empty.
6458 */
6459}
6460
6461/* Copies input data found in an HTTP message. Unlike the channel function used
6462 * to duplicate raw data, this one can only be called inside a filter, from
6463 * http_payload callback. So it cannot yield. An exception is returned if it is
6464 * called from another callback. If nothing was copied, a nil value is pushed on
6465 * the stack.
6466 */
6467__LJMP static int hlua_http_msg_get_body(lua_State *L)
6468{
6469 struct http_msg *msg;
6470 struct filter *filter;
6471 size_t output, input;
6472 int offset, len;
6473
6474 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6475 WILL_LJMP(luaL_error(L, "'data' expects at most 2 arguments"));
6476 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6477
6478 if (msg->msg_state < HTTP_MSG_DATA)
6479 WILL_LJMP(lua_error(L));
6480
6481 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6482 if (!filter || !hlua_filter_from_payload(filter))
6483 WILL_LJMP(lua_error(L));
6484
6485 if (!ci_data(msg->chn) && channel_input_closed(msg->chn)) {
6486 lua_pushnil(L);
6487 return 1;
6488 }
6489
6490 offset = output;
6491 if (lua_gettop(L) > 1) {
6492 offset = MAY_LJMP(luaL_checkinteger(L, 2));
6493 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006494 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006495 offset += output;
6496 if (offset < output || offset > input + output) {
6497 lua_pushfstring(L, "offset out of range.");
6498 WILL_LJMP(lua_error(L));
6499 }
6500 }
6501 len = output + input - offset;
6502 if (lua_gettop(L) == 3) {
6503 len = MAY_LJMP(luaL_checkinteger(L, 3));
6504 if (!len)
6505 goto dup;
6506 if (len == -1)
6507 len = global.tune.bufsize;
6508 if (len < 0) {
6509 lua_pushfstring(L, "length out of range.");
6510 WILL_LJMP(lua_error(L));
6511 }
6512 }
6513
6514 dup:
6515 _hlua_http_msg_dup(msg, L, offset, len);
6516 return 1;
6517}
6518
6519/* Appends a string to the HTTP message, after all existing DATA blocks but
6520 * before the trailers, if any. It returns the amount of data written or -1 if
6521 * nothing was copied. Unlike the channel function used to append data, this one
6522 * can only be called inside a filter, from http_payload callback. So it cannot
6523 * yield. An exception is returned if it is called from another callback.
6524 */
6525__LJMP static int hlua_http_msg_append(lua_State *L)
6526{
6527 struct http_msg *msg;
6528 struct filter *filter;
6529 const char *str;
6530 size_t offset, len, sz;
6531 int ret;
6532
6533 MAY_LJMP(check_args(L, 2, "append"));
6534 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6535
6536 if (msg->msg_state < HTTP_MSG_DATA)
6537 WILL_LJMP(lua_error(L));
6538
6539 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6540 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6541 if (!filter || !hlua_filter_from_payload(filter))
6542 WILL_LJMP(lua_error(L));
6543
6544 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset+len);
6545 lua_pushinteger(L, ret);
6546 return 1;
6547}
6548
6549/* Prepends a string to the HTTP message, before all existing DATA blocks. It
6550 * returns the amount of data written or -1 if nothing was copied. Unlike the
6551 * channel function used to prepend data, this one can only be called inside a
6552 * filter, from http_payload callback. So it cannot yield. An exception is
6553 * returned if it is called from another callback.
6554 */
6555__LJMP static int hlua_http_msg_prepend(lua_State *L)
6556{
6557 struct http_msg *msg;
6558 struct filter *filter;
6559 const char *str;
6560 size_t offset, len, sz;
6561 int ret;
6562
6563 MAY_LJMP(check_args(L, 2, "prepend"));
6564 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006565
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006566 if (msg->msg_state < HTTP_MSG_DATA)
6567 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006568
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006569 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6570 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6571 if (!filter || !hlua_filter_from_payload(filter))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006572 WILL_LJMP(lua_error(L));
6573
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006574 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6575 lua_pushinteger(L, ret);
6576 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006577}
6578
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006579/* Inserts a string to the HTTP message at a given offset. By default the string
6580 * is appended at the end of DATA blocks. It returns the amount of data written
6581 * or -1 if nothing was copied. Unlike the channel function used to insert data,
6582 * this one can only be called inside a filter, from http_payload callback. So
6583 * it cannot yield. An exception is returned if it is called from another
6584 * callback.
6585 */
6586__LJMP static int hlua_http_msg_insert_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006587{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006588 struct http_msg *msg;
6589 struct filter *filter;
6590 const char *str;
6591 size_t input, output, sz;
6592 int offset;
6593 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006594
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006595 if (lua_gettop(L) < 2 || lua_gettop(L) > 3)
6596 WILL_LJMP(luaL_error(L, "'insert' expects at least 1 argument and at most 2 arguments"));
6597 MAY_LJMP(check_args(L, 2, "insert"));
6598 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006599
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006600 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006601 WILL_LJMP(lua_error(L));
6602
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006603 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6604 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6605 if (!filter || !hlua_filter_from_payload(filter))
6606 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006607
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006608 offset = input + output;
6609 if (lua_gettop(L) > 2) {
6610 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6611 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006612 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006613 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006614 if (offset < output || offset > output + input) {
6615 lua_pushfstring(L, "offset out of range.");
6616 WILL_LJMP(lua_error(L));
6617 }
6618 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006619
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006620 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6621 lua_pushinteger(L, ret);
6622 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006623}
6624
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006625/* Removes a given amount of data from the HTTP message at a given offset. By
6626 * default all DATA blocks are removed. It returns the amount of data
6627 * removed. Unlike the channel function used to remove data, this one can only
6628 * be called inside a filter, from http_payload callback. So it cannot yield. An
6629 * exception is returned if it is called from another callback.
6630 */
6631__LJMP static int hlua_http_msg_del_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006632{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006633 struct http_msg *msg;
6634 struct filter *filter;
6635 size_t input, output;
6636 int offset, len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006637
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006638 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
6639 WILL_LJMP(luaL_error(L, "'insert' expects at most 2 arguments"));
6640 MAY_LJMP(check_args(L, 2, "insert"));
6641 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006642
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006643 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006644 WILL_LJMP(lua_error(L));
6645
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006646 filter = hlua_http_msg_filter(L, 1, msg, &input, &output);
6647 if (!filter || !hlua_filter_from_payload(filter))
6648 WILL_LJMP(lua_error(L));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006649
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006650 offset = input + output;
6651 if (lua_gettop(L) > 2) {
6652 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6653 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006654 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006655 offset += output;
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006656 if (offset < output || offset > output + input) {
6657 lua_pushfstring(L, "offset out of range.");
6658 WILL_LJMP(lua_error(L));
6659 }
6660 }
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006661
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006662 len = output + input - offset;
6663 if (lua_gettop(L) == 4) {
6664 len = MAY_LJMP(luaL_checkinteger(L, 4));
6665 if (!len)
6666 goto end;
6667 if (len == -1)
6668 len = output + input - offset;
6669 if (len < 0 || offset + len > output + input) {
6670 lua_pushfstring(L, "length out of range.");
6671 WILL_LJMP(lua_error(L));
6672 }
6673 }
6674
6675 _hlua_http_msg_delete(msg, filter, offset, len);
6676
6677 end:
6678 lua_pushinteger(L, len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006679 return 1;
6680}
6681
Ilya Shipitsinff0f2782021-08-22 22:18:07 +05006682/* Replaces a given amount of data at the given offset by a string. By default,
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006683 * all remaining data are removed, accordingly to the filter context. It returns
6684 * the amount of data written or -1 if nothing was copied. Unlike the channel
6685 * function used to replace data, this one can only be called inside a filter,
6686 * from http_payload callback. So it cannot yield. An exception is returned if
6687 * it is called from another callback.
6688 */
6689__LJMP static int hlua_http_msg_set_data(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006690{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006691 struct http_msg *msg;
6692 struct filter *filter;
6693 struct htx *htx;
6694 const char *str;
6695 size_t input, output, sz;
6696 int offset, len;
6697 int ret;
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02006698
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006699 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
6700 WILL_LJMP(luaL_error(L, "'set' expects at least 1 argument and at most 3 arguments"));
6701 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6702
6703 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006704 WILL_LJMP(lua_error(L));
6705
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006706 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6707 filter = hlua_http_msg_filter(L, 1, msg, &output, &input);
6708 if (!filter || !hlua_filter_from_payload(filter))
6709 WILL_LJMP(lua_error(L));
6710
6711 offset = output;
6712 if (lua_gettop(L) > 2) {
6713 offset = MAY_LJMP(luaL_checkinteger(L, 3));
6714 if (offset < 0)
Christopher Faulet70c43452021-08-13 08:11:00 +02006715 offset = MAX(0, (int)input + offset);
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006716 offset += output;
6717 if (offset < output || offset > input + output) {
6718 lua_pushfstring(L, "offset out of range.");
6719 WILL_LJMP(lua_error(L));
6720 }
6721 }
6722
6723 len = output + input - offset;
6724 if (lua_gettop(L) == 4) {
6725 len = MAY_LJMP(luaL_checkinteger(L, 4));
6726 if (!len)
6727 goto set;
6728 if (len == -1)
6729 len = output + input - offset;
6730 if (len < 0 || offset + len > output + input) {
6731 lua_pushfstring(L, "length out of range.");
6732 WILL_LJMP(lua_error(L));
6733 }
6734 }
6735
6736 set:
6737 /* Be sure we can copied the string once input data will be removed. */
6738 htx = htx_from_buf(&msg->chn->buf);
6739 if (sz > htx_free_data_space(htx) + len)
6740 lua_pushinteger(L, -1);
6741 else {
6742 _hlua_http_msg_delete(msg, filter, offset, len);
6743 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6744 lua_pushinteger(L, ret);
6745 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006746 return 1;
6747}
6748
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006749/* Prepends data into an HTTP message and forward it, from the filter point of
6750 * view. It returns the amount of data written or -1 if nothing was sent. Unlike
6751 * the channel function used to send data, this one can only be called inside a
6752 * filter, from http_payload callback. So it cannot yield. An exception is
6753 * returned if it is called from another callback.
6754 */
6755__LJMP static int hlua_http_msg_send(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006756{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006757 struct http_msg *msg;
6758 struct filter *filter;
6759 struct htx *htx;
6760 const char *str;
6761 size_t offset, len, sz;
6762 int ret;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006763
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006764 MAY_LJMP(check_args(L, 2, "send"));
6765 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6766
6767 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006768 WILL_LJMP(lua_error(L));
6769
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006770 str = MAY_LJMP(luaL_checklstring(L, 2, &sz));
6771 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6772 if (!filter || !hlua_filter_from_payload(filter))
6773 WILL_LJMP(lua_error(L));
6774
6775 /* Return an error if the channel's output is closed */
6776 if (unlikely(channel_output_closed(msg->chn))) {
6777 lua_pushinteger(L, -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006778 return 1;
6779 }
6780
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006781 htx = htx_from_buf(&msg->chn->buf);
6782 if (sz > htx_free_data_space(htx)) {
6783 lua_pushinteger(L, -1);
6784 return 1;
6785 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006786
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006787 ret = _hlua_http_msg_insert(msg, filter, ist2(str, sz), offset);
6788 if (ret > 0) {
6789 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6790
6791 FLT_OFF(filter, msg->chn) += ret;
6792 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6793 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6794 }
6795
6796 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006797 return 1;
6798}
6799
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006800/* Forwards a given amount of bytes. It return -1 if the channel's output is
6801 * closed. Otherwise, it returns the number of bytes forwarded. Unlike the
6802 * channel function used to forward data, this one can only be called inside a
6803 * filter, from http_payload callback. So it cannot yield. An exception is
6804 * returned if it is called from another callback. All other functions deal with
6805 * DATA block, this one not.
6806*/
6807__LJMP static int hlua_http_msg_forward(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006808{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006809 struct http_msg *msg;
6810 struct filter *filter;
6811 size_t offset, len;
6812 int fwd, ret = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006813
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006814 MAY_LJMP(check_args(L, 2, "forward"));
6815 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6816
6817 if (msg->msg_state < HTTP_MSG_DATA)
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006818 WILL_LJMP(lua_error(L));
6819
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006820 fwd = MAY_LJMP(luaL_checkinteger(L, 2));
6821 filter = hlua_http_msg_filter(L, 1, msg, &offset, &len);
6822 if (!filter || !hlua_filter_from_payload(filter))
6823 WILL_LJMP(lua_error(L));
6824
6825 /* Nothing to do, just return */
6826 if (!fwd)
6827 goto end;
6828
6829 /* Return an error if the channel's output is closed */
6830 if (unlikely(channel_output_closed(msg->chn))) {
6831 ret = -1;
6832 goto end;
6833 }
6834
6835 ret = fwd;
6836 if (ret > len)
6837 ret = len;
6838
6839 if (ret) {
6840 struct hlua_flt_ctx *flt_ctx = filter->ctx;
6841
6842 FLT_OFF(filter, msg->chn) += ret;
6843 flt_ctx->cur_off[CHN_IDX(msg->chn)] += ret;
6844 flt_ctx->cur_len[CHN_IDX(msg->chn)] -= ret;
6845 }
6846
6847 end:
6848 lua_pushinteger(L, ret);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006849 return 1;
6850}
6851
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006852/* Set EOM flag on the HTX message.
6853 *
6854 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6855 * really know how to do without this feature.
6856 */
6857__LJMP static int hlua_http_msg_set_eom(lua_State *L)
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006858{
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006859 struct http_msg *msg;
6860 struct htx *htx;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006861
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006862 MAY_LJMP(check_args(L, 1, "set_eom"));
6863 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6864 htx = htxbuf(&msg->chn->buf);
6865 htx->flags |= HTX_FL_EOM;
6866 return 0;
6867}
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02006868
Christopher Fauletdf97ac42020-02-26 16:57:19 +01006869/* Unset EOM flag on the HTX message.
6870 *
6871 * NOTE: Not sure it is a good idea to manipulate this flag but for now I don't
6872 * really know how to do without this feature.
6873 */
6874__LJMP static int hlua_http_msg_unset_eom(lua_State *L)
6875{
6876 struct http_msg *msg;
6877 struct htx *htx;
6878
6879 MAY_LJMP(check_args(L, 1, "set_eom"));
6880 msg = MAY_LJMP(hlua_checkhttpmsg(L, 1));
6881 htx = htxbuf(&msg->chn->buf);
6882 htx->flags &= ~HTX_FL_EOM;
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006883 return 0;
6884}
6885
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006886/*
6887 *
6888 *
William Lallemand3956c4e2021-09-21 16:25:15 +02006889 * Class HTTPClient
6890 *
6891 *
6892 */
6893__LJMP static struct hlua_httpclient *hlua_checkhttpclient(lua_State *L, int ud)
6894{
6895 return MAY_LJMP(hlua_checkudata(L, ud, class_httpclient_ref));
6896}
6897
6898__LJMP static int hlua_httpclient_new(lua_State *L)
6899{
6900 struct hlua_httpclient *hlua_hc;
6901 struct hlua *hlua;
6902
6903 /* Get hlua struct, or NULL if we execute from main lua state */
6904 hlua = hlua_gethlua(L);
6905 if (!hlua)
6906 return 0;
6907
6908 /* Check stack size. */
6909 if (!lua_checkstack(L, 3)) {
6910 hlua_pusherror(L, "httpclient: full stack");
6911 goto err;
6912 }
6913 /* Create the object: obj[0] = userdata. */
6914 lua_newtable(L);
6915 hlua_hc = MAY_LJMP(lua_newuserdata(L, sizeof(*hlua_hc)));
6916 lua_rawseti(L, -2, 0);
6917 memset(hlua_hc, 0, sizeof(*hlua_hc));
6918
6919 hlua_hc->hc = httpclient_new(hlua, 0, IST_NULL);
6920 if (!hlua_hc->hc)
6921 goto err;
6922
6923 /* Pop a class stream metatable and affect it to the userdata. */
6924 lua_rawgeti(L, LUA_REGISTRYINDEX, class_httpclient_ref);
6925 lua_setmetatable(L, -2);
6926
6927 return 1;
6928
6929 err:
6930 WILL_LJMP(lua_error(L));
6931 return 0;
6932}
6933
6934
6935/*
6936 * Callback of the httpclient, this callback wakes the lua task up, once the
6937 * httpclient receives some data
6938 *
6939 */
6940
6941static void hlua_httpclient_res_cb(struct httpclient *hc)
6942{
6943 struct hlua *hlua = hc->caller;
6944
6945 if (!hlua || !hlua->task)
6946 return;
6947
6948 task_wakeup(hlua->task, TASK_WOKEN_MSG);
6949}
6950
6951/*
6952 * For each yield, checks if there is some data in the httpclient and push them
6953 * in the lua buffer, once the httpclient finished its job, push the result on
6954 * the stack
6955 */
6956__LJMP static int hlua_httpclient_get_yield(lua_State *L, int status, lua_KContext ctx)
6957{
6958 struct buffer *tr;
6959 int res;
6960 struct hlua *hlua = hlua_gethlua(L);
6961 struct hlua_httpclient *hlua_hc = hlua_checkhttpclient(L, 1);
6962
6963
6964 tr = get_trash_chunk();
6965
6966 res = httpclient_res_xfer(hlua_hc->hc, tr);
6967 luaL_addlstring(&hlua_hc->b, b_orig(tr), res);
6968
6969 if (!httpclient_data(hlua_hc->hc) && httpclient_ended(hlua_hc->hc)) {
6970
6971 luaL_pushresult(&hlua_hc->b);
6972 lua_settable(L, -3);
6973
6974 lua_pushstring(L, "status");
6975 lua_pushinteger(L, hlua_hc->hc->res.status);
6976 lua_settable(L, -3);
6977
6978
6979 lua_pushstring(L, "reason");
6980 lua_pushlstring(L, hlua_hc->hc->res.reason.ptr, hlua_hc->hc->res.reason.len);
6981 lua_settable(L, -3);
6982
6983 return 1;
6984 }
6985
6986 if (httpclient_data(hlua_hc->hc))
6987 task_wakeup(hlua->task, TASK_WOKEN_MSG);
6988
6989
6990 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_get_yield, TICK_ETERNITY, 0));
6991 return 0;
6992}
6993
6994/*
6995 * Sends and receive an HTTP request
6996 *
6997 * httpclient.get(url, headers)
6998 */
6999
7000__LJMP static int hlua_httpclient_get(lua_State *L)
7001{
7002 struct hlua_httpclient *hlua_hc;
7003 struct hlua *hlua;
7004 const char *url_str;
7005
7006 hlua = hlua_gethlua(L);
7007
7008 if (!hlua || !hlua->task)
7009 WILL_LJMP(luaL_error(L, "The 'get' function is only allowed in "
7010 "'frontend', 'backend' or 'task'"));
7011
7012 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
7013 WILL_LJMP(luaL_error(L, "'get' needs between 1 or 2 arguments"));
7014
7015 /* arg 1: URL */
7016 if (lua_type(L, -1) == LUA_TSTRING)
7017 url_str = lua_tostring(L, -1);
7018
7019 hlua_hc = hlua_checkhttpclient(L, 1);
7020
7021 hlua_hc->hc->req.url = istdup(ist(url_str));
7022 hlua_hc->hc->req.meth = HTTP_METH_GET;
7023
7024 /* update the httpclient callbacks */
7025 hlua_hc->hc->ops.res_stline = hlua_httpclient_res_cb;
7026 hlua_hc->hc->ops.res_headers = hlua_httpclient_res_cb;
7027 hlua_hc->hc->ops.res_payload = hlua_httpclient_res_cb;
7028 hlua_hc->hc->ops.res_end = hlua_httpclient_res_cb;
7029
7030
7031 httpclient_req_gen(hlua_hc->hc, hlua_hc->hc->req.url, HTTP_METH_GET, NULL);
7032 httpclient_start(hlua_hc->hc);
7033
7034 /* we return a "res" object */
7035 lua_newtable(L);
7036
7037 luaL_buffinit(L, &hlua_hc->b);
7038 lua_pushstring(L, "body");
7039
7040 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_httpclient_get_yield, TICK_ETERNITY, 0));
7041 return 0;
7042}
7043
7044/*
7045 *
7046 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007047 * Class TXN
7048 *
7049 *
7050 */
7051
7052/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02007053 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007054 */
7055__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
7056{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007057 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007058}
7059
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007060__LJMP static int hlua_set_var(lua_State *L)
7061{
7062 struct hlua_txn *htxn;
7063 const char *name;
7064 size_t len;
7065 struct sample smp;
7066
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007067 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7068 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007069
7070 /* It is useles to retrieve the stream, but this function
7071 * runs only in a stream context.
7072 */
7073 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7074 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7075
7076 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01007077 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007078 hlua_lua2smp(L, 3, &smp);
7079
7080 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01007081 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02007082
7083 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
7084 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
7085 else
7086 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
7087
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007088 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007089}
7090
Christopher Faulet85d79c92016-11-09 16:54:56 +01007091__LJMP static int hlua_unset_var(lua_State *L)
7092{
7093 struct hlua_txn *htxn;
7094 const char *name;
7095 size_t len;
7096 struct sample smp;
7097
7098 MAY_LJMP(check_args(L, 2, "unset_var"));
7099
7100 /* It is useles to retrieve the stream, but this function
7101 * runs only in a stream context.
7102 */
7103 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7104 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7105
7106 /* Unset the variable. */
7107 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02007108 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
7109 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01007110}
7111
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007112__LJMP static int hlua_get_var(lua_State *L)
7113{
7114 struct hlua_txn *htxn;
7115 const char *name;
7116 size_t len;
7117 struct sample smp;
7118
7119 MAY_LJMP(check_args(L, 2, "get_var"));
7120
7121 /* It is useles to retrieve the stream, but this function
7122 * runs only in a stream context.
7123 */
7124 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7125 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
7126
Willy Tarreau7560dd42016-03-10 16:28:58 +01007127 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreaue352b9d2021-09-03 11:52:38 +02007128 if (!vars_get_by_name(name, len, &smp, NULL)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007129 lua_pushnil(L);
7130 return 1;
7131 }
7132
7133 return hlua_smp2lua(L, &smp);
7134}
7135
Willy Tarreau59551662015-03-10 14:23:13 +01007136__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007137{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007138 struct hlua *hlua;
7139
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007140 MAY_LJMP(check_args(L, 2, "set_priv"));
7141
Willy Tarreau87b09662015-04-03 00:22:06 +02007142 /* It is useles to retrieve the stream, but this function
7143 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007144 */
7145 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007146
7147 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007148 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007149 if (!hlua)
7150 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007151
7152 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02007153 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007154
7155 /* Get and store new value. */
7156 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
7157 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
7158
7159 return 0;
7160}
7161
Willy Tarreau59551662015-03-10 14:23:13 +01007162__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007163{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007164 struct hlua *hlua;
7165
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007166 MAY_LJMP(check_args(L, 1, "get_priv"));
7167
Willy Tarreau87b09662015-04-03 00:22:06 +02007168 /* It is useles to retrieve the stream, but this function
7169 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007170 */
7171 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007172
7173 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007174 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007175 if (!hlua) {
7176 lua_pushnil(L);
7177 return 1;
7178 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007179
7180 /* Push configuration index in the stack. */
7181 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
7182
7183 return 1;
7184}
7185
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007186/* Create stack entry containing a class TXN. This function
7187 * return 0 if the stack does not contains free slots,
7188 * otherwise it returns 1.
7189 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007190static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007191{
Willy Tarreaude491382015-04-06 11:04:28 +02007192 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007193
7194 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007195 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007196 return 0;
7197
7198 /* NOTE: The allocation never fails. The failure
7199 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007200 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007201 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007202 /* Create the object: obj[0] = userdata. */
7203 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02007204 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01007205 lua_rawseti(L, -2, 0);
7206
Willy Tarreaude491382015-04-06 11:04:28 +02007207 htxn->s = s;
7208 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01007209 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007210 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007211
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007212 /* Create the "f" field that contains a list of fetches. */
7213 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007214 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007215 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007216 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007217
7218 /* Create the "sf" field that contains a list of stringsafe fetches. */
7219 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01007220 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007221 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007222 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007223
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007224 /* Create the "c" field that contains a list of converters. */
7225 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02007226 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007227 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007228 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01007229
7230 /* Create the "sc" field that contains a list of stringsafe converters. */
7231 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01007232 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007233 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007234 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007235
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007236 /* Create the "req" field that contains the request channel object. */
7237 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007238 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007239 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007240 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007241
7242 /* Create the "res" field that contains the response channel object. */
7243 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01007244 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007245 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007246 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01007247
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007248 /* Creates the HTTP object is the current proxy allows http. */
7249 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01007250 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02007251 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007252 return 0;
7253 }
7254 else
7255 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007256 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007257
Christopher Faulet78c35472020-02-26 17:14:08 +01007258 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX) {
7259 /* HTTPMessage object are created when a lua TXN is created from
7260 * a filter context only
7261 */
7262
7263 /* Creates the HTTP-Request object is the current proxy allows http. */
7264 lua_pushstring(L, "http_req");
7265 if (p->mode == PR_MODE_HTTP) {
7266 if (!hlua_http_msg_new(L, &s->txn->req))
7267 return 0;
7268 }
7269 else
7270 lua_pushnil(L);
7271 lua_rawset(L, -3);
7272
7273 /* Creates the HTTP-Response object is the current proxy allows http. */
7274 lua_pushstring(L, "http_res");
7275 if (p->mode == PR_MODE_HTTP) {
7276 if (!hlua_http_msg_new(L, &s->txn->rsp))
7277 return 0;
7278 }
7279 else
7280 lua_pushnil(L);
7281 lua_rawset(L, -3);
7282 }
7283
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007284 /* Pop a class sesison metatable and affect it to the userdata. */
7285 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
7286 lua_setmetatable(L, -2);
7287
7288 return 1;
7289}
7290
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007291__LJMP static int hlua_txn_deflog(lua_State *L)
7292{
7293 const char *msg;
7294 struct hlua_txn *htxn;
7295
7296 MAY_LJMP(check_args(L, 2, "deflog"));
7297 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7298 msg = MAY_LJMP(luaL_checkstring(L, 2));
7299
7300 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
7301 return 0;
7302}
7303
7304__LJMP static int hlua_txn_log(lua_State *L)
7305{
7306 int level;
7307 const char *msg;
7308 struct hlua_txn *htxn;
7309
7310 MAY_LJMP(check_args(L, 3, "log"));
7311 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7312 level = MAY_LJMP(luaL_checkinteger(L, 2));
7313 msg = MAY_LJMP(luaL_checkstring(L, 3));
7314
7315 if (level < 0 || level >= NB_LOG_LEVELS)
7316 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7317
7318 hlua_sendlog(htxn->s->be, level, msg);
7319 return 0;
7320}
7321
7322__LJMP static int hlua_txn_log_debug(lua_State *L)
7323{
7324 const char *msg;
7325 struct hlua_txn *htxn;
7326
7327 MAY_LJMP(check_args(L, 2, "Debug"));
7328 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7329 msg = MAY_LJMP(luaL_checkstring(L, 2));
7330 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
7331 return 0;
7332}
7333
7334__LJMP static int hlua_txn_log_info(lua_State *L)
7335{
7336 const char *msg;
7337 struct hlua_txn *htxn;
7338
7339 MAY_LJMP(check_args(L, 2, "Info"));
7340 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7341 msg = MAY_LJMP(luaL_checkstring(L, 2));
7342 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
7343 return 0;
7344}
7345
7346__LJMP static int hlua_txn_log_warning(lua_State *L)
7347{
7348 const char *msg;
7349 struct hlua_txn *htxn;
7350
7351 MAY_LJMP(check_args(L, 2, "Warning"));
7352 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7353 msg = MAY_LJMP(luaL_checkstring(L, 2));
7354 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
7355 return 0;
7356}
7357
7358__LJMP static int hlua_txn_log_alert(lua_State *L)
7359{
7360 const char *msg;
7361 struct hlua_txn *htxn;
7362
7363 MAY_LJMP(check_args(L, 2, "Alert"));
7364 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7365 msg = MAY_LJMP(luaL_checkstring(L, 2));
7366 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
7367 return 0;
7368}
7369
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007370__LJMP static int hlua_txn_set_loglevel(lua_State *L)
7371{
7372 struct hlua_txn *htxn;
7373 int ll;
7374
7375 MAY_LJMP(check_args(L, 2, "set_loglevel"));
7376 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7377 ll = MAY_LJMP(luaL_checkinteger(L, 2));
7378
7379 if (ll < 0 || ll > 7)
7380 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
7381
7382 htxn->s->logs.level = ll;
7383 return 0;
7384}
7385
7386__LJMP static int hlua_txn_set_tos(lua_State *L)
7387{
7388 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007389 int tos;
7390
7391 MAY_LJMP(check_args(L, 2, "set_tos"));
7392 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7393 tos = MAY_LJMP(luaL_checkinteger(L, 2));
7394
Willy Tarreau1a18b542018-12-11 16:37:42 +01007395 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007396 return 0;
7397}
7398
7399__LJMP static int hlua_txn_set_mark(lua_State *L)
7400{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007401 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007402 int mark;
7403
7404 MAY_LJMP(check_args(L, 2, "set_mark"));
7405 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7406 mark = MAY_LJMP(luaL_checkinteger(L, 2));
7407
Lukas Tribus579e3e32019-08-11 18:03:45 +02007408 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007409 return 0;
7410}
7411
Patrick Hemmer268a7072018-05-11 12:52:31 -04007412__LJMP static int hlua_txn_set_priority_class(lua_State *L)
7413{
7414 struct hlua_txn *htxn;
7415
7416 MAY_LJMP(check_args(L, 2, "set_priority_class"));
7417 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7418 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
7419 return 0;
7420}
7421
7422__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
7423{
7424 struct hlua_txn *htxn;
7425
7426 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
7427 htxn = MAY_LJMP(hlua_checktxn(L, 1));
7428 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
7429 return 0;
7430}
7431
Christopher Faulet700d9e82020-01-31 12:21:52 +01007432/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007433 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01007434 * message and terminate the transaction. It returns 1 on success and 0 on
7435 * error. The Reply must be on top of the stack.
7436 */
7437__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
7438{
7439 struct htx *htx;
7440 struct htx_sl *sl;
7441 struct h1m h1m;
7442 const char *status, *reason, *body;
7443 size_t status_len, reason_len, body_len;
7444 int ret, code, flags;
7445
7446 code = 200;
7447 status = "200";
7448 status_len = 3;
7449 ret = lua_getfield(L, -1, "status");
7450 if (ret == LUA_TNUMBER) {
7451 code = lua_tointeger(L, -1);
7452 status = lua_tolstring(L, -1, &status_len);
7453 }
7454 lua_pop(L, 1);
7455
7456 reason = http_get_reason(code);
7457 reason_len = strlen(reason);
7458 ret = lua_getfield(L, -1, "reason");
7459 if (ret == LUA_TSTRING)
7460 reason = lua_tolstring(L, -1, &reason_len);
7461 lua_pop(L, 1);
7462
7463 body = NULL;
7464 body_len = 0;
7465 ret = lua_getfield(L, -1, "body");
7466 if (ret == LUA_TSTRING)
7467 body = lua_tolstring(L, -1, &body_len);
7468 lua_pop(L, 1);
7469
7470 /* Prepare the response before inserting the headers */
7471 h1m_init_res(&h1m);
7472 htx = htx_from_buf(&s->res.buf);
7473 channel_htx_truncate(&s->res, htx);
7474 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
7475 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
7476 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
7477 ist2(status, status_len), ist2(reason, reason_len));
7478 }
7479 else {
7480 flags = HTX_SL_F_IS_RESP;
7481 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
7482 ist2(status, status_len), ist2(reason, reason_len));
7483 }
7484 if (!sl)
7485 goto fail;
7486 sl->info.res.status = code;
7487
7488 /* Push in the stack the "headers" entry. */
7489 ret = lua_getfield(L, -1, "headers");
7490 if (ret != LUA_TTABLE)
7491 goto skip_headers;
7492
7493 lua_pushnil(L);
7494 while (lua_next(L, -2) != 0) {
7495 struct ist name, value;
7496 const char *n, *v;
7497 size_t nlen, vlen;
7498
7499 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
7500 /* Skip element if the key is not a string or if the value is not a table */
7501 goto next_hdr;
7502 }
7503
7504 n = lua_tolstring(L, -2, &nlen);
7505 name = ist2(n, nlen);
7506 if (isteqi(name, ist("content-length"))) {
7507 /* Always skip content-length header. It will be added
7508 * later with the correct len
7509 */
7510 goto next_hdr;
7511 }
7512
7513 /* Loop on header's values */
7514 lua_pushnil(L);
7515 while (lua_next(L, -2)) {
7516 if (!lua_isstring(L, -1)) {
7517 /* Skip the value if it is not a string */
7518 goto next_value;
7519 }
7520
7521 v = lua_tolstring(L, -1, &vlen);
7522 value = ist2(v, vlen);
7523
7524 if (isteqi(name, ist("transfer-encoding")))
7525 h1_parse_xfer_enc_header(&h1m, value);
7526 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
7527 goto fail;
7528
7529 next_value:
7530 lua_pop(L, 1);
7531 }
7532
7533 next_hdr:
7534 lua_pop(L, 1);
7535 }
7536 skip_headers:
7537 lua_pop(L, 1);
7538
7539 /* Update h1m flags: CLEN is set if CHNK is not present */
7540 if (!(h1m.flags & H1_MF_CHNK)) {
7541 const char *clen = ultoa(body_len);
7542
7543 h1m.flags |= H1_MF_CLEN;
7544 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
7545 goto fail;
7546 }
7547 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
7548 h1m.flags |= H1_MF_XFER_LEN;
7549
7550 /* Update HTX start-line flags */
7551 if (h1m.flags & H1_MF_XFER_ENC)
7552 flags |= HTX_SL_F_XFER_ENC;
7553 if (h1m.flags & H1_MF_XFER_LEN) {
7554 flags |= HTX_SL_F_XFER_LEN;
7555 if (h1m.flags & H1_MF_CHNK)
7556 flags |= HTX_SL_F_CHNK;
7557 else if (h1m.flags & H1_MF_CLEN)
7558 flags |= HTX_SL_F_CLEN;
7559 if (h1m.body_len == 0)
7560 flags |= HTX_SL_F_BODYLESS;
7561 }
7562 sl->flags |= flags;
7563
7564
7565 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007566 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01007567 goto fail;
7568
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007569 htx->flags |= HTX_FL_EOM;
7570
Christopher Faulet700d9e82020-01-31 12:21:52 +01007571 /* Now, forward the response and terminate the transaction */
7572 s->txn->status = code;
7573 htx_to_buf(htx, &s->res.buf);
7574 if (!http_forward_proxy_resp(s, 1))
7575 goto fail;
7576
7577 return 1;
7578
7579 fail:
7580 channel_htx_truncate(&s->res, htx);
7581 return 0;
7582}
7583
7584/* Terminate a transaction if called from a lua action. For TCP streams,
7585 * processing is just aborted. Nothing is returned to the client and all
7586 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
7587 * is forwarded to the client before terminating the transaction. On success,
7588 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
7589 * with ACT_RET_ERR code. If this function is not called from a lua action, it
7590 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007591 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007592__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007593{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007594 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01007595 struct stream *s;
7596 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007597
Willy Tarreaub2ccb562015-04-06 11:11:15 +02007598 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007599
Christopher Faulet700d9e82020-01-31 12:21:52 +01007600 /* If the flags NOTERM is set, we cannot terminate the session, so we
7601 * just end the execution of the current lua code. */
7602 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007603 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02007604
Christopher Faulet700d9e82020-01-31 12:21:52 +01007605 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007606 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007607 struct channel *req = &s->req;
7608 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01007609
Christopher Faulet700d9e82020-01-31 12:21:52 +01007610 channel_auto_read(req);
7611 channel_abort(req);
7612 channel_auto_close(req);
7613 channel_erase(req);
7614
7615 res->wex = tick_add_ifset(now_ms, res->wto);
7616 channel_auto_read(res);
7617 channel_auto_close(res);
7618 channel_shutr_now(res);
7619
7620 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
7621 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007622 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02007623
Christopher Faulet700d9e82020-01-31 12:21:52 +01007624 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
7625 /* No reply or invalid reply */
7626 s->txn->status = 0;
7627 http_reply_and_close(s, 0, NULL);
7628 }
7629 else {
7630 /* Remove extra args to have the reply on top of the stack */
7631 if (lua_gettop(L) > 2)
7632 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007633
Christopher Faulet700d9e82020-01-31 12:21:52 +01007634 if (!hlua_txn_forward_reply(L, s)) {
7635 if (!(s->flags & SF_ERR_MASK))
7636 s->flags |= SF_ERR_PRXCOND;
7637 lua_pushinteger(L, ACT_RET_ERR);
7638 WILL_LJMP(hlua_done(L));
7639 return 0; /* Never reached */
7640 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02007641 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007642
Christopher Faulet700d9e82020-01-31 12:21:52 +01007643 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
7644 if (htxn->dir == SMP_OPT_DIR_REQ) {
7645 /* let's log the request time */
7646 s->logs.tv_request = now;
7647 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02007648 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01007649 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007650
Christopher Faulet700d9e82020-01-31 12:21:52 +01007651 done:
7652 if (!(s->flags & SF_ERR_MASK))
7653 s->flags |= SF_ERR_LOCAL;
7654 if (!(s->flags & SF_FINST_MASK))
7655 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02007656
Christopher Faulete48d1dc2021-08-13 14:11:17 +02007657 if ((htxn->flags & HLUA_TXN_CTX_MASK) == HLUA_TXN_FLT_CTX)
7658 lua_pushinteger(L, -1);
7659 else
7660 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007661 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007662 return 0;
7663}
7664
Christopher Faulet700d9e82020-01-31 12:21:52 +01007665/*
7666 *
7667 *
7668 * Class REPLY
7669 *
7670 *
7671 */
7672
7673/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
7674 * free slots, the function fails and returns 0;
7675 */
7676static int hlua_txn_reply_new(lua_State *L)
7677{
7678 struct hlua_txn *htxn;
7679 const char *reason, *body = NULL;
7680 int ret, status;
7681
7682 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007683 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01007684 hlua_pusherror(L, "txn object is not an HTTP transaction.");
7685 WILL_LJMP(lua_error(L));
7686 }
7687
7688 /* Default value */
7689 status = 200;
7690 reason = http_get_reason(status);
7691
7692 if (lua_istable(L, 2)) {
7693 /* load status and reason from the table argument at index 2 */
7694 ret = lua_getfield(L, 2, "status");
7695 if (ret == LUA_TNIL)
7696 goto reason;
7697 else if (ret != LUA_TNUMBER) {
7698 /* invalid status: ignore the reason */
7699 goto body;
7700 }
7701 status = lua_tointeger(L, -1);
7702
7703 reason:
7704 lua_pop(L, 1); /* restore the stack: remove status */
7705 ret = lua_getfield(L, 2, "reason");
7706 if (ret == LUA_TSTRING)
7707 reason = lua_tostring(L, -1);
7708
7709 body:
7710 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
7711 ret = lua_getfield(L, 2, "body");
7712 if (ret == LUA_TSTRING)
7713 body = lua_tostring(L, -1);
7714 lua_pop(L, 1); /* restore the stack: remove body */
7715 }
7716
7717 /* Create the Reply table */
7718 lua_newtable(L);
7719
7720 /* Add status element */
7721 lua_pushstring(L, "status");
7722 lua_pushinteger(L, status);
7723 lua_settable(L, -3);
7724
7725 /* Add reason element */
7726 reason = http_get_reason(status);
7727 lua_pushstring(L, "reason");
7728 lua_pushstring(L, reason);
7729 lua_settable(L, -3);
7730
7731 /* Add body element, nil if undefined */
7732 lua_pushstring(L, "body");
7733 if (body)
7734 lua_pushstring(L, body);
7735 else
7736 lua_pushnil(L);
7737 lua_settable(L, -3);
7738
7739 /* Add headers element */
7740 lua_pushstring(L, "headers");
7741 lua_newtable(L);
7742
7743 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7744 if (lua_istable(L, 2)) {
7745 /* load headers from the table argument at index 2. If it is a table, copy it. */
7746 ret = lua_getfield(L, 2, "headers");
7747 if (ret == LUA_TTABLE) {
7748 /* stack: [ ... <headers:table>, <table> ] */
7749 lua_pushnil(L);
7750 while (lua_next(L, -2) != 0) {
7751 /* stack: [ ... <headers:table>, <table>, k, v] */
7752 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
7753 /* invalid value type, skip it */
7754 lua_pop(L, 1);
7755 continue;
7756 }
7757
7758
7759 /* Duplicate the key and swap it with the value. */
7760 lua_pushvalue(L, -2);
7761 lua_insert(L, -2);
7762 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
7763
7764 lua_newtable(L);
7765 lua_insert(L, -2);
7766 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
7767
7768 if (lua_isstring(L, -1)) {
7769 /* push the value in the inner table */
7770 lua_rawseti(L, -2, 1);
7771 }
7772 else { /* table */
7773 lua_pushnil(L);
7774 while (lua_next(L, -2) != 0) {
7775 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
7776 if (!lua_isstring(L, -1)) {
7777 /* invalid value type, skip it*/
7778 lua_pop(L, 1);
7779 continue;
7780 }
7781 /* push the value in the inner table */
7782 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
7783 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
7784 }
7785 lua_pop(L, 1);
7786 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
7787 }
7788
7789 /* push (k,v) on the stack in the headers table:
7790 * stack: [ ... <headers:table>, <table>, k, k, v ]
7791 */
7792 lua_settable(L, -5);
7793 /* stack: [ ... <headers:table>, <table>, k ] */
7794 }
7795 }
7796 lua_pop(L, 1);
7797 }
7798 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
7799 lua_settable(L, -3);
7800 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
7801
7802 /* Pop a class sesison metatable and affect it to the userdata. */
7803 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
7804 lua_setmetatable(L, -2);
7805 return 1;
7806}
7807
7808/* Set the reply status code, and optionally the reason. If no reason is
7809 * provided, the default one corresponding to the status code is used.
7810 */
7811__LJMP static int hlua_txn_reply_set_status(lua_State *L)
7812{
7813 int status = MAY_LJMP(luaL_checkinteger(L, 2));
7814 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
7815
7816 /* First argument (self) must be a table */
7817 luaL_checktype(L, 1, LUA_TTABLE);
7818
7819 if (status < 100 || status > 599) {
7820 lua_pushboolean(L, 0);
7821 return 1;
7822 }
7823 if (!reason)
7824 reason = http_get_reason(status);
7825
7826 lua_pushinteger(L, status);
7827 lua_setfield(L, 1, "status");
7828
7829 lua_pushstring(L, reason);
7830 lua_setfield(L, 1, "reason");
7831
7832 lua_pushboolean(L, 1);
7833 return 1;
7834}
7835
7836/* Add a header into the reply object. Each header name is associated to an
7837 * array of values in the "headers" table. If the header name is not found, a
7838 * new entry is created.
7839 */
7840__LJMP static int hlua_txn_reply_add_header(lua_State *L)
7841{
7842 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7843 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
7844 int ret;
7845
7846 /* First argument (self) must be a table */
7847 luaL_checktype(L, 1, LUA_TTABLE);
7848
7849 /* Push in the stack the "headers" entry. */
7850 ret = lua_getfield(L, 1, "headers");
7851 if (ret != LUA_TTABLE) {
7852 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
7853 WILL_LJMP(lua_error(L));
7854 }
7855
7856 /* check if the header is already registered. If not, register it. */
7857 ret = lua_getfield(L, -1, name);
7858 if (ret == LUA_TNIL) {
7859 /* Entry not found. */
7860 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
7861
7862 /* Insert the new header name in the array in the top of the stack.
7863 * It left the new array in the top of the stack.
7864 */
7865 lua_newtable(L);
7866 lua_pushstring(L, name);
7867 lua_pushvalue(L, -2);
7868 lua_settable(L, -4);
7869 }
7870 else if (ret != LUA_TTABLE) {
7871 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
7872 WILL_LJMP(lua_error(L));
7873 }
7874
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07007875 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01007876 * the header value as new entry.
7877 */
7878 lua_pushstring(L, value);
7879 ret = lua_rawlen(L, -2);
7880 lua_rawseti(L, -2, ret + 1);
7881
7882 lua_pushboolean(L, 1);
7883 return 1;
7884}
7885
7886/* Remove all occurrences of a given header name. */
7887__LJMP static int hlua_txn_reply_del_header(lua_State *L)
7888{
7889 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
7890 int ret;
7891
7892 /* First argument (self) must be a table */
7893 luaL_checktype(L, 1, LUA_TTABLE);
7894
7895 /* Push in the stack the "headers" entry. */
7896 ret = lua_getfield(L, 1, "headers");
7897 if (ret != LUA_TTABLE) {
7898 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
7899 WILL_LJMP(lua_error(L));
7900 }
7901
7902 lua_pushstring(L, name);
7903 lua_pushnil(L);
7904 lua_settable(L, -3);
7905
7906 lua_pushboolean(L, 1);
7907 return 1;
7908}
7909
7910/* Set the reply's body. Overwrite any existing entry. */
7911__LJMP static int hlua_txn_reply_set_body(lua_State *L)
7912{
7913 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
7914
7915 /* First argument (self) must be a table */
7916 luaL_checktype(L, 1, LUA_TTABLE);
7917
7918 lua_pushstring(L, payload);
7919 lua_setfield(L, 1, "body");
7920
7921 lua_pushboolean(L, 1);
7922 return 1;
7923}
7924
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007925__LJMP static int hlua_log(lua_State *L)
7926{
7927 int level;
7928 const char *msg;
7929
7930 MAY_LJMP(check_args(L, 2, "log"));
7931 level = MAY_LJMP(luaL_checkinteger(L, 1));
7932 msg = MAY_LJMP(luaL_checkstring(L, 2));
7933
7934 if (level < 0 || level >= NB_LOG_LEVELS)
7935 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
7936
7937 hlua_sendlog(NULL, level, msg);
7938 return 0;
7939}
7940
7941__LJMP static int hlua_log_debug(lua_State *L)
7942{
7943 const char *msg;
7944
7945 MAY_LJMP(check_args(L, 1, "debug"));
7946 msg = MAY_LJMP(luaL_checkstring(L, 1));
7947 hlua_sendlog(NULL, LOG_DEBUG, msg);
7948 return 0;
7949}
7950
7951__LJMP static int hlua_log_info(lua_State *L)
7952{
7953 const char *msg;
7954
7955 MAY_LJMP(check_args(L, 1, "info"));
7956 msg = MAY_LJMP(luaL_checkstring(L, 1));
7957 hlua_sendlog(NULL, LOG_INFO, msg);
7958 return 0;
7959}
7960
7961__LJMP static int hlua_log_warning(lua_State *L)
7962{
7963 const char *msg;
7964
7965 MAY_LJMP(check_args(L, 1, "warning"));
7966 msg = MAY_LJMP(luaL_checkstring(L, 1));
7967 hlua_sendlog(NULL, LOG_WARNING, msg);
7968 return 0;
7969}
7970
7971__LJMP static int hlua_log_alert(lua_State *L)
7972{
7973 const char *msg;
7974
7975 MAY_LJMP(check_args(L, 1, "alert"));
7976 msg = MAY_LJMP(luaL_checkstring(L, 1));
7977 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01007978 return 0;
7979}
7980
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007981__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007982{
7983 int wakeup_ms = lua_tointeger(L, -1);
7984 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02007985 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007986 return 0;
7987}
7988
7989__LJMP static int hlua_sleep(lua_State *L)
7990{
7991 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007992 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007993
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007994 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007995
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01007996 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01007997 wakeup_ms = tick_add(now_ms, delay);
7998 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007999
Willy Tarreau9635e032018-10-16 17:52:55 +02008000 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008001 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008002}
8003
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008004__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008005{
8006 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008007 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008008
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008009 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008010
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008011 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008012 wakeup_ms = tick_add(now_ms, delay);
8013 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008014
Willy Tarreau9635e032018-10-16 17:52:55 +02008015 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008016 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008017}
8018
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008019/* This functionis an LUA binding. it permits to give back
8020 * the hand at the HAProxy scheduler. It is used when the
8021 * LUA processing consumes a lot of time.
8022 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01008023__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008024{
8025 return 0;
8026}
8027
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008028__LJMP static int hlua_yield(lua_State *L)
8029{
Willy Tarreau9635e032018-10-16 17:52:55 +02008030 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01008031 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008032}
8033
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008034/* This function change the nice of the currently executed
8035 * task. It is used set low or high priority at the current
8036 * task.
8037 */
Willy Tarreau59551662015-03-10 14:23:13 +01008038__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008039{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008040 struct hlua *hlua;
8041 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008042
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008043 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008044 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008045
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008046 /* Get hlua struct, or NULL if we execute from main lua state */
8047 hlua = hlua_gethlua(L);
8048
8049 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008050 if (!hlua || !hlua->task)
8051 return 0;
8052
8053 if (nice < -1024)
8054 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008055 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01008056 nice = 1024;
8057
8058 hlua->task->nice = nice;
8059 return 0;
8060}
8061
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008062/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008063 * HAProxy task subsystem when the task is awaked. The LUA runtime can
8064 * return an E_AGAIN signal, the emmiter of this signal must set a
8065 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008066 *
8067 * Task wrapper are longjmp safe because the only one Lua code
8068 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008069 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01008070struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008071{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008072 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008073 enum hlua_exec status;
8074
Christopher Faulet5bc99722018-04-25 10:34:45 +02008075 if (task->thread_mask == MAX_THREADS_MASK)
8076 task_set_affinity(task, tid_bit);
8077
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008078 /* If it is the first call to the task, we must initialize the
8079 * execution timeouts.
8080 */
8081 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008082 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008083
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008084 /* Execute the Lua code. */
8085 status = hlua_ctx_resume(hlua, 1);
8086
8087 switch (status) {
8088 /* finished or yield */
8089 case HLUA_E_OK:
8090 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008091 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02008092 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008093 break;
8094
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008095 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01008096 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02008097 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008098 break;
8099
8100 /* finished with error. */
8101 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008102 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008103 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008104 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008105 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008106 break;
8107
8108 case HLUA_E_ERR:
8109 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008110 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008111 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02008112 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02008113 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008114 break;
8115 }
Emeric Brun253e53e2017-10-17 18:58:40 +02008116 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008117}
8118
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008119/* This function is an LUA binding that register LUA function to be
8120 * executed after the HAProxy configuration parsing and before the
8121 * HAProxy scheduler starts. This function expect only one LUA
8122 * argument that is a function. This function returns nothing, but
8123 * throws if an error is encountered.
8124 */
8125__LJMP static int hlua_register_init(lua_State *L)
8126{
8127 struct hlua_init_function *init;
8128 int ref;
8129
8130 MAY_LJMP(check_args(L, 1, "register_init"));
8131
8132 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8133
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008134 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008135 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008136 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008137
8138 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02008139 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008140 return 0;
8141}
8142
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008143/* This functio is an LUA binding. It permits to register a task
8144 * executed in parallel of the main HAroxy activity. The task is
8145 * created and it is set in the HAProxy scheduler. It can be called
8146 * from the "init" section, "post init" or during the runtime.
8147 *
8148 * Lua prototype:
8149 *
8150 * <none> core.register_task(<function>)
8151 */
8152static int hlua_register_task(lua_State *L)
8153{
Christopher Faulet5294ec02021-04-12 12:24:47 +02008154 struct hlua *hlua = NULL;
8155 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008156 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01008157 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008158
8159 MAY_LJMP(check_args(L, 1, "register_task"));
8160
8161 ref = MAY_LJMP(hlua_checkfunction(L, 1));
8162
Thierry Fournier75fc0292020-11-28 13:18:56 +01008163 /* Get the reference state. If the reference is NULL, L is the master
8164 * state, otherwise hlua->T is.
8165 */
8166 hlua = hlua_gethlua(L);
8167 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01008168 /* we are in runtime processing */
8169 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008170 else
Thierry Fournier021d9862020-11-28 23:42:03 +01008171 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01008172 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01008173
Willy Tarreaubafbe012017-11-24 17:34:44 +01008174 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008175 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008176 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008177 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008178
Thierry Fournier59f11be2020-11-29 00:37:41 +01008179 /* We are in the common lua state, execute the task anywhere,
8180 * otherwise, inherit the current thread identifier
8181 */
8182 if (state_id == 0)
8183 task = task_new(MAX_THREADS_MASK);
8184 else
8185 task = task_new(tid_bit);
Willy Tarreaue09101e2018-10-16 17:37:12 +02008186 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02008187 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02008188
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008189 task->context = hlua;
8190 task->process = hlua_process_task;
8191
Thierry Fournier021d9862020-11-28 23:42:03 +01008192 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02008193 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008194
8195 /* Restore the function in the stack. */
8196 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
8197 hlua->nargs = 0;
8198
8199 /* Schedule task. */
8200 task_schedule(task, now_ms);
8201
8202 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02008203
8204 alloc_error:
8205 task_destroy(task);
8206 hlua_ctx_destroy(hlua);
8207 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8208 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008209}
8210
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008211/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
8212 * doesn't allow "yield" functions because the HAProxy engine cannot
8213 * resume converters.
8214 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008215static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008216{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008217 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008218 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008219 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008220
Willy Tarreaube508f12016-03-10 11:47:01 +01008221 if (!stream)
8222 return 0;
8223
Willy Tarreau87b09662015-04-03 00:22:06 +02008224 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008225 * Lua context can be not initialized. This behavior
8226 * permits to save performances because a systematic
8227 * Lua initialization cause 5% performances loss.
8228 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008229 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008230 struct hlua *hlua;
8231
8232 hlua = pool_alloc(pool_head_hlua);
8233 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008234 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8235 return 0;
8236 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008237 HLUA_INIT(hlua);
8238 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008239 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008240 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
8241 return 0;
8242 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008243 }
8244
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008245 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008246 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008247
8248 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008249 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008250 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8251 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008252 else
8253 error = "critical error";
8254 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008255 return 0;
8256 }
8257
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008258 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008259 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008260 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008261 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008262 return 0;
8263 }
8264
8265 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008266 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008267
8268 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008269 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008270 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008271 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008272 return 0;
8273 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008274 hlua_smp2lua(stream->hlua->T, smp);
8275 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008276
8277 /* push keywords in the stack. */
8278 if (arg_p) {
8279 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008280 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008281 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008282 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008283 return 0;
8284 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008285 hlua_arg2lua(stream->hlua->T, arg_p);
8286 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008287 }
8288 }
8289
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008290 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008291 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008292
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008293 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008294 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008295 }
8296
8297 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008298 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008299 /* finished. */
8300 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008301 /* If the stack is empty, the function fails. */
8302 if (lua_gettop(stream->hlua->T) <= 0)
8303 return 0;
8304
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008305 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008306 hlua_lua2smp(stream->hlua->T, -1, smp);
8307 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008308 return 1;
8309
8310 /* yield. */
8311 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008312 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008313 return 0;
8314
8315 /* finished with error. */
8316 case HLUA_E_ERRMSG:
8317 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008318 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008319 fcn->name, lua_tostring(stream->hlua->T, -1));
8320 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008321 return 0;
8322
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008323 case HLUA_E_ETMOUT:
8324 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
8325 return 0;
8326
8327 case HLUA_E_NOMEM:
8328 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
8329 return 0;
8330
8331 case HLUA_E_YIELD:
8332 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
8333 return 0;
8334
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008335 case HLUA_E_ERR:
8336 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008337 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008338 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008339
8340 default:
8341 return 0;
8342 }
8343}
8344
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008345/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
8346 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01008347 * resume sample-fetches. This function will be called by the sample
8348 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008349 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02008350static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
8351 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008352{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008353 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02008354 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008355 const char *error;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008356 unsigned int hflags = HLUA_TXN_NOTERM | HLUA_TXN_SMP_CTX;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008357
Willy Tarreaube508f12016-03-10 11:47:01 +01008358 if (!stream)
8359 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01008360
Willy Tarreau87b09662015-04-03 00:22:06 +02008361 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008362 * Lua context can be not initialized. This behavior
8363 * permits to save performances because a systematic
8364 * Lua initialization cause 5% performances loss.
8365 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008366 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008367 struct hlua *hlua;
8368
8369 hlua = pool_alloc(pool_head_hlua);
8370 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008371 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8372 return 0;
8373 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008374 hlua->T = NULL;
8375 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008376 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008377 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
8378 return 0;
8379 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008380 }
8381
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008382 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008383 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008384
8385 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008386 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008387 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
8388 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008389 else
8390 error = "critical error";
8391 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008392 return 0;
8393 }
8394
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008395 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008396 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008397 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008398 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008399 return 0;
8400 }
8401
8402 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008403 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008404
8405 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008406 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008407 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008408 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008409 return 0;
8410 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008411 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008412
8413 /* push keywords in the stack. */
8414 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
8415 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008416 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008417 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008418 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008419 return 0;
8420 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008421 hlua_arg2lua(stream->hlua->T, arg_p);
8422 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008423 }
8424
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008425 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008426 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008427
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008428 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008429 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008430 }
8431
8432 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008433 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008434 /* finished. */
8435 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02008436 /* If the stack is empty, the function fails. */
8437 if (lua_gettop(stream->hlua->T) <= 0)
8438 return 0;
8439
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008440 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008441 hlua_lua2smp(stream->hlua->T, -1, smp);
8442 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008443
8444 /* Set the end of execution flag. */
8445 smp->flags &= ~SMP_F_MAY_CHANGE;
8446 return 1;
8447
8448 /* yield. */
8449 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008450 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008451 return 0;
8452
8453 /* finished with error. */
8454 case HLUA_E_ERRMSG:
8455 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008456 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008457 fcn->name, lua_tostring(stream->hlua->T, -1));
8458 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008459 return 0;
8460
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008461 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008462 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
8463 return 0;
8464
8465 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008466 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
8467 return 0;
8468
8469 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008470 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
8471 return 0;
8472
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008473 case HLUA_E_ERR:
8474 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008475 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02008476 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008477
8478 default:
8479 return 0;
8480 }
8481}
8482
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008483/* This function is an LUA binding used for registering
8484 * "sample-conv" functions. It expects a converter name used
8485 * in the haproxy configuration file, and an LUA function.
8486 */
8487__LJMP static int hlua_register_converters(lua_State *L)
8488{
8489 struct sample_conv_kw_list *sck;
8490 const char *name;
8491 int ref;
8492 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02008493 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008494 struct sample_conv *sc;
8495 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008496
8497 MAY_LJMP(check_args(L, 2, "register_converters"));
8498
8499 /* First argument : converter name. */
8500 name = MAY_LJMP(luaL_checkstring(L, 1));
8501
8502 /* Second argument : lua function. */
8503 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8504
Thierry Fournierf67442e2020-11-28 20:41:07 +01008505 /* Check if the converter is already registered */
8506 trash = get_trash_chunk();
8507 chunk_printf(trash, "lua.%s", name);
8508 sc = find_sample_conv(trash->area, trash->data);
8509 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008510 fcn = sc->private;
8511 if (fcn->function_ref[hlua_state_id] != -1) {
8512 ha_warning("Trying to register converter 'lua.%s' more than once. "
8513 "This will become a hard error in version 2.5.\n", name);
8514 }
8515 fcn->function_ref[hlua_state_id] = ref;
8516 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008517 }
8518
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008519 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008520 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008521 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02008522 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008523 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008524 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02008525 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008526
8527 /* Fill fcn. */
8528 fcn->name = strdup(name);
8529 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02008530 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008531 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008532
8533 /* List head */
8534 sck->list.n = sck->list.p = NULL;
8535
8536 /* converter keyword. */
8537 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008538 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008539 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02008540 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008541
8542 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
8543 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008544 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 +01008545 sck->kw[0].val_args = NULL;
8546 sck->kw[0].in_type = SMP_T_STR;
8547 sck->kw[0].out_type = SMP_T_STR;
8548 sck->kw[0].private = fcn;
8549
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008550 /* Register this new converter */
8551 sample_register_convs(sck);
8552
8553 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02008554
8555 alloc_error:
8556 release_hlua_function(fcn);
8557 ha_free(&sck);
8558 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8559 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008560}
8561
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008562/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008563 * "sample-fetch" functions. It expects a converter name used
8564 * in the haproxy configuration file, and an LUA function.
8565 */
8566__LJMP static int hlua_register_fetches(lua_State *L)
8567{
8568 const char *name;
8569 int ref;
8570 int len;
8571 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02008572 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008573 struct sample_fetch *sf;
8574 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008575
8576 MAY_LJMP(check_args(L, 2, "register_fetches"));
8577
8578 /* First argument : sample-fetch name. */
8579 name = MAY_LJMP(luaL_checkstring(L, 1));
8580
8581 /* Second argument : lua function. */
8582 ref = MAY_LJMP(hlua_checkfunction(L, 2));
8583
Thierry Fournierf67442e2020-11-28 20:41:07 +01008584 /* Check if the sample-fetch is already registered */
8585 trash = get_trash_chunk();
8586 chunk_printf(trash, "lua.%s", name);
8587 sf = find_sample_fetch(trash->area, trash->data);
8588 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008589 fcn = sf->private;
8590 if (fcn->function_ref[hlua_state_id] != -1) {
8591 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
8592 "This will become a hard error in version 2.5.\n", name);
8593 }
8594 fcn->function_ref[hlua_state_id] = ref;
8595 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008596 }
8597
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008598 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008599 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008600 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02008601 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008602 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008603 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02008604 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008605
8606 /* Fill fcn. */
8607 fcn->name = strdup(name);
8608 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02008609 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008610 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008611
8612 /* List head */
8613 sfk->list.n = sfk->list.p = NULL;
8614
8615 /* sample-fetch keyword. */
8616 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008617 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008618 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02008619 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008620
8621 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
8622 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01008623 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 +01008624 sfk->kw[0].val_args = NULL;
8625 sfk->kw[0].out_type = SMP_T_STR;
8626 sfk->kw[0].use = SMP_USE_HTTP_ANY;
8627 sfk->kw[0].val = 0;
8628 sfk->kw[0].private = fcn;
8629
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008630 /* Register this new fetch. */
8631 sample_register_fetches(sfk);
8632
8633 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02008634
8635 alloc_error:
8636 release_hlua_function(fcn);
8637 ha_free(&sfk);
8638 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8639 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008640}
8641
Christopher Faulet501465d2020-02-26 14:54:16 +01008642/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008643 */
Christopher Faulet501465d2020-02-26 14:54:16 +01008644__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008645{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008646 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008647 unsigned int delay;
8648 unsigned int wakeup_ms;
8649
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008650 /* Get hlua struct, or NULL if we execute from main lua state */
8651 hlua = hlua_gethlua(L);
8652 if (!hlua) {
8653 return 0;
8654 }
8655
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008656 MAY_LJMP(check_args(L, 1, "wake_time"));
8657
8658 delay = MAY_LJMP(luaL_checkinteger(L, 1));
8659 wakeup_ms = tick_add(now_ms, delay);
8660 hlua->wake_time = wakeup_ms;
8661 return 0;
8662}
8663
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008664/* This function is a wrapper to execute each LUA function declared as an action
8665 * wrapper during the initialisation period. This function may return any
8666 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
8667 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
8668 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008669 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008670static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02008671 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008672{
8673 char **arg;
Christopher Faulet8c9e6bb2021-08-06 16:29:41 +02008674 unsigned int hflags = HLUA_TXN_ACT_CTX;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008675 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008676 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008677
8678 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01008679 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
8680 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
8681 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
8682 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008683 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008684 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008685 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008686 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008687
Willy Tarreau87b09662015-04-03 00:22:06 +02008688 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008689 * Lua context can be not initialized. This behavior
8690 * permits to save performances because a systematic
8691 * Lua initialization cause 5% performances loss.
8692 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008693 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008694 struct hlua *hlua;
8695
8696 hlua = pool_alloc(pool_head_hlua);
8697 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008698 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008699 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008700 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008701 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01008702 HLUA_INIT(hlua);
8703 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01008704 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 +01008705 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008706 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008707 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008708 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01008709 }
8710
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008711 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008712 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008713
8714 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008715 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008716 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
8717 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01008718 else
8719 error = "critical error";
8720 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008721 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008722 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008723 }
8724
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008725 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008726 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008727 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008728 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008729 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008730 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008731 }
8732
8733 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008734 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 +01008735
Willy Tarreau87b09662015-04-03 00:22:06 +02008736 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02008737 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008738 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008739 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008740 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008741 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008742 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008743 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008744
8745 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02008746 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008747 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008748 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008749 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008750 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008751 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008752 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008753 lua_pushstring(s->hlua->T, *arg);
8754 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008755 }
8756
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008757 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008758 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008759
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008760 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008761 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008762 }
8763
8764 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01008765 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008766 /* finished. */
8767 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008768 /* Catch the return value */
8769 if (lua_gettop(s->hlua->T) > 0)
8770 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008771
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008772 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02008773 if (act_ret == ACT_RET_YIELD) {
8774 if (flags & ACT_OPT_FINAL)
8775 goto err_yield;
8776
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008777 if (dir == SMP_OPT_DIR_REQ)
8778 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8779 s->hlua->wake_time);
8780 else
8781 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8782 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008783 }
8784 goto end;
8785
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008786 /* yield. */
8787 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01008788 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008789 if (dir == SMP_OPT_DIR_REQ)
8790 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
8791 s->hlua->wake_time);
8792 else
8793 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
8794 s->hlua->wake_time);
8795
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008796 /* Some actions can be wake up when a "write" event
8797 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008798 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008799 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02008800 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008801 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008802 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01008803 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008804 act_ret = ACT_RET_YIELD;
8805 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008806
8807 /* finished with error. */
8808 case HLUA_E_ERRMSG:
8809 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008810 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008811 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01008812 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008813 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008814
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008815 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008816 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008817 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008818
8819 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01008820 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008821 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008822
8823 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02008824 err_yield:
8825 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008826 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008827 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008828 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008829
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008830 case HLUA_E_ERR:
8831 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02008832 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008833 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008834
8835 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008836 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008837 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008838
8839 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02008840 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02008841 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01008842 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01008843}
8844
Willy Tarreau144f84a2021-03-02 16:09:26 +01008845struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008846{
Olivier Houchard9f6af332018-05-25 14:04:04 +02008847 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008848
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008849 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02008850 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02008851 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008852}
8853
8854static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
8855{
8856 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008857 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008858 struct task *task;
8859 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008860 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008861
Willy Tarreaubafbe012017-11-24 17:34:44 +01008862 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008863 if (!hlua) {
8864 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008865 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008866 return 0;
8867 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008868 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008869 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008870 ctx->ctx.hlua_apptcp.flags = 0;
8871
8872 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008873 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008874 if (!task) {
8875 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008876 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008877 return 0;
8878 }
8879 task->nice = 0;
8880 task->context = ctx;
8881 task->process = hlua_applet_wakeup;
8882 ctx->ctx.hlua_apptcp.task = task;
8883
8884 /* In the execution wrappers linked with a stream, the
8885 * Lua context can be not initialized. This behavior
8886 * permits to save performances because a systematic
8887 * Lua initialization cause 5% performances loss.
8888 */
Thierry Fournierc7492592020-11-28 23:57:24 +01008889 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008890 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008891 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008892 return 0;
8893 }
8894
8895 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02008896 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008897
8898 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008899 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008900 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8901 error = lua_tostring(hlua->T, -1);
8902 else
8903 error = "critical error";
8904 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008905 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008906 return 0;
8907 }
8908
8909 /* Check stack available size. */
8910 if (!lua_checkstack(hlua->T, 1)) {
8911 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008912 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008913 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008914 return 0;
8915 }
8916
8917 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008918 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008919
8920 /* Create and and push object stream in the stack. */
8921 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
8922 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008923 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008924 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008925 return 0;
8926 }
8927 hlua->nargs = 1;
8928
8929 /* push keywords in the stack. */
8930 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
8931 if (!lua_checkstack(hlua->T, 1)) {
8932 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008933 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008934 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008935 return 0;
8936 }
8937 lua_pushstring(hlua->T, *arg);
8938 hlua->nargs++;
8939 }
8940
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008941 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008942
8943 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01008944 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01008945 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008946
8947 return 1;
8948}
8949
Willy Tarreau60409db2019-08-21 14:14:50 +02008950void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008951{
8952 struct stream_interface *si = ctx->owner;
8953 struct stream *strm = si_strm(si);
8954 struct channel *res = si_ic(si);
8955 struct act_rule *rule = ctx->rule;
8956 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008957 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008958
8959 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02008960 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
8961 /* eat the whole request */
8962 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008963 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02008964 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008965
8966 /* If the stream is disconnect or closed, ldo nothing. */
8967 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8968 return;
8969
8970 /* Execute the function. */
8971 switch (hlua_ctx_resume(hlua, 1)) {
8972 /* finished. */
8973 case HLUA_E_OK:
8974 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
8975
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008976 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02008977 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008978 res->flags |= CF_READ_NULL;
8979 si_shutr(si);
8980 return;
8981
8982 /* yield. */
8983 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01008984 if (hlua->wake_time != TICK_ETERNITY)
8985 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008986 return;
8987
8988 /* finished with error. */
8989 case HLUA_E_ERRMSG:
8990 /* Display log. */
8991 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008992 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008993 lua_pop(hlua->T, 1);
8994 goto error;
8995
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008996 case HLUA_E_ETMOUT:
8997 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01008998 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008999 goto error;
9000
9001 case HLUA_E_NOMEM:
9002 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009003 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009004 goto error;
9005
9006 case HLUA_E_YIELD: /* unexpected */
9007 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009008 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009009 goto error;
9010
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009011 case HLUA_E_ERR:
9012 /* Display log. */
9013 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009014 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009015 goto error;
9016
9017 default:
9018 goto error;
9019 }
9020
9021error:
9022
9023 /* For all other cases, just close the stream. */
9024 si_shutw(si);
9025 si_shutr(si);
9026 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
9027}
9028
9029static void hlua_applet_tcp_release(struct appctx *ctx)
9030{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009031 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009032 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009033 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009034 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009035}
9036
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009037/* The function returns 1 if the initialisation is complete, 0 if
9038 * an errors occurs and -1 if more data are required for initializing
9039 * the applet.
9040 */
9041static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
9042{
9043 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009044 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009045 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009046 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009047 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009048 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009049
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009050 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01009051 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009052 if (!hlua) {
9053 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009054 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009055 return 0;
9056 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009057 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009058 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009059 ctx->ctx.hlua_apphttp.left_bytes = -1;
9060 ctx->ctx.hlua_apphttp.flags = 0;
9061
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01009062 if (txn->req.flags & HTTP_MSGF_VER_11)
9063 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
9064
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009065 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01009066 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009067 if (!task) {
9068 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009069 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009070 return 0;
9071 }
9072 task->nice = 0;
9073 task->context = ctx;
9074 task->process = hlua_applet_wakeup;
9075 ctx->ctx.hlua_apphttp.task = task;
9076
9077 /* In the execution wrappers linked with a stream, the
9078 * Lua context can be not initialized. This behavior
9079 * permits to save performances because a systematic
9080 * Lua initialization cause 5% performances loss.
9081 */
Thierry Fournierc7492592020-11-28 23:57:24 +01009082 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009083 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009084 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009085 return 0;
9086 }
9087
9088 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02009089 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009090
9091 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009092 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01009093 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9094 error = lua_tostring(hlua->T, -1);
9095 else
9096 error = "critical error";
9097 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009098 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009099 return 0;
9100 }
9101
9102 /* Check stack available size. */
9103 if (!lua_checkstack(hlua->T, 1)) {
9104 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009105 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009106 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009107 return 0;
9108 }
9109
9110 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009111 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009112
9113 /* Create and and push object stream in the stack. */
9114 if (!hlua_applet_http_new(hlua->T, ctx)) {
9115 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009116 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009117 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009118 return 0;
9119 }
9120 hlua->nargs = 1;
9121
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009122 /* push keywords in the stack. */
9123 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
9124 if (!lua_checkstack(hlua->T, 1)) {
9125 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009126 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009127 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009128 return 0;
9129 }
9130 lua_pushstring(hlua->T, *arg);
9131 hlua->nargs++;
9132 }
9133
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009134 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009135
9136 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01009137 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009138
9139 return 1;
9140}
9141
Willy Tarreau60409db2019-08-21 14:14:50 +02009142void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009143{
9144 struct stream_interface *si = ctx->owner;
9145 struct stream *strm = si_strm(si);
9146 struct channel *req = si_oc(si);
9147 struct channel *res = si_ic(si);
9148 struct act_rule *rule = ctx->rule;
9149 struct proxy *px = strm->be;
9150 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
9151 struct htx *req_htx, *res_htx;
9152
9153 res_htx = htx_from_buf(&res->buf);
9154
9155 /* If the stream is disconnect or closed, ldo nothing. */
9156 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9157 goto out;
9158
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009159 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009160 if (!b_size(&res->buf)) {
9161 si_rx_room_blk(si);
9162 goto out;
9163 }
9164 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009165 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009166 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9167
9168 /* Set the currently running flag. */
9169 if (!HLUA_IS_RUNNING(hlua) &&
9170 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02009171 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009172 si_cant_get(si);
9173 goto out;
9174 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009175 }
9176
9177 /* Executes The applet if it is not done. */
9178 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
9179
9180 /* Execute the function. */
9181 switch (hlua_ctx_resume(hlua, 1)) {
9182 /* finished. */
9183 case HLUA_E_OK:
9184 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9185 break;
9186
9187 /* yield. */
9188 case HLUA_E_AGAIN:
9189 if (hlua->wake_time != TICK_ETERNITY)
9190 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009191 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009192
9193 /* finished with error. */
9194 case HLUA_E_ERRMSG:
9195 /* Display log. */
9196 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009197 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009198 lua_pop(hlua->T, 1);
9199 goto error;
9200
9201 case HLUA_E_ETMOUT:
9202 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009203 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009204 goto error;
9205
9206 case HLUA_E_NOMEM:
9207 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009208 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009209 goto error;
9210
9211 case HLUA_E_YIELD: /* unexpected */
9212 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009213 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009214 goto error;
9215
9216 case HLUA_E_ERR:
9217 /* Display log. */
9218 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01009219 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009220 goto error;
9221
9222 default:
9223 goto error;
9224 }
9225 }
9226
9227 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009228 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
9229 goto done;
9230
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009231 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
9232 goto error;
9233
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01009234 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
9235 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009236 strm->txn->status = ctx->ctx.hlua_apphttp.status;
9237 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009238 }
9239
9240 done:
9241 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009242 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009243 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01009244 si_shutr(si);
9245 }
9246
9247 /* eat the whole request */
9248 if (co_data(req)) {
9249 req_htx = htx_from_buf(&req->buf);
9250 co_htx_skip(req, req_htx, co_data(req));
9251 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009252 }
9253 }
9254
9255 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009256 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009257 return;
9258
9259 error:
9260
9261 /* If we are in HTTP mode, and we are not send any
9262 * data, return a 500 server error in best effort:
9263 * if there is no room available in the buffer,
9264 * just close the connection.
9265 */
9266 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02009267 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009268
9269 channel_erase(res);
9270 res->buf.data = b_data(err);
9271 memcpy(res->buf.area, b_head(err), b_data(err));
9272 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01009273 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01009274 }
9275 if (!(strm->flags & SF_ERR_MASK))
9276 strm->flags |= SF_ERR_RESOURCE;
9277 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
9278 goto done;
9279}
9280
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009281static void hlua_applet_http_release(struct appctx *ctx)
9282{
Olivier Houchard3f795f72019-04-17 22:51:06 +02009283 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009284 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009285 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009286 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009287}
9288
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009289/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009290 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009291 *
9292 * This function can fail with an abort() due to an Lua critical error.
9293 * We are in the configuration parsing process of HAProxy, this abort() is
9294 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009295 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009296static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
9297 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009298{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009299 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009300 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009301
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009302 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009303 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009304 if (!rule->arg.hlua_rule) {
9305 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009306 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009307 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009308
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009309 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02009310 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
9311 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009312 if (!rule->arg.hlua_rule->args) {
9313 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009314 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009315 }
9316
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009317 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009318 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009319
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009320 /* Expect some arguments */
9321 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009322 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009323 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02009324 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009325 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01009326 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009327 if (!rule->arg.hlua_rule->args[i]) {
9328 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02009329 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009330 }
9331 (*cur_arg)++;
9332 }
9333 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009334
Thierry FOURNIER42148732015-09-02 17:17:33 +02009335 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02009336 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02009337 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02009338
9339 error:
9340 if (rule->arg.hlua_rule) {
9341 if (rule->arg.hlua_rule->args) {
9342 for (i = 0; i < fcn->nargs; i++)
9343 ha_free(&rule->arg.hlua_rule->args[i]);
9344 ha_free(&rule->arg.hlua_rule->args);
9345 }
9346 ha_free(&rule->arg.hlua_rule);
9347 }
9348 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01009349}
9350
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009351static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
9352 struct act_rule *rule, char **err)
9353{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009354 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009355
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009356 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009357 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009358 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05009359 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01009360 * the call of this analyzer.
9361 */
9362 if (rule->from != ACT_F_HTTP_REQ) {
9363 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
9364 return ACT_RET_PRS_ERR;
9365 }
9366
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009367 /* Memory for the rule. */
9368 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9369 if (!rule->arg.hlua_rule) {
9370 memprintf(err, "out of memory error");
9371 return ACT_RET_PRS_ERR;
9372 }
9373
9374 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009375 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009376
9377 /* TODO: later accept arguments. */
9378 rule->arg.hlua_rule->args = NULL;
9379
9380 /* Add applet pointer in the rule. */
9381 rule->applet.obj_type = OBJ_TYPE_APPLET;
9382 rule->applet.name = fcn->name;
9383 rule->applet.init = hlua_applet_http_init;
9384 rule->applet.fct = hlua_applet_http_fct;
9385 rule->applet.release = hlua_applet_http_release;
9386 rule->applet.timeout = hlua_timeout_applet;
9387
9388 return ACT_RET_PRS_OK;
9389}
9390
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009391/* This function is an LUA binding used for registering
9392 * "sample-conv" functions. It expects a converter name used
9393 * in the haproxy configuration file, and an LUA function.
9394 */
9395__LJMP static int hlua_register_action(lua_State *L)
9396{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009397 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009398 const char *name;
9399 int ref;
9400 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009401 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009402 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009403 struct buffer *trash;
9404 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009405
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009406 /* Initialise the number of expected arguments at 0. */
9407 nargs = 0;
9408
9409 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
9410 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009411
9412 /* First argument : converter name. */
9413 name = MAY_LJMP(luaL_checkstring(L, 1));
9414
9415 /* Second argument : environment. */
9416 if (lua_type(L, 2) != LUA_TTABLE)
9417 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9418
9419 /* Third argument : lua function. */
9420 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9421
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009422 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009423 if (lua_gettop(L) >= 4)
9424 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
9425
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009426 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009427 lua_pushnil(L);
9428 while (lua_next(L, 2) != 0) {
9429 if (lua_type(L, -1) != LUA_TSTRING)
9430 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
9431
Thierry Fournierf67442e2020-11-28 20:41:07 +01009432 /* Check if action exists */
9433 trash = get_trash_chunk();
9434 chunk_printf(trash, "lua.%s", name);
9435 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
9436 akw = tcp_req_cont_action(trash->area);
9437 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
9438 akw = tcp_res_cont_action(trash->area);
9439 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
9440 akw = action_http_req_custom(trash->area);
9441 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
9442 akw = action_http_res_custom(trash->area);
9443 } else {
9444 akw = NULL;
9445 }
9446 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009447 fcn = akw->private;
9448 if (fcn->function_ref[hlua_state_id] != -1) {
9449 ha_warning("Trying to register action 'lua.%s' more than once. "
9450 "This will become a hard error in version 2.5.\n", name);
9451 }
9452 fcn->function_ref[hlua_state_id] = ref;
9453
9454 /* pop the environment string. */
9455 lua_pop(L, 1);
9456 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009457 }
9458
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009459 /* Check required environment. Only accepted "http" or "tcp". */
9460 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009461 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009462 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009463 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009464 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009465 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009466 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009467
9468 /* Fill fcn. */
9469 fcn->name = strdup(name);
9470 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009471 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01009472 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009473
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07009474 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01009475 fcn->nargs = nargs;
9476
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009477 /* List head */
9478 akl->list.n = akl->list.p = NULL;
9479
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009480 /* action keyword. */
9481 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02009482 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009483 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009484 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009485
9486 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9487
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009488 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009489 akl->kw[0].private = fcn;
9490 akl->kw[0].parse = action_register_lua;
9491
9492 /* select the action registering point. */
9493 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
9494 tcp_req_cont_keywords_register(akl);
9495 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
9496 tcp_res_cont_keywords_register(akl);
9497 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
9498 http_req_keywords_register(akl);
9499 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
9500 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009501 else {
9502 release_hlua_function(fcn);
9503 if (akl)
9504 ha_free((char **)&(akl->kw[0].kw));
9505 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009506 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009507 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
9508 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009509 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009510
9511 /* pop the environment string. */
9512 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009513
9514 /* reset for next loop */
9515 akl = NULL;
9516 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009517 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009518 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02009519
9520 alloc_error:
9521 release_hlua_function(fcn);
9522 ha_free(&akl);
9523 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9524 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009525}
9526
9527static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
9528 struct act_rule *rule, char **err)
9529{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02009530 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009531
Christopher Faulet280f85b2019-07-15 15:02:04 +02009532 if (px->mode == PR_MODE_HTTP) {
9533 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01009534 return ACT_RET_PRS_ERR;
9535 }
9536
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009537 /* Memory for the rule. */
9538 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
9539 if (!rule->arg.hlua_rule) {
9540 memprintf(err, "out of memory error");
9541 return ACT_RET_PRS_ERR;
9542 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009543
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009544 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01009545 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009546
9547 /* TODO: later accept arguments. */
9548 rule->arg.hlua_rule->args = NULL;
9549
9550 /* Add applet pointer in the rule. */
9551 rule->applet.obj_type = OBJ_TYPE_APPLET;
9552 rule->applet.name = fcn->name;
9553 rule->applet.init = hlua_applet_tcp_init;
9554 rule->applet.fct = hlua_applet_tcp_fct;
9555 rule->applet.release = hlua_applet_tcp_release;
9556 rule->applet.timeout = hlua_timeout_applet;
9557
9558 return 0;
9559}
9560
9561/* This function is an LUA binding used for registering
9562 * "sample-conv" functions. It expects a converter name used
9563 * in the haproxy configuration file, and an LUA function.
9564 */
9565__LJMP static int hlua_register_service(lua_State *L)
9566{
9567 struct action_kw_list *akl;
9568 const char *name;
9569 const char *env;
9570 int ref;
9571 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009572 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009573 struct buffer *trash;
9574 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009575
9576 MAY_LJMP(check_args(L, 3, "register_service"));
9577
9578 /* First argument : converter name. */
9579 name = MAY_LJMP(luaL_checkstring(L, 1));
9580
9581 /* Second argument : environment. */
9582 env = MAY_LJMP(luaL_checkstring(L, 2));
9583
9584 /* Third argument : lua function. */
9585 ref = MAY_LJMP(hlua_checkfunction(L, 3));
9586
Thierry Fournierf67442e2020-11-28 20:41:07 +01009587 /* Check for service already registered */
9588 trash = get_trash_chunk();
9589 chunk_printf(trash, "lua.%s", name);
9590 akw = service_find(trash->area);
9591 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009592 fcn = akw->private;
9593 if (fcn->function_ref[hlua_state_id] != -1) {
9594 ha_warning("Trying to register service 'lua.%s' more than once. "
9595 "This will become a hard error in version 2.5.\n", name);
9596 }
9597 fcn->function_ref[hlua_state_id] = ref;
9598 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009599 }
9600
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009601 /* Allocate and fill the sample fetch keyword struct. */
9602 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
9603 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009604 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009605 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009606 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009607 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009608
9609 /* Fill fcn. */
9610 len = strlen("<lua.>") + strlen(name) + 1;
9611 fcn->name = calloc(1, len);
9612 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009613 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009614 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01009615 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009616
9617 /* List head */
9618 akl->list.n = akl->list.p = NULL;
9619
9620 /* converter keyword. */
9621 len = strlen("lua.") + strlen(name) + 1;
9622 akl->kw[0].kw = calloc(1, len);
9623 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02009624 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009625
9626 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
9627
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01009628 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009629 if (strcmp(env, "tcp") == 0)
9630 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009631 else if (strcmp(env, "http") == 0)
9632 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009633 else {
9634 release_hlua_function(fcn);
9635 if (akl)
9636 ha_free((char **)&(akl->kw[0].kw));
9637 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01009638 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01009639 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02009640 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009641
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02009642 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009643 akl->kw[0].private = fcn;
9644
9645 /* End of array. */
9646 memset(&akl->kw[1], 0, sizeof(*akl->kw));
9647
9648 /* Register this new converter */
9649 service_keywords_register(akl);
9650
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009651 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02009652
9653 alloc_error:
9654 release_hlua_function(fcn);
9655 ha_free(&akl);
9656 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
9657 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02009658}
9659
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009660/* This function initialises Lua cli handler. It copies the
9661 * arguments in the Lua stack and create channel IO objects.
9662 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02009663static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009664{
9665 struct hlua *hlua;
9666 struct hlua_function *fcn;
9667 int i;
9668 const char *error;
9669
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009670 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009671 appctx->ctx.hlua_cli.fcn = private;
9672
Willy Tarreaubafbe012017-11-24 17:34:44 +01009673 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009674 if (!hlua) {
9675 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009676 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009677 }
9678 HLUA_INIT(hlua);
9679 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009680
9681 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05009682 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009683 * applet_http. It is absolutely compatible.
9684 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01009685 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009686 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01009687 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009688 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009689 }
9690 appctx->ctx.hlua_cli.task->nice = 0;
9691 appctx->ctx.hlua_cli.task->context = appctx;
9692 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
9693
9694 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +01009695 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009696 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009697 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009698 }
9699
9700 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009701 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009702 if (lua_type(hlua->T, -1) == LUA_TSTRING)
9703 error = lua_tostring(hlua->T, -1);
9704 else
9705 error = "critical error";
9706 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
9707 goto error;
9708 }
9709
9710 /* Check stack available size. */
9711 if (!lua_checkstack(hlua->T, 2)) {
9712 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9713 goto error;
9714 }
9715
9716 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01009717 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009718
9719 /* Once the arguments parsed, the CLI is like an AppletTCP,
9720 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009721 */
9722 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
9723 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9724 goto error;
9725 }
9726 hlua->nargs = 1;
9727
9728 /* push keywords in the stack. */
9729 for (i = 0; *args[i]; i++) {
9730 /* Check stack available size. */
9731 if (!lua_checkstack(hlua->T, 1)) {
9732 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
9733 goto error;
9734 }
9735 lua_pushstring(hlua->T, args[i]);
9736 hlua->nargs++;
9737 }
9738
9739 /* We must initialize the execution timeouts. */
9740 hlua->max_time = hlua_timeout_session;
9741
9742 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009743 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009744
9745 /* It's ok */
9746 return 0;
9747
9748 /* It's not ok. */
9749error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +01009750 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009751 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01009752 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009753 return 1;
9754}
9755
9756static int hlua_cli_io_handler_fct(struct appctx *appctx)
9757{
9758 struct hlua *hlua;
9759 struct stream_interface *si;
9760 struct hlua_function *fcn;
9761
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009762 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009763 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01009764 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009765
9766 /* If the stream is disconnect or closed, ldo nothing. */
9767 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
9768 return 1;
9769
9770 /* Execute the function. */
9771 switch (hlua_ctx_resume(hlua, 1)) {
9772
9773 /* finished. */
9774 case HLUA_E_OK:
9775 return 1;
9776
9777 /* yield. */
9778 case HLUA_E_AGAIN:
9779 /* We want write. */
9780 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01009781 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009782 /* Set the timeout. */
9783 if (hlua->wake_time != TICK_ETERNITY)
9784 task_schedule(hlua->task, hlua->wake_time);
9785 return 0;
9786
9787 /* finished with error. */
9788 case HLUA_E_ERRMSG:
9789 /* Display log. */
9790 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
9791 fcn->name, lua_tostring(hlua->T, -1));
9792 lua_pop(hlua->T, 1);
9793 return 1;
9794
Thierry Fournierd5b073c2018-05-21 19:42:47 +02009795 case HLUA_E_ETMOUT:
9796 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
9797 fcn->name);
9798 return 1;
9799
9800 case HLUA_E_NOMEM:
9801 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
9802 fcn->name);
9803 return 1;
9804
9805 case HLUA_E_YIELD: /* unexpected */
9806 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
9807 fcn->name);
9808 return 1;
9809
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009810 case HLUA_E_ERR:
9811 /* Display log. */
9812 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
9813 fcn->name);
9814 return 1;
9815
9816 default:
9817 return 1;
9818 }
9819
9820 return 1;
9821}
9822
9823static void hlua_cli_io_release_fct(struct appctx *appctx)
9824{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009825 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01009826 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009827}
9828
9829/* This function is an LUA binding used for registering
9830 * new keywords in the cli. It expects a list of keywords
9831 * which are the "path". It is limited to 5 keywords. A
9832 * description of the command, a function to be executed
9833 * for the parsing and a function for io handlers.
9834 */
9835__LJMP static int hlua_register_cli(lua_State *L)
9836{
9837 struct cli_kw_list *cli_kws;
9838 const char *message;
9839 int ref_io;
9840 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009841 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009842 int index;
9843 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009844 struct buffer *trash;
9845 const char *kw[5];
9846 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009847 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009848
9849 MAY_LJMP(check_args(L, 3, "register_cli"));
9850
9851 /* First argument : an array of maximum 5 keywords. */
9852 if (!lua_istable(L, 1))
9853 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
9854
9855 /* Second argument : string with contextual message. */
9856 message = MAY_LJMP(luaL_checkstring(L, 2));
9857
9858 /* Third and fourth argument : lua function. */
9859 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
9860
Thierry Fournierf67442e2020-11-28 20:41:07 +01009861 /* Check for CLI service already registered */
9862 trash = get_trash_chunk();
9863 index = 0;
9864 lua_pushnil(L);
9865 memset(kw, 0, sizeof(kw));
9866 while (lua_next(L, 1) != 0) {
9867 if (index >= CLI_PREFIX_KW_NB)
9868 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
9869 if (lua_type(L, -1) != LUA_TSTRING)
9870 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
9871 kw[index] = lua_tostring(L, -1);
9872 if (index == 0)
9873 chunk_printf(trash, "%s", kw[index]);
9874 else
9875 chunk_appendf(trash, " %s", kw[index]);
9876 index++;
9877 lua_pop(L, 1);
9878 }
9879 cli_kw = cli_find_kw_exact((char **)kw);
9880 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01009881 fcn = cli_kw->private;
9882 if (fcn->function_ref[hlua_state_id] != -1) {
9883 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
9884 "This will become a hard error in version 2.5.\n", trash->area);
9885 }
9886 fcn->function_ref[hlua_state_id] = ref_io;
9887 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01009888 }
9889
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009890 /* Allocate and fill the sample fetch keyword struct. */
9891 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009892 if (!cli_kws) {
9893 errmsg = "Lua out of memory error.";
9894 goto error;
9895 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +01009896 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009897 if (!fcn) {
9898 errmsg = "Lua out of memory error.";
9899 goto error;
9900 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009901
9902 /* Fill path. */
9903 index = 0;
9904 lua_pushnil(L);
9905 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009906 if (index >= 5) {
9907 errmsg = "1st argument must be a table with a maximum of 5 entries";
9908 goto error;
9909 }
9910 if (lua_type(L, -1) != LUA_TSTRING) {
9911 errmsg = "1st argument must be a table filled with strings";
9912 goto error;
9913 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009914 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009915 if (!cli_kws->kw[0].str_kw[index]) {
9916 errmsg = "Lua out of memory error.";
9917 goto error;
9918 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009919 index++;
9920 lua_pop(L, 1);
9921 }
9922
9923 /* Copy help message. */
9924 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009925 if (!cli_kws->kw[0].usage) {
9926 errmsg = "Lua out of memory error.";
9927 goto error;
9928 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009929
9930 /* Fill fcn io handler. */
9931 len = strlen("<lua.cli>") + 1;
9932 for (i = 0; i < index; i++)
9933 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
9934 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009935 if (!fcn->name) {
9936 errmsg = "Lua out of memory error.";
9937 goto error;
9938 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009939 strncat((char *)fcn->name, "<lua.cli", len);
9940 for (i = 0; i < index; i++) {
9941 strncat((char *)fcn->name, ".", len);
9942 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
9943 }
9944 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +01009945 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009946
9947 /* Fill last entries. */
9948 cli_kws->kw[0].private = fcn;
9949 cli_kws->kw[0].parse = hlua_cli_parse_fct;
9950 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
9951 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
9952
9953 /* Register this new converter */
9954 cli_register_kw(cli_kws);
9955
9956 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02009957
9958 error:
9959 release_hlua_function(fcn);
9960 if (cli_kws) {
9961 for (i = 0; i < index; i++)
9962 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
9963 ha_free((char **)&(cli_kws->kw[0].usage));
9964 }
9965 ha_free(&cli_kws);
9966 WILL_LJMP(luaL_error(L, errmsg));
9967 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01009968}
9969
Christopher Faulet69c581a2021-05-31 08:54:04 +02009970static int hlua_filter_init_per_thread(struct proxy *px, struct flt_conf *fconf)
9971{
9972 struct hlua_flt_config *conf = fconf->conf;
9973 lua_State *L;
9974 int error, pos, state_id, flt_ref;
9975
9976 state_id = reg_flt_to_stack_id(conf->reg);
9977 L = hlua_states[state_id];
9978 pos = lua_gettop(L);
9979
9980 /* The filter parsing function */
9981 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->fun_ref[state_id]);
9982
9983 /* Push the filter class on the stack and resolve all callbacks */
9984 lua_rawgeti(L, LUA_REGISTRYINDEX, conf->reg->flt_ref[state_id]);
9985
9986 /* Duplicate the filter class so each filter will have its own copy */
9987 lua_newtable(L);
9988 lua_pushnil(L);
9989
9990 while (lua_next(L, pos+2)) {
9991 lua_pushvalue(L, -2);
9992 lua_insert(L, -2);
9993 lua_settable(L, -4);
9994 }
9995 flt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
9996
9997 /* Remove the original lua filter class from the stack */
9998 lua_pop(L, 1);
9999
10000 /* Push the copy on the stack */
10001 lua_rawgeti(L, LUA_REGISTRYINDEX, flt_ref);
10002
10003 /* extra args are pushed in a table */
10004 lua_newtable(L);
10005 for (pos = 0; conf->args[pos]; pos++) {
10006 /* Check stack available size. */
10007 if (!lua_checkstack(L, 1)) {
10008 ha_alert("Lua filter '%s' : Lua error : full stack.", conf->reg->name);
10009 goto error;
10010 }
10011 lua_pushstring(L, conf->args[pos]);
10012 lua_rawseti(L, -2, lua_rawlen(L, -2) + 1);
10013 }
10014
10015 error = lua_pcall(L, 2, LUA_MULTRET, 0);
10016 switch (error) {
10017 case LUA_OK:
10018 /* replace the filter ref */
10019 conf->ref[state_id] = flt_ref;
10020 break;
10021 case LUA_ERRRUN:
10022 ha_alert("Lua filter '%s' : runtime error : %s", conf->reg->name, lua_tostring(L, -1));
10023 goto error;
10024 case LUA_ERRMEM:
10025 ha_alert("Lua filter '%s' : out of memory error", conf->reg->name);
10026 goto error;
10027 case LUA_ERRERR:
10028 ha_alert("Lua filter '%s' : message handler error : %s", conf->reg->name, lua_tostring(L, -1));
10029 goto error;
10030#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
10031 case LUA_ERRGCMM:
10032 ha_alert("Lua filter '%s' : garbage collector error : %s", conf->reg->name, lua_tostring(L, -1));
10033 goto error;
10034#endif
10035 default:
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010036 ha_alert("Lua filter '%s' : unknown error : %s", conf->reg->name, lua_tostring(L, -1));
Christopher Faulet69c581a2021-05-31 08:54:04 +020010037 goto error;
10038 }
10039
10040 lua_settop(L, 0);
10041 return 0;
10042
10043 error:
10044 lua_settop(L, 0);
10045 return -1;
10046}
10047
10048static void hlua_filter_deinit_per_thread(struct proxy *px, struct flt_conf *fconf)
10049{
10050 struct hlua_flt_config *conf = fconf->conf;
10051 lua_State *L;
10052 int state_id;
10053
10054 if (!conf)
10055 return;
10056
10057 state_id = reg_flt_to_stack_id(conf->reg);
10058 L = hlua_states[state_id];
10059 luaL_unref(L, LUA_REGISTRYINDEX, conf->ref[state_id]);
10060}
10061
10062static int hlua_filter_init(struct proxy *px, struct flt_conf *fconf)
10063{
10064 struct hlua_flt_config *conf = fconf->conf;
10065 int state_id = reg_flt_to_stack_id(conf->reg);
10066
10067 /* Rely on per-thread init for global scripts */
10068 if (!state_id)
10069 return hlua_filter_init_per_thread(px, fconf);
10070 return 0;
10071}
10072
10073static void hlua_filter_deinit(struct proxy *px, struct flt_conf *fconf)
10074{
10075
10076 if (fconf->conf) {
10077 struct hlua_flt_config *conf = fconf->conf;
10078 int state_id = reg_flt_to_stack_id(conf->reg);
10079 int pos;
10080
10081 /* Rely on per-thread deinit for global scripts */
10082 if (!state_id)
10083 hlua_filter_deinit_per_thread(px, fconf);
10084
10085 for (pos = 0; conf->args[pos]; pos++)
10086 free(conf->args[pos]);
10087 free(conf->args);
10088 }
10089 ha_free(&fconf->conf);
10090 ha_free((char **)&fconf->id);
10091 ha_free(&fconf->ops);
10092}
10093
10094static int hlua_filter_new(struct stream *s, struct filter *filter)
10095{
10096 struct hlua_flt_config *conf = FLT_CONF(filter);
10097 struct hlua_flt_ctx *flt_ctx = NULL;
10098 int ret = 1;
10099
10100 /* In the execution wrappers linked with a stream, the
10101 * Lua context can be not initialized. This behavior
10102 * permits to save performances because a systematic
10103 * Lua initialization cause 5% performances loss.
10104 */
10105 if (!s->hlua) {
10106 struct hlua *hlua;
10107
10108 hlua = pool_alloc(pool_head_hlua);
10109 if (!hlua) {
10110 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10111 conf->reg->name);
10112 ret = 0;
10113 goto end;
10114 }
10115 HLUA_INIT(hlua);
10116 s->hlua = hlua;
10117 if (!hlua_ctx_init(s->hlua, reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10118 SEND_ERR(s->be, "Lua filter '%s': can't initialize Lua context.\n",
10119 conf->reg->name);
10120 ret = 0;
10121 goto end;
10122 }
10123 }
10124
10125 flt_ctx = pool_zalloc(pool_head_hlua_flt_ctx);
10126 if (!flt_ctx) {
10127 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10128 conf->reg->name);
10129 ret = 0;
10130 goto end;
10131 }
10132 flt_ctx->hlua[0] = pool_alloc(pool_head_hlua);
10133 flt_ctx->hlua[1] = pool_alloc(pool_head_hlua);
10134 if (!flt_ctx->hlua[0] || !flt_ctx->hlua[1]) {
10135 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10136 conf->reg->name);
10137 ret = 0;
10138 goto end;
10139 }
10140 HLUA_INIT(flt_ctx->hlua[0]);
10141 HLUA_INIT(flt_ctx->hlua[1]);
10142 if (!hlua_ctx_init(flt_ctx->hlua[0], reg_flt_to_stack_id(conf->reg), s->task, 0) ||
10143 !hlua_ctx_init(flt_ctx->hlua[1], reg_flt_to_stack_id(conf->reg), s->task, 0)) {
10144 SEND_ERR(s->be, "Lua filter '%s': can't initialize filter Lua context.\n",
10145 conf->reg->name);
10146 ret = 0;
10147 goto end;
10148 }
10149
10150 if (!HLUA_IS_RUNNING(s->hlua)) {
10151 /* The following Lua calls can fail. */
10152 if (!SET_SAFE_LJMP(s->hlua)) {
10153 const char *error;
10154
10155 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
10156 error = lua_tostring(s->hlua->T, -1);
10157 else
10158 error = "critical error";
10159 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10160 ret = 0;
10161 goto end;
10162 }
10163
10164 /* Check stack size. */
10165 if (!lua_checkstack(s->hlua->T, 1)) {
10166 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
Tim Duesterhus22817382021-09-11 23:17:25 +020010167 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010168 ret = 0;
10169 goto end;
10170 }
10171
10172 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, conf->ref[s->hlua->state_id]);
10173 if (lua_getfield(s->hlua->T, -1, "new") != LUA_TFUNCTION) {
10174 SEND_ERR(s->be, "Lua filter '%s': 'new' field is not a function.\n",
10175 conf->reg->name);
10176 RESET_SAFE_LJMP(s->hlua);
10177 ret = 0;
10178 goto end;
10179 }
10180 lua_insert(s->hlua->T, -2);
10181
10182 /* Push the copy on the stack */
10183 s->hlua->nargs = 1;
10184
10185 /* We must initialize the execution timeouts. */
10186 s->hlua->max_time = hlua_timeout_session;
10187
10188 /* At this point the execution is safe. */
10189 RESET_SAFE_LJMP(s->hlua);
10190 }
10191
10192 switch (hlua_ctx_resume(s->hlua, 0)) {
10193 case HLUA_E_OK:
10194 /* Nothing returned or not a table, ignore the filter for current stream */
10195 if (!lua_gettop(s->hlua->T) || !lua_istable(s->hlua->T, 1)) {
10196 ret = 0;
10197 goto end;
10198 }
10199
10200 /* Attached the filter pointer to the ctx */
10201 lua_pushstring(s->hlua->T, "__filter");
10202 lua_pushlightuserdata(s->hlua->T, filter);
10203 lua_settable(s->hlua->T, -3);
10204
10205 /* Save a ref on the filter ctx */
10206 lua_pushvalue(s->hlua->T, 1);
10207 flt_ctx->ref = luaL_ref(s->hlua->T, LUA_REGISTRYINDEX);
10208 filter->ctx = flt_ctx;
10209 break;
10210 case HLUA_E_ERRMSG:
10211 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(s->hlua->T, -1));
10212 ret = -1;
10213 goto end;
10214 case HLUA_E_ETMOUT:
10215 SEND_ERR(s->be, "Lua filter '%s' : 'new' execution timeout.\n", conf->reg->name);
10216 ret = 0;
10217 goto end;
10218 case HLUA_E_NOMEM:
10219 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10220 ret = 0;
10221 goto end;
10222 case HLUA_E_AGAIN:
10223 case HLUA_E_YIELD:
10224 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10225 " are not allowed from 'new' function.\n", conf->reg->name);
10226 ret = 0;
10227 goto end;
10228 case HLUA_E_ERR:
10229 SEND_ERR(s->be, "Lua filter '%s': 'new' returns an unknown error.\n", conf->reg->name);
10230 ret = 0;
10231 goto end;
10232 default:
10233 ret = 0;
10234 goto end;
10235 }
10236
10237 end:
10238 if (s->hlua)
10239 lua_settop(s->hlua->T, 0);
10240 if (ret <= 0) {
10241 if (flt_ctx) {
10242 hlua_ctx_destroy(flt_ctx->hlua[0]);
10243 hlua_ctx_destroy(flt_ctx->hlua[1]);
10244 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10245 }
10246 }
10247 return ret;
10248}
10249
10250static void hlua_filter_delete(struct stream *s, struct filter *filter)
10251{
10252 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10253
10254 luaL_unref(s->hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10255 hlua_ctx_destroy(flt_ctx->hlua[0]);
10256 hlua_ctx_destroy(flt_ctx->hlua[1]);
10257 pool_free(pool_head_hlua_flt_ctx, flt_ctx);
10258 filter->ctx = NULL;
10259}
10260
Christopher Faulet9f55a502020-02-25 15:21:02 +010010261static int hlua_filter_from_payload(struct filter *filter)
10262{
10263 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10264
10265 return (flt_ctx && !!(flt_ctx->flags & HLUA_FLT_CTX_FL_PAYLOAD));
10266}
10267
Christopher Fauletc404f112020-02-26 15:03:09 +010010268static int hlua_filter_callback(struct stream *s, struct filter *filter, const char *fun,
10269 int dir, unsigned int flags)
10270{
10271 struct hlua *flt_hlua;
10272 struct hlua_flt_config *conf = FLT_CONF(filter);
10273 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10274 unsigned int hflags = HLUA_TXN_FLT_CTX;
10275 int ret = 1;
10276
10277 flt_hlua = flt_ctx->hlua[(dir == SMP_OPT_DIR_REQ ? 0 : 1)];
10278 if (!flt_hlua)
10279 goto end;
10280
10281 if (!HLUA_IS_RUNNING(flt_hlua)) {
10282 int extra_idx = lua_gettop(flt_hlua->T);
10283
10284 /* The following Lua calls can fail. */
10285 if (!SET_SAFE_LJMP(flt_hlua)) {
10286 const char *error;
10287
10288 if (lua_type(flt_hlua->T, -1) == LUA_TSTRING)
10289 error = lua_tostring(flt_hlua->T, -1);
10290 else
10291 error = "critical error";
10292 SEND_ERR(s->be, "Lua filter '%s': %s.\n", conf->reg->name, error);
10293 goto end;
10294 }
10295
10296 /* Check stack size. */
10297 if (!lua_checkstack(flt_hlua->T, 3)) {
10298 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10299 RESET_SAFE_LJMP(flt_hlua);
10300 goto end;
10301 }
10302
10303 lua_rawgeti(flt_hlua->T, LUA_REGISTRYINDEX, flt_ctx->ref);
10304 if (lua_getfield(flt_hlua->T, -1, fun) != LUA_TFUNCTION) {
10305 RESET_SAFE_LJMP(flt_hlua);
10306 goto end;
10307 }
10308 lua_insert(flt_hlua->T, -2);
10309
10310 if (!hlua_txn_new(flt_hlua->T, s, s->be, dir, hflags)) {
10311 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10312 RESET_SAFE_LJMP(flt_hlua);
10313 goto end;
10314 }
10315 flt_hlua->nargs = 2;
10316
10317 if (flags & HLUA_FLT_CB_ARG_CHN) {
10318 if (dir == SMP_OPT_DIR_REQ)
10319 lua_getfield(flt_hlua->T, -1, "req");
10320 else
10321 lua_getfield(flt_hlua->T, -1, "res");
10322 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10323 lua_pushstring(flt_hlua->T, "__filter");
10324 lua_pushlightuserdata(flt_hlua->T, filter);
10325 lua_settable(flt_hlua->T, -3);
10326 }
10327 flt_hlua->nargs++;
10328 }
10329 else if (flags & HLUA_FLT_CB_ARG_HTTP_MSG) {
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010330 if (dir == SMP_OPT_DIR_REQ)
10331 lua_getfield(flt_hlua->T, -1, "http_req");
10332 else
10333 lua_getfield(flt_hlua->T, -1, "http_res");
10334 if (lua_type(flt_hlua->T, -1) == LUA_TTABLE) {
10335 lua_pushstring(flt_hlua->T, "__filter");
10336 lua_pushlightuserdata(flt_hlua->T, filter);
10337 lua_settable(flt_hlua->T, -3);
10338 }
10339 flt_hlua->nargs++;
Christopher Fauletc404f112020-02-26 15:03:09 +010010340 }
10341
10342 /* Check stack size. */
10343 if (!lua_checkstack(flt_hlua->T, 1)) {
10344 SEND_ERR(s->be, "Lua filter '%s': full stack.\n", conf->reg->name);
10345 RESET_SAFE_LJMP(flt_hlua);
10346 goto end;
10347 }
10348
10349 while (extra_idx--) {
10350 lua_pushvalue(flt_hlua->T, 1);
10351 lua_remove(flt_hlua->T, 1);
10352 flt_hlua->nargs++;
10353 }
10354
10355 /* We must initialize the execution timeouts. */
10356 flt_hlua->max_time = hlua_timeout_session;
10357
10358 /* At this point the execution is safe. */
10359 RESET_SAFE_LJMP(flt_hlua);
10360 }
10361
10362 switch (hlua_ctx_resume(flt_hlua, !(flags & HLUA_FLT_CB_FINAL))) {
10363 case HLUA_E_OK:
10364 /* Catch the return value if it required */
10365 if ((flags & HLUA_FLT_CB_RETVAL) && lua_gettop(flt_hlua->T) > 0) {
10366 ret = lua_tointeger(flt_hlua->T, -1);
10367 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10368 }
10369
10370 /* Set timeout in the required channel. */
10371 if (flt_hlua->wake_time != TICK_ETERNITY) {
10372 if (dir == SMP_OPT_DIR_REQ)
10373 s->req.analyse_exp = flt_hlua->wake_time;
10374 else
10375 s->res.analyse_exp = flt_hlua->wake_time;
10376 }
10377 break;
10378 case HLUA_E_AGAIN:
10379 /* Set timeout in the required channel. */
10380 if (flt_hlua->wake_time != TICK_ETERNITY) {
10381 if (dir == SMP_OPT_DIR_REQ)
10382 s->req.analyse_exp = flt_hlua->wake_time;
10383 else
10384 s->res.analyse_exp = flt_hlua->wake_time;
10385 }
10386 /* Some actions can be wake up when a "write" event
10387 * is detected on a response channel. This is useful
10388 * only for actions targeted on the requests.
10389 */
10390 if (HLUA_IS_WAKERESWR(flt_hlua))
10391 s->res.flags |= CF_WAKE_WRITE;
10392 if (HLUA_IS_WAKEREQWR(flt_hlua))
10393 s->req.flags |= CF_WAKE_WRITE;
10394 ret = 0;
10395 goto end;
10396 case HLUA_E_ERRMSG:
10397 SEND_ERR(s->be, "Lua filter '%s' : %s.\n", conf->reg->name, lua_tostring(flt_hlua->T, -1));
10398 ret = -1;
10399 goto end;
10400 case HLUA_E_ETMOUT:
10401 SEND_ERR(s->be, "Lua filter '%s' : '%s' callback execution timeout.\n", conf->reg->name, fun);
10402 goto end;
10403 case HLUA_E_NOMEM:
10404 SEND_ERR(s->be, "Lua filter '%s' : out of memory error.\n", conf->reg->name);
10405 goto end;
10406 case HLUA_E_YIELD:
10407 SEND_ERR(s->be, "Lua filter '%s': yield functions like core.tcp() or core.sleep()"
10408 " are not allowed from '%s' callback.\n", conf->reg->name, fun);
10409 goto end;
10410 case HLUA_E_ERR:
10411 SEND_ERR(s->be, "Lua filter '%s': '%s' returns an unknown error.\n", conf->reg->name, fun);
10412 goto end;
10413 default:
10414 goto end;
10415 }
10416
10417
10418 end:
10419 return ret;
10420}
10421
10422static int hlua_filter_start_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10423{
10424 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10425
10426 flt_ctx->flags = 0;
10427 return hlua_filter_callback(s, filter, "start_analyze",
10428 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10429 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10430}
10431
10432static int hlua_filter_end_analyze(struct stream *s, struct filter *filter, struct channel *chn)
10433{
10434 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10435
10436 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10437 return hlua_filter_callback(s, filter, "end_analyze",
10438 (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10439 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_CHN));
10440}
10441
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010442static int hlua_filter_http_headers(struct stream *s, struct filter *filter, struct http_msg *msg)
10443{
10444 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10445
10446 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10447 return hlua_filter_callback(s, filter, "http_headers",
10448 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10449 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10450}
10451
10452static int hlua_filter_http_payload(struct stream *s, struct filter *filter, struct http_msg *msg,
10453 unsigned int offset, unsigned int len)
10454{
10455 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10456 struct hlua *flt_hlua;
10457 int dir = (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10458 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10459 int ret;
10460
10461 flt_hlua = flt_ctx->hlua[idx];
10462 flt_ctx->cur_off[idx] = offset;
10463 flt_ctx->cur_len[idx] = len;
10464 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10465 ret = hlua_filter_callback(s, filter, "http_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10466 if (ret != -1) {
10467 ret = flt_ctx->cur_len[idx];
10468 if (lua_gettop(flt_hlua->T) > 0) {
10469 ret = lua_tointeger(flt_hlua->T, -1);
10470 if (ret > flt_ctx->cur_len[idx])
10471 ret = flt_ctx->cur_len[idx];
10472 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10473 }
10474 }
10475 return ret;
10476}
10477
10478static int hlua_filter_http_end(struct stream *s, struct filter *filter, struct http_msg *msg)
10479{
10480 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10481
10482 flt_ctx->flags &= ~HLUA_FLT_CTX_FL_PAYLOAD;
10483 return hlua_filter_callback(s, filter, "http_end",
10484 (!(msg->chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES),
10485 (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_RETVAL | HLUA_FLT_CB_ARG_HTTP_MSG));
10486}
10487
Christopher Fauletc404f112020-02-26 15:03:09 +010010488static int hlua_filter_tcp_payload(struct stream *s, struct filter *filter, struct channel *chn,
10489 unsigned int offset, unsigned int len)
10490{
10491 struct hlua_flt_ctx *flt_ctx = filter->ctx;
10492 struct hlua *flt_hlua;
10493 int dir = (!(chn->flags & CF_ISRESP) ? SMP_OPT_DIR_REQ : SMP_OPT_DIR_RES);
10494 int idx = (dir == SMP_OPT_DIR_REQ ? 0 : 1);
10495 int ret;
10496
10497 flt_hlua = flt_ctx->hlua[idx];
10498 flt_ctx->cur_off[idx] = offset;
10499 flt_ctx->cur_len[idx] = len;
10500 flt_ctx->flags |= HLUA_FLT_CTX_FL_PAYLOAD;
10501 ret = hlua_filter_callback(s, filter, "tcp_payload", dir, (HLUA_FLT_CB_FINAL | HLUA_FLT_CB_ARG_CHN));
10502 if (ret != -1) {
10503 ret = flt_ctx->cur_len[idx];
10504 if (lua_gettop(flt_hlua->T) > 0) {
10505 ret = lua_tointeger(flt_hlua->T, -1);
10506 if (ret > flt_ctx->cur_len[idx])
10507 ret = flt_ctx->cur_len[idx];
10508 lua_settop(flt_hlua->T, 0); /* Empty the stack. */
10509 }
10510 }
10511 return ret;
10512}
10513
Christopher Faulet69c581a2021-05-31 08:54:04 +020010514static int hlua_filter_parse_fct(char **args, int *cur_arg, struct proxy *px,
10515 struct flt_conf *fconf, char **err, void *private)
10516{
10517 struct hlua_reg_filter *reg_flt = private;
10518 lua_State *L;
10519 struct hlua_flt_config *conf = NULL;
10520 const char *flt_id = NULL;
10521 int state_id, pos, flt_flags = 0;
10522 struct flt_ops *hlua_flt_ops = NULL;
10523
10524 state_id = reg_flt_to_stack_id(reg_flt);
10525 L = hlua_states[state_id];
10526
10527 /* Initialize the filter ops with default callbacks */
10528 hlua_flt_ops = calloc(1, sizeof(*hlua_flt_ops));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010529 if (!hlua_flt_ops)
10530 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010531 hlua_flt_ops->init = hlua_filter_init;
10532 hlua_flt_ops->deinit = hlua_filter_deinit;
10533 if (state_id) {
10534 /* Set per-thread callback if script is loaded per-thread */
10535 hlua_flt_ops->init_per_thread = hlua_filter_init_per_thread;
10536 hlua_flt_ops->deinit_per_thread = hlua_filter_deinit_per_thread;
10537 }
10538 hlua_flt_ops->attach = hlua_filter_new;
10539 hlua_flt_ops->detach = hlua_filter_delete;
10540
10541 /* Push the filter class on the stack and resolve all callbacks */
10542 lua_rawgeti(L, LUA_REGISTRYINDEX, reg_flt->flt_ref[state_id]);
10543
Christopher Fauletc404f112020-02-26 15:03:09 +010010544 if (lua_getfield(L, -1, "start_analyze") == LUA_TFUNCTION)
10545 hlua_flt_ops->channel_start_analyze = hlua_filter_start_analyze;
10546 lua_pop(L, 1);
10547 if (lua_getfield(L, -1, "end_analyze") == LUA_TFUNCTION)
10548 hlua_flt_ops->channel_end_analyze = hlua_filter_end_analyze;
10549 lua_pop(L, 1);
Christopher Fauleteae8afa2020-02-26 17:15:48 +010010550 if (lua_getfield(L, -1, "http_headers") == LUA_TFUNCTION)
10551 hlua_flt_ops->http_headers = hlua_filter_http_headers;
10552 lua_pop(L, 1);
10553 if (lua_getfield(L, -1, "http_payload") == LUA_TFUNCTION)
10554 hlua_flt_ops->http_payload = hlua_filter_http_payload;
10555 lua_pop(L, 1);
10556 if (lua_getfield(L, -1, "http_end") == LUA_TFUNCTION)
10557 hlua_flt_ops->http_end = hlua_filter_http_end;
10558 lua_pop(L, 1);
Christopher Fauletc404f112020-02-26 15:03:09 +010010559 if (lua_getfield(L, -1, "tcp_payload") == LUA_TFUNCTION)
10560 hlua_flt_ops->tcp_payload = hlua_filter_tcp_payload;
10561 lua_pop(L, 1);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010562
10563 /* Get id and flags of the filter class */
10564 if (lua_getfield(L, -1, "id") == LUA_TSTRING)
10565 flt_id = lua_tostring(L, -1);
10566 lua_pop(L, 1);
10567 if (lua_getfield(L, -1, "flags") == LUA_TNUMBER)
10568 flt_flags = lua_tointeger(L, -1);
10569 lua_pop(L, 1);
10570
10571 /* Create the filter config */
10572 conf = calloc(1, sizeof(*conf));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010573 if (!conf)
Christopher Faulet69c581a2021-05-31 08:54:04 +020010574 goto error;
Christopher Faulet69c581a2021-05-31 08:54:04 +020010575 conf->reg = reg_flt;
10576
10577 /* duplicate args */
10578 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++);
10579 conf->args = calloc(pos + 1, sizeof(*conf->args));
Christopher Fauletc86bb872021-08-13 08:33:57 +020010580 if (!conf->args)
10581 goto error;
10582 for (pos = 0; *args[*cur_arg + 1 + pos]; pos++) {
Christopher Faulet69c581a2021-05-31 08:54:04 +020010583 conf->args[pos] = strdup(args[*cur_arg + 1 + pos]);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010584 if (!conf->args[pos])
10585 goto error;
10586 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010587 conf->args[pos] = NULL;
10588 *cur_arg += pos + 1;
10589
Christopher Fauletc86bb872021-08-13 08:33:57 +020010590 if (flt_id) {
10591 fconf->id = strdup(flt_id);
10592 if (!fconf->id)
10593 goto error;
10594 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010595 fconf->flags = flt_flags;
10596 fconf->conf = conf;
10597 fconf->ops = hlua_flt_ops;
10598
10599 lua_settop(L, 0);
10600 return 0;
10601
10602 error:
Christopher Fauletc86bb872021-08-13 08:33:57 +020010603 memprintf(err, "Lua filter '%s' : Lua out of memory error", reg_flt->name);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010604 free(hlua_flt_ops);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010605 if (conf && conf->args) {
10606 for (pos = 0; conf->args[pos]; pos++)
10607 free(conf->args[pos]);
10608 free(conf->args);
10609 }
Christopher Faulet69c581a2021-05-31 08:54:04 +020010610 free(conf);
Christopher Fauletc86bb872021-08-13 08:33:57 +020010611 free((char *)fconf->id);
Christopher Faulet69c581a2021-05-31 08:54:04 +020010612 lua_settop(L, 0);
10613 return -1;
10614}
10615
Christopher Fauletc404f112020-02-26 15:03:09 +010010616__LJMP static int hlua_register_data_filter(lua_State *L)
10617{
10618 struct filter *filter;
10619 struct channel *chn;
10620
10621 MAY_LJMP(check_args(L, 2, "register_data_filter"));
10622 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10623 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10624
10625 lua_getfield(L, 1, "__filter");
10626 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10627 filter = lua_touserdata (L, -1);
10628 lua_pop(L, 1);
10629
10630 register_data_filter(chn_strm(chn), chn, filter);
10631 return 1;
10632}
10633
10634__LJMP static int hlua_unregister_data_filter(lua_State *L)
10635{
10636 struct filter *filter;
10637 struct channel *chn;
10638
10639 MAY_LJMP(check_args(L, 2, "unregister_data_filter"));
10640 MAY_LJMP(luaL_checktype(L, 1, LUA_TTABLE));
10641 chn = MAY_LJMP(hlua_checkchannel(L, 2));
10642
10643 lua_getfield(L, 1, "__filter");
10644 MAY_LJMP(luaL_checktype(L, -1, LUA_TLIGHTUSERDATA));
10645 filter = lua_touserdata (L, -1);
10646 lua_pop(L, 1);
10647
10648 unregister_data_filter(chn_strm(chn), chn, filter);
10649 return 1;
10650}
10651
Christopher Faulet69c581a2021-05-31 08:54:04 +020010652/* This function is an LUA binding used for registering a filter. It expects a
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050010653 * filter name used in the haproxy configuration file and a LUA function to
Christopher Faulet69c581a2021-05-31 08:54:04 +020010654 * parse configuration arguments.
10655 */
10656__LJMP static int hlua_register_filter(lua_State *L)
10657{
10658 struct buffer *trash;
10659 struct flt_kw_list *fkl;
10660 struct flt_kw *fkw;
10661 const char *name;
10662 struct hlua_reg_filter *reg_flt= NULL;
10663 int flt_ref, fun_ref;
10664 int len;
10665
10666 MAY_LJMP(check_args(L, 3, "register_filter"));
10667
10668 /* First argument : filter name. */
10669 name = MAY_LJMP(luaL_checkstring(L, 1));
10670
10671 /* Second argument : The filter class */
10672 flt_ref = MAY_LJMP(hlua_checktable(L, 2));
10673
10674 /* Third argument : lua function. */
10675 fun_ref = MAY_LJMP(hlua_checkfunction(L, 3));
10676
10677 trash = get_trash_chunk();
10678 chunk_printf(trash, "lua.%s", name);
10679 fkw = flt_find_kw(trash->area);
10680 if (fkw != NULL) {
10681 reg_flt = fkw->private;
10682 if (reg_flt->flt_ref[hlua_state_id] != -1 || reg_flt->fun_ref[hlua_state_id] != -1) {
10683 ha_warning("Trying to register filter 'lua.%s' more than once. "
10684 "This will become a hard error in version 2.5.\n", name);
10685 }
10686 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10687 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10688 return 0;
10689 }
10690
10691 fkl = calloc(1, sizeof(*fkl) + sizeof(struct flt_kw) * 2);
10692 if (!fkl)
10693 goto alloc_error;
10694 fkl->scope = "HLUA";
10695
10696 reg_flt = new_hlua_reg_filter(name);
10697 if (!reg_flt)
10698 goto alloc_error;
10699
10700 reg_flt->flt_ref[hlua_state_id] = flt_ref;
10701 reg_flt->fun_ref[hlua_state_id] = fun_ref;
10702
10703 /* The filter keyword */
10704 len = strlen("lua.") + strlen(name) + 1;
10705 fkl->kw[0].kw = calloc(1, len);
10706 if (!fkl->kw[0].kw)
10707 goto alloc_error;
10708
10709 snprintf((char *)fkl->kw[0].kw, len, "lua.%s", name);
10710
10711 fkl->kw[0].parse = hlua_filter_parse_fct;
10712 fkl->kw[0].private = reg_flt;
10713 memset(&fkl->kw[1], 0, sizeof(*fkl->kw));
10714
10715 /* Register this new filter */
10716 flt_register_keywords(fkl);
10717
10718 return 0;
10719
10720 alloc_error:
10721 release_hlua_reg_filter(reg_flt);
10722 ha_free(&fkl);
10723 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
10724 return 0; /* Never reached */
10725}
10726
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010727static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010728 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010729 char **err, unsigned int *timeout)
10730{
10731 const char *error;
10732
10733 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +020010734 if (error == PARSE_TIME_OVER) {
10735 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
10736 args[1], args[0]);
10737 return -1;
10738 }
10739 else if (error == PARSE_TIME_UNDER) {
10740 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
10741 args[1], args[0]);
10742 return -1;
10743 }
10744 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010745 memprintf(err, "%s: invalid timeout", args[0]);
10746 return -1;
10747 }
10748 return 0;
10749}
10750
10751static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010752 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010753 char **err)
10754{
10755 return hlua_read_timeout(args, section_type, curpx, defpx,
10756 file, line, err, &hlua_timeout_session);
10757}
10758
10759static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010760 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010761 char **err)
10762{
10763 return hlua_read_timeout(args, section_type, curpx, defpx,
10764 file, line, err, &hlua_timeout_task);
10765}
10766
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010767static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010768 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020010769 char **err)
10770{
10771 return hlua_read_timeout(args, section_type, curpx, defpx,
10772 file, line, err, &hlua_timeout_applet);
10773}
10774
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010775static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010776 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010010777 char **err)
10778{
10779 char *error;
10780
10781 hlua_nb_instruction = strtoll(args[1], &error, 10);
10782 if (*error != '\0') {
10783 memprintf(err, "%s: invalid number", args[0]);
10784 return -1;
10785 }
10786 return 0;
10787}
10788
Willy Tarreau32f61e22015-03-18 17:54:59 +010010789static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010790 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +010010791 char **err)
10792{
10793 char *error;
10794
10795 if (*(args[1]) == 0) {
10796 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
10797 return -1;
10798 }
10799 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
10800 if (*error != '\0') {
10801 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
10802 return -1;
10803 }
10804 return 0;
10805}
10806
10807
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010808/* This function is called by the main configuration key "lua-load". It loads and
10809 * execute an lua file during the parsing of the HAProxy configuration file. It is
10810 * the main lua entry point.
10811 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080010812 * This function runs with the HAProxy keywords API. It returns -1 if an error
10813 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010814 *
10815 * In some error case, LUA set an error message in top of the stack. This function
10816 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020010817 *
10818 * This function can fail with an abort() due to an Lua critical error.
10819 * We are in the configuration parsing process of HAProxy, this abort() is
10820 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010821 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010822static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010823{
10824 int error;
10825
10826 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010827 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010828 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010829 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
10830 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010831 return -1;
10832 }
10833
10834 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010835 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010836 switch (error) {
10837 case LUA_OK:
10838 break;
10839 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010840 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
10841 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010842 return -1;
10843 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +010010844 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010845 return -1;
10846 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010847 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
10848 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010849 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010850#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010851 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010852 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
10853 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010854 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +020010855#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010856 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010857 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
10858 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010859 return -1;
10860 }
10861
10862 return 0;
10863}
10864
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010865static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010866 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010867 char **err)
10868{
10869 if (*(args[1]) == 0) {
10870 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
10871 return -1;
10872 }
10873
Thierry Fournier59f11be2020-11-29 00:37:41 +010010874 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +010010875 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010876 ha_set_tid(0);
Thierry Fournierafc63e22020-11-28 17:06:51 +010010877 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +010010878}
10879
Thierry Fournier59f11be2020-11-29 00:37:41 +010010880static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010881 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +010010882 char **err)
10883{
10884 int len;
10885
10886 if (*(args[1]) == 0) {
10887 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
10888 return -1;
10889 }
10890
10891 if (per_thread_load == NULL) {
10892 /* allocate the first entry large enough to store the final NULL */
10893 per_thread_load = calloc(1, sizeof(*per_thread_load));
10894 if (per_thread_load == NULL) {
10895 memprintf(err, "out of memory error");
10896 return -1;
10897 }
10898 }
10899
10900 /* count used entries */
10901 for (len = 0; per_thread_load[len] != NULL; len++)
10902 ;
10903
10904 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
10905 if (per_thread_load == NULL) {
10906 memprintf(err, "out of memory error");
10907 return -1;
10908 }
10909
10910 per_thread_load[len] = strdup(args[1]);
10911 per_thread_load[len + 1] = NULL;
10912
10913 if (per_thread_load[len] == NULL) {
10914 memprintf(err, "out of memory error");
10915 return -1;
10916 }
10917
10918 /* loading for thread 1 only */
10919 hlua_state_id = 1;
10920 ha_set_tid(0);
10921 return hlua_load_state(args[1], hlua_states[1], err);
10922}
10923
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010924/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
10925 * in the given <ctx>.
10926 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010927static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010928{
Thierry Fournier3fb9e512020-11-28 10:13:12 +010010929 lua_getglobal(L, "package"); /* push package variable */
10930 lua_pushstring(L, path); /* push given path */
10931 lua_pushstring(L, ";"); /* push semicolon */
10932 lua_getfield(L, -3, type); /* push old path */
10933 lua_concat(L, 3); /* concatenate to new path */
10934 lua_setfield(L, -2, type); /* store new path */
10935 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +010010936
10937 return 0;
10938}
10939
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010940static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +010010941 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010942 char **err)
10943{
10944 char *path;
10945 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010946 struct prepend_path *p = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010947
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010948 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010949 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010950 }
10951
10952 if (!(*args[1])) {
10953 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010954 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010955 }
10956 path = args[1];
10957
10958 if (*args[2]) {
10959 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
10960 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010961 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010962 }
10963 type = args[2];
10964 }
10965
Thierry Fournier59f11be2020-11-29 00:37:41 +010010966 p = calloc(1, sizeof(*p));
10967 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010968 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010969 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010970 }
10971 p->path = strdup(path);
10972 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010973 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010974 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010975 }
10976 p->type = strdup(type);
10977 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +010010978 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010979 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +010010980 }
Willy Tarreau2b718102021-04-21 07:32:39 +020010981 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +010010982
10983 hlua_prepend_path(hlua_states[0], type, path);
10984 hlua_prepend_path(hlua_states[1], type, path);
10985 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +010010986
10987err2:
10988 free(p->type);
10989 free(p->path);
10990err:
10991 free(p);
10992 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010993}
10994
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010010995/* configuration keywords declaration */
10996static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +010010997 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010010998 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +010010999 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +010011000 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
11001 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +020011002 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010011003 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +010011004 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +010011005 { 0, NULL, NULL },
11006}};
11007
Willy Tarreau0108d902018-11-25 19:14:37 +010011008INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
11009
Christopher Fauletafd8f102018-11-08 11:34:21 +010011010
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011011/* This function can fail with an abort() due to an Lua critical error.
11012 * We are in the initialisation process of HAProxy, this abort() is
11013 * tolerated.
11014 */
Thierry Fournierb8cef172020-11-28 15:37:17 +010011015int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011016{
11017 struct hlua_init_function *init;
11018 const char *msg;
11019 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011020 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +010011021 const char *kind;
11022 const char *trace;
11023 int return_status = 1;
11024#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
11025 int nres;
11026#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011027
Willy Tarreaucdb53462020-12-02 12:12:00 +010011028 /* disable memory limit checks if limit is not set */
11029 if (!hlua_global_allocator.limit)
11030 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
11031
Ilya Shipitsin856aabc2020-04-16 23:51:34 +050011032 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +010011033 if (setjmp(safe_ljmp_env) != 0) {
11034 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011035 if (lua_type(L, -1) == LUA_TSTRING)
11036 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011037 else
11038 error = "critical error";
11039 fprintf(stderr, "Lua post-init: %s.\n", error);
11040 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011041 } else {
11042 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011043 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +020011044
Thierry Fournierb8cef172020-11-28 15:37:17 +010011045 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +010011046
Thierry Fournierc7492592020-11-28 23:57:24 +010011047 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011048 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +010011049
11050#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +010011051 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +010011052#else
Thierry Fournierb8cef172020-11-28 15:37:17 +010011053 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +010011054#endif
11055 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011056 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +010011057
11058 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +010011059 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +010011060 break;
Thierry Fournier670db242020-11-28 10:49:59 +010011061
11062 case LUA_ERRERR:
11063 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011064 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011065 case LUA_ERRRUN:
11066 if (!kind)
11067 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011068 msg = lua_tostring(L, -1);
11069 lua_settop(L, 0); /* Empty the stack. */
11070 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011071 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011072 if (msg)
11073 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
11074 else
11075 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
11076 return_status = 0;
11077 break;
11078
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011079 default:
Thierry Fournier670db242020-11-28 10:49:59 +010011080 /* Unknown error */
11081 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011082 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011083 case LUA_YIELD:
11084 /* yield is not configured at this step, this state doesn't happen */
11085 if (!kind)
11086 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -070011087 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +010011088 case LUA_ERRMEM:
11089 if (!kind)
11090 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +010011091 lua_settop(L, 0);
11092 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +010011093 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +010011094 ha_alert("Lua init: %s: %s\n", kind, trace);
11095 return_status = 0;
11096 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011097 }
Thierry Fournier670db242020-11-28 10:49:59 +010011098 if (!return_status)
11099 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011100 }
Thierry Fournier3c539322020-11-28 16:05:05 +010011101
11102 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +010011103 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011104}
11105
Thierry Fournierb8cef172020-11-28 15:37:17 +010011106int hlua_post_init()
11107{
Thierry Fournier59f11be2020-11-29 00:37:41 +010011108 int ret;
11109 int i;
11110 int errors;
11111 char *err = NULL;
11112 struct hlua_function *fcn;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011113 struct hlua_reg_filter *reg_flt;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011114
Willy Tarreaub1310492021-08-30 09:35:18 +020011115#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +010011116 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011117 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +010011118 int saved_used_backed = global.ssl_used_backend;
11119 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011120 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +010011121 global.ssl_used_backend = saved_used_backed;
11122 }
11123#endif
11124
Thierry Fournierc7492592020-11-28 23:57:24 +010011125 /* Perform post init of common thread */
11126 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011127 ha_set_tid(0);
11128 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11129 if (ret == 0)
11130 return 0;
11131
11132 /* init remaining lua states and load files */
11133 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11134
11135 /* set thread context */
11136 ha_set_tid(hlua_state_id - 1);
11137
11138 /* Init lua state */
11139 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
11140
11141 /* Load lua files */
11142 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
11143 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
11144 if (ret != 0) {
11145 ha_alert("Lua init: %s\n", err);
11146 return 0;
11147 }
11148 }
11149 }
11150
11151 /* Reset thread context */
11152 ha_set_tid(0);
11153
11154 /* Execute post init for all states */
11155 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
11156
11157 /* set thread context */
11158 ha_set_tid(hlua_state_id - 1);
11159
11160 /* run post init */
11161 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
11162 if (ret == 0)
11163 return 0;
11164 }
11165
11166 /* Reset thread context */
11167 ha_set_tid(0);
11168
11169 /* control functions registering. Each function must have:
11170 * - only the function_ref[0] set positive and all other to -1
11171 * - only the function_ref[0] set to -1 and all other positive
11172 * This ensure a same reference is not used both in shared
11173 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011174 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +010011175 * complicated to found for the end user.
11176 */
11177 errors = 0;
11178 list_for_each_entry(fcn, &referenced_functions, l) {
11179 ret = 0;
11180 for (i = 1; i < global.nbthread + 1; i++) {
11181 if (fcn->function_ref[i] == -1)
11182 ret--;
11183 else
11184 ret++;
11185 }
11186 if (abs(ret) != global.nbthread) {
11187 ha_alert("Lua function '%s' is not referenced in all thread. "
11188 "Expect function in all thread or in none thread.\n", fcn->name);
11189 errors++;
11190 continue;
11191 }
11192
11193 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011194 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
11195 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +010011196 "exclusive.\n", fcn->name);
11197 errors++;
11198 }
11199 }
11200
Christopher Faulet69c581a2021-05-31 08:54:04 +020011201 /* Do the same with registered filters */
11202 list_for_each_entry(reg_flt, &referenced_filters, l) {
11203 ret = 0;
11204 for (i = 1; i < global.nbthread + 1; i++) {
11205 if (reg_flt->flt_ref[i] == -1)
11206 ret--;
11207 else
11208 ret++;
11209 }
11210 if (abs(ret) != global.nbthread) {
11211 ha_alert("Lua filter '%s' is not referenced in all thread. "
11212 "Expect function in all thread or in none thread.\n", reg_flt->name);
11213 errors++;
11214 continue;
11215 }
11216
11217 if ((reg_flt->flt_ref[0] == -1) == (ret < 0)) {
11218 ha_alert("Lua filter '%s' is referenced both ins shared Lua context (through lua-load) "
11219 "and per-thread Lua context (through lua-load-per-thread). these two context "
11220 "exclusive.\n", fcn->name);
11221 errors++;
11222 }
11223 }
11224
11225
Thierry Fournier59f11be2020-11-29 00:37:41 +010011226 if (errors > 0)
11227 return 0;
11228
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +050011229 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +010011230 * -1 in order to have probably a segfault if someone use it
11231 */
11232 hlua_state_id = -1;
11233
11234 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +010011235}
11236
Willy Tarreau32f61e22015-03-18 17:54:59 +010011237/* The memory allocator used by the Lua stack. <ud> is a pointer to the
11238 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
11239 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011240 * allocation. <nsize> is the requested new size. A new allocation is
11241 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +010011242 * zero. This one verifies that the limits are respected but is optimized
11243 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreau32f61e22015-03-18 17:54:59 +010011244 */
11245static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
11246{
11247 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +010011248 size_t limit, old, new;
11249
Tim Duesterhus22586522021-01-08 10:35:33 +010011250 if (unlikely(!ptr && !nsize))
11251 return NULL;
11252
Willy Tarreaucdb53462020-12-02 12:12:00 +010011253 /* a limit of ~0 means unlimited and boot complete, so there's no need
11254 * for accounting anymore.
11255 */
Christopher Fauletcc2c4f82021-03-24 14:52:24 +010011256 if (likely(~zone->limit == 0))
11257 return realloc(ptr, nsize);
Willy Tarreau32f61e22015-03-18 17:54:59 +010011258
Willy Tarreaud36c7fa2020-12-02 12:26:29 +010011259 if (!ptr)
11260 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +010011261
Willy Tarreaucdb53462020-12-02 12:12:00 +010011262 /* enforce strict limits across all threads */
11263 limit = zone->limit;
11264 old = _HA_ATOMIC_LOAD(&zone->allocated);
11265 do {
11266 new = old + nsize - osize;
11267 if (unlikely(nsize && limit && new > limit))
11268 return NULL;
11269 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +010011270
11271 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +010011272
11273 if (unlikely(!ptr && nsize)) // failed
11274 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
11275
11276 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +010011277 return ptr;
11278}
11279
Thierry Fournierecb83c22020-11-28 15:49:44 +010011280/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011281 * We are in the initialisation process of HAProxy, this abort() is
11282 * tolerated.
11283 */
Thierry Fournierecb83c22020-11-28 15:49:44 +010011284lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011285{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011286 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011287 int idx;
11288 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011289 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011290 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +010011291 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011292 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011293 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +010011294 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011295
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011296 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011297 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011298
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011299 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011300 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +010011301 *context = NULL;
11302
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011303 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +020011304 * the Lua function can fail with an abort. We are in the initialisation
11305 * process of HAProxy, this abort() is tolerated.
11306 */
11307
Thierry Fournier3c539322020-11-28 16:05:05 +010011308 /* Call post initialisation function in safe environment. */
11309 if (setjmp(safe_ljmp_env) != 0) {
11310 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011311 if (lua_type(L, -1) == LUA_TSTRING)
11312 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011313 else
11314 error_msg = "critical error";
11315 fprintf(stderr, "Lua init: %s.\n", error_msg);
11316 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +010011317 } else {
11318 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +010011319 }
11320
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011321 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011322 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011323#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
11324#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
11325#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011326 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011327#endif
11328#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011329 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +010011330#endif
11331#undef HLUA_PREPEND_PATH_TOSTRING
11332#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011333
Thierry Fournier59f11be2020-11-29 00:37:41 +010011334 /* Apply configured prepend path */
11335 list_for_each_entry(pp, &prepend_path_list, l)
11336 hlua_prepend_path(L, pp->type, pp->path);
11337
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011338 /*
11339 *
11340 * Create "core" object.
11341 *
11342 */
11343
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +010011344 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011345 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011346
Thierry Fournierecb83c22020-11-28 15:49:44 +010011347 /* set the thread id */
11348 hlua_class_const_int(L, "thread", thread_num);
11349
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011350 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +010011351 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011352 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010011353
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011354 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011355 hlua_class_function(L, "register_init", hlua_register_init);
11356 hlua_class_function(L, "register_task", hlua_register_task);
11357 hlua_class_function(L, "register_fetches", hlua_register_fetches);
11358 hlua_class_function(L, "register_converters", hlua_register_converters);
11359 hlua_class_function(L, "register_action", hlua_register_action);
11360 hlua_class_function(L, "register_service", hlua_register_service);
11361 hlua_class_function(L, "register_cli", hlua_register_cli);
Christopher Faulet69c581a2021-05-31 08:54:04 +020011362 hlua_class_function(L, "register_filter", hlua_register_filter);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011363 hlua_class_function(L, "yield", hlua_yield);
11364 hlua_class_function(L, "set_nice", hlua_set_nice);
11365 hlua_class_function(L, "sleep", hlua_sleep);
11366 hlua_class_function(L, "msleep", hlua_msleep);
11367 hlua_class_function(L, "add_acl", hlua_add_acl);
11368 hlua_class_function(L, "del_acl", hlua_del_acl);
11369 hlua_class_function(L, "set_map", hlua_set_map);
11370 hlua_class_function(L, "del_map", hlua_del_map);
11371 hlua_class_function(L, "tcp", hlua_socket_new);
William Lallemand3956c4e2021-09-21 16:25:15 +020011372 hlua_class_function(L, "httpclient", hlua_httpclient_new);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011373 hlua_class_function(L, "log", hlua_log);
11374 hlua_class_function(L, "Debug", hlua_log_debug);
11375 hlua_class_function(L, "Info", hlua_log_info);
11376 hlua_class_function(L, "Warning", hlua_log_warning);
11377 hlua_class_function(L, "Alert", hlua_log_alert);
11378 hlua_class_function(L, "done", hlua_done);
11379 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010011380
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011381 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011382
11383 /*
11384 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011385 * Create "act" object.
11386 *
11387 */
11388
11389 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011390 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011391
11392 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011393 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
11394 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
11395 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
11396 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
11397 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
11398 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
11399 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
11400 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011401
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011402 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +010011403
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011404 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +010011405
11406 /*
11407 *
Christopher Faulet69c581a2021-05-31 08:54:04 +020011408 * Create "Filter" object.
11409 *
11410 */
11411
11412 /* This table entry is the object "filter" base. */
11413 lua_newtable(L);
11414
11415 /* push flags and constants */
11416 hlua_class_const_int(L, "CONTINUE", 1);
11417 hlua_class_const_int(L, "WAIT", 0);
11418 hlua_class_const_int(L, "ERROR", -1);
11419
11420 hlua_class_const_int(L, "FLT_CFG_FL_HTX", FLT_CFG_FL_HTX);
11421
Christopher Fauletc404f112020-02-26 15:03:09 +010011422 hlua_class_function(L, "wake_time", hlua_set_wake_time);
11423 hlua_class_function(L, "register_data_filter", hlua_register_data_filter);
11424 hlua_class_function(L, "unregister_data_filter", hlua_unregister_data_filter);
11425
Christopher Faulet69c581a2021-05-31 08:54:04 +020011426 lua_setglobal(L, "filter");
11427
11428 /*
11429 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011430 * Register class Map
11431 *
11432 */
11433
11434 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011435 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011436
11437 /* register pattern types. */
11438 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011439 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011440 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011441 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011442 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +010011443 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011444
11445 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011446 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011447
11448 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011449 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011450
Ilya Shipitsind4259502020-04-08 01:07:56 +050011451 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011452 lua_pushstring(L, "__index");
11453 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011454
11455 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011456 hlua_class_function(L, "lookup", hlua_map_lookup);
11457 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011458
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011459 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011460
Thierry Fournier45e78d72016-02-19 18:34:46 +010011461 /* Register previous table in the registry with reference and named entry.
11462 * The function hlua_register_metatable() pops the stack, so we
11463 * previously create a copy of the table.
11464 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011465 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
11466 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011467
11468 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011469 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011470
11471 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011472 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +020011473
11474 /*
11475 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011476 * Register class Channel
11477 *
11478 */
11479
11480 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011481 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011482
Ilya Shipitsind4259502020-04-08 01:07:56 +050011483 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011484 lua_pushstring(L, "__index");
11485 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011486
11487 /* Register . */
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011488 hlua_class_function(L, "data", hlua_channel_get_data);
11489 hlua_class_function(L, "line", hlua_channel_get_line);
11490 hlua_class_function(L, "set", hlua_channel_set_data);
11491 hlua_class_function(L, "remove", hlua_channel_del_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011492 hlua_class_function(L, "append", hlua_channel_append);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011493 hlua_class_function(L, "prepend", hlua_channel_prepend);
11494 hlua_class_function(L, "insert", hlua_channel_insert_data);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011495 hlua_class_function(L, "send", hlua_channel_send);
11496 hlua_class_function(L, "forward", hlua_channel_forward);
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011497 hlua_class_function(L, "input", hlua_channel_get_in_len);
11498 hlua_class_function(L, "output", hlua_channel_get_out_len);
11499 hlua_class_function(L, "may_recv", hlua_channel_may_recv);
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011500 hlua_class_function(L, "is_full", hlua_channel_is_full);
11501 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011502
Christopher Faulet6a79fc12021-08-06 16:02:36 +020011503 /* Deprecated API */
11504 hlua_class_function(L, "get", hlua_channel_get);
11505 hlua_class_function(L, "dup", hlua_channel_dup);
11506 hlua_class_function(L, "getline", hlua_channel_getline);
11507 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
11508 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
11509
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011510 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011511
11512 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011513 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010011514
11515 /*
11516 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011517 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011518 *
11519 */
11520
11521 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011522 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011523
Ilya Shipitsind4259502020-04-08 01:07:56 +050011524 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011525 lua_pushstring(L, "__index");
11526 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011527
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011528 /* Browse existing fetches and create the associated
11529 * object method.
11530 */
11531 sf = NULL;
11532 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011533 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11534 * by an underscore.
11535 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011536 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011537 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011538 if (*p == '.' || *p == '-' || *p == '+')
11539 *p = '_';
11540
11541 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011542 lua_pushstring(L, trash.area);
11543 lua_pushlightuserdata(L, sf);
11544 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
11545 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010011546 }
11547
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011548 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011549
11550 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011551 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011552
11553 /*
11554 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011555 * Register class Converters
11556 *
11557 */
11558
11559 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011560 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011561
11562 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011563 lua_pushstring(L, "__index");
11564 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011565
11566 /* Browse existing converters and create the associated
11567 * object method.
11568 */
11569 sc = NULL;
11570 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011571 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
11572 * by an underscore.
11573 */
Willy Tarreau5ef96562021-08-26 16:48:53 +020011574 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +020011575 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011576 if (*p == '.' || *p == '-' || *p == '+')
11577 *p = '_';
11578
11579 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011580 lua_pushstring(L, trash.area);
11581 lua_pushlightuserdata(L, sc);
11582 lua_pushcclosure(L, hlua_run_sample_conv, 1);
11583 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011584 }
11585
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011586 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011587
11588 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011589 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +010011590
11591 /*
11592 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011593 * Register class HTTP
11594 *
11595 */
11596
11597 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011598 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011599
Ilya Shipitsind4259502020-04-08 01:07:56 +050011600 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011601 lua_pushstring(L, "__index");
11602 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011603
11604 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011605 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
11606 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
11607 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
11608 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
11609 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
11610 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
11611 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
11612 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
11613 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
11614 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011615
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011616 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
11617 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
11618 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
11619 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
11620 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
11621 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
11622 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011623
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011624 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011625
11626 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011627 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011628
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011629 /*
11630 *
11631 * Register class HTTPMessage
11632 *
11633 */
11634
11635 /* Create and fill the metatable. */
11636 lua_newtable(L);
11637
Ilya Shipitsinff0f2782021-08-22 22:18:07 +050011638 /* Create and fill the __index entry. */
Christopher Fauletdf97ac42020-02-26 16:57:19 +010011639 lua_pushstring(L, "__index");
11640 lua_newtable(L);
11641
11642 /* Register Lua functions. */
11643 hlua_class_function(L, "is_resp", hlua_http_msg_is_resp);
11644 hlua_class_function(L, "get_stline", hlua_http_msg_get_stline);
11645 hlua_class_function(L, "get_headers", hlua_http_msg_get_headers);
11646 hlua_class_function(L, "del_header", hlua_http_msg_del_hdr);
11647 hlua_class_function(L, "rep_header", hlua_http_msg_rep_hdr);
11648 hlua_class_function(L, "rep_value", hlua_http_msg_rep_val);
11649 hlua_class_function(L, "add_header", hlua_http_msg_add_hdr);
11650 hlua_class_function(L, "set_header", hlua_http_msg_set_hdr);
11651 hlua_class_function(L, "set_method", hlua_http_msg_set_meth);
11652 hlua_class_function(L, "set_path", hlua_http_msg_set_path);
11653 hlua_class_function(L, "set_query", hlua_http_msg_set_query);
11654 hlua_class_function(L, "set_uri", hlua_http_msg_set_uri);
11655 hlua_class_function(L, "set_status", hlua_http_msg_set_status);
11656 hlua_class_function(L, "is_full", hlua_http_msg_is_full);
11657 hlua_class_function(L, "may_recv", hlua_http_msg_may_recv);
11658 hlua_class_function(L, "eom", hlua_http_msg_is_eom);
11659 hlua_class_function(L, "input", hlua_http_msg_get_in_len);
11660 hlua_class_function(L, "output", hlua_http_msg_get_out_len);
11661
11662 hlua_class_function(L, "body", hlua_http_msg_get_body);
11663 hlua_class_function(L, "set", hlua_http_msg_set_data);
11664 hlua_class_function(L, "remove", hlua_http_msg_del_data);
11665 hlua_class_function(L, "append", hlua_http_msg_append);
11666 hlua_class_function(L, "prepend", hlua_http_msg_prepend);
11667 hlua_class_function(L, "insert", hlua_http_msg_insert_data);
11668 hlua_class_function(L, "set_eom", hlua_http_msg_set_eom);
11669 hlua_class_function(L, "unset_eom", hlua_http_msg_unset_eom);
11670
11671 hlua_class_function(L, "send", hlua_http_msg_send);
11672 hlua_class_function(L, "forward", hlua_http_msg_forward);
11673
11674 lua_rawset(L, -3);
11675
11676 /* Register previous table in the registry with reference and named entry. */
11677 class_http_msg_ref = hlua_register_metatable(L, CLASS_HTTP_MSG);
William Lallemand3956c4e2021-09-21 16:25:15 +020011678
11679 /*
11680 *
11681 * Register class HTTPClient
11682 *
11683 */
11684
11685 /* Create and fill the metatable. */
11686 lua_newtable(L);
11687 lua_pushstring(L, "__index");
11688 lua_newtable(L);
11689 hlua_class_function(L, "get", hlua_httpclient_get);
11690 lua_settable(L, -3); /* Sets the __index entry. */
11691
11692
11693 class_httpclient_ref = hlua_register_metatable(L, CLASS_HTTPCLIENT);
Thierry FOURNIER08504f42015-03-16 14:17:08 +010011694 /*
11695 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011696 * Register class AppletTCP
11697 *
11698 */
11699
11700 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011701 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011702
Ilya Shipitsind4259502020-04-08 01:07:56 +050011703 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011704 lua_pushstring(L, "__index");
11705 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011706
11707 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011708 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
11709 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
11710 hlua_class_function(L, "send", hlua_applet_tcp_send);
11711 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
11712 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
11713 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
11714 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
11715 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011716
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011717 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011718
11719 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011720 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +020011721
11722 /*
11723 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011724 * Register class AppletHTTP
11725 *
11726 */
11727
11728 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011729 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011730
Ilya Shipitsind4259502020-04-08 01:07:56 +050011731 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011732 lua_pushstring(L, "__index");
11733 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011734
11735 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011736 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
11737 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
11738 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
11739 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
11740 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
11741 hlua_class_function(L, "getline", hlua_applet_http_getline);
11742 hlua_class_function(L, "receive", hlua_applet_http_recv);
11743 hlua_class_function(L, "send", hlua_applet_http_send);
11744 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
11745 hlua_class_function(L, "set_status", hlua_applet_http_status);
11746 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011747
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011748 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011749
11750 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011751 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +020011752
11753 /*
11754 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011755 * Register class TXN
11756 *
11757 */
11758
11759 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011760 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011761
Ilya Shipitsind4259502020-04-08 01:07:56 +050011762 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011763 lua_pushstring(L, "__index");
11764 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010011765
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011766 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011767 hlua_class_function(L, "set_priv", hlua_set_priv);
11768 hlua_class_function(L, "get_priv", hlua_get_priv);
11769 hlua_class_function(L, "set_var", hlua_set_var);
11770 hlua_class_function(L, "unset_var", hlua_unset_var);
11771 hlua_class_function(L, "get_var", hlua_get_var);
11772 hlua_class_function(L, "done", hlua_txn_done);
11773 hlua_class_function(L, "reply", hlua_txn_reply_new);
11774 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
11775 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
11776 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
11777 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
11778 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
11779 hlua_class_function(L, "deflog", hlua_txn_deflog);
11780 hlua_class_function(L, "log", hlua_txn_log);
11781 hlua_class_function(L, "Debug", hlua_txn_log_debug);
11782 hlua_class_function(L, "Info", hlua_txn_log_info);
11783 hlua_class_function(L, "Warning", hlua_txn_log_warning);
11784 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +010011785
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011786 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010011787
11788 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011789 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011790
11791 /*
11792 *
Christopher Faulet700d9e82020-01-31 12:21:52 +010011793 * Register class reply
11794 *
11795 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011796 lua_newtable(L);
11797 lua_pushstring(L, "__index");
11798 lua_newtable(L);
11799 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
11800 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
11801 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
11802 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
11803 lua_settable(L, -3); /* Sets the __index entry. */
11804 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +010011805
11806
11807 /*
11808 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011809 * Register class Socket
11810 *
11811 */
11812
11813 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011814 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011815
Ilya Shipitsind4259502020-04-08 01:07:56 +050011816 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011817 lua_pushstring(L, "__index");
11818 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011819
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011820#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011821 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +010011822#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011823 hlua_class_function(L, "connect", hlua_socket_connect);
11824 hlua_class_function(L, "send", hlua_socket_send);
11825 hlua_class_function(L, "receive", hlua_socket_receive);
11826 hlua_class_function(L, "close", hlua_socket_close);
11827 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
11828 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
11829 hlua_class_function(L, "setoption", hlua_socket_setoption);
11830 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011831
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011832 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011833
11834 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011835 lua_pushstring(L, "__gc");
11836 lua_pushcclosure(L, hlua_socket_gc, 0);
11837 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011838
11839 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +010011840 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011841
Thierry Fournieraafc7772020-12-04 11:47:47 +010011842 lua_atpanic(L, hlua_panic_safe);
11843
11844 return L;
11845}
11846
11847void hlua_init(void) {
11848 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011849 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +010011850#ifdef USE_OPENSSL
11851 struct srv_kw *kw;
11852 int tmp_error;
11853 char *error;
11854 char *args[] = { /* SSL client configuration. */
11855 "ssl",
11856 "verify",
11857 "none",
11858 NULL
11859 };
11860#endif
11861
11862 /* Init post init function list head */
11863 for (i = 0; i < MAX_THREADS + 1; i++)
11864 LIST_INIT(&hlua_init_functions[i]);
11865
11866 /* Init state for common/shared lua parts */
11867 hlua_state_id = 0;
11868 ha_set_tid(0);
11869 hlua_states[0] = hlua_init_state(0);
11870
11871 /* Init state 1 for thread 0. We have at least one thread. */
11872 hlua_state_id = 1;
11873 ha_set_tid(0);
11874 hlua_states[1] = hlua_init_state(1);
11875
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011876 /* Proxy and server configuration initialisation. */
William Lallemand6bb77b92021-07-28 15:48:16 +020011877 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_INT, &errmsg);
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011878 if (!socket_proxy) {
11879 fprintf(stderr, "Lua init: %s\n", errmsg);
11880 exit(1);
11881 }
11882 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011883
11884 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011885 socket_tcp = new_server(socket_proxy);
11886 if (!socket_tcp) {
11887 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
11888 exit(1);
11889 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011890
11891#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011892 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011893 socket_ssl = new_server(socket_proxy);
11894 if (!socket_ssl) {
11895 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
11896 exit(1);
11897 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011898
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011899 socket_ssl->use_ssl = 1;
11900 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011901
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011902 for (i = 0; args[i] != NULL; i++) {
11903 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011904 /*
11905 *
11906 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080011907 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011908 * features like client certificates and ssl_verify.
11909 *
11910 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +010011911 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011912 if (tmp_error != 0) {
11913 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
11914 abort(); /* This must be never arrives because the command line
11915 not editable by the user. */
11916 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +000011917 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011918 }
11919 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010011920#endif
Thierry Fournier75933d42016-01-21 09:30:18 +010011921
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010011922}
Willy Tarreaubb57d942016-12-21 19:04:56 +010011923
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011924static void hlua_deinit()
11925{
Willy Tarreau186f3762020-12-04 11:48:12 +010011926 int thr;
Christopher Faulet69c581a2021-05-31 08:54:04 +020011927 struct hlua_reg_filter *reg_flt, *reg_flt_bck;
11928
11929 list_for_each_entry_safe(reg_flt, reg_flt_bck, &referenced_filters, l)
11930 release_hlua_reg_filter(reg_flt);
Willy Tarreau186f3762020-12-04 11:48:12 +010011931
11932 for (thr = 0; thr < MAX_THREADS+1; thr++) {
11933 if (hlua_states[thr])
11934 lua_close(hlua_states[thr]);
11935 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011936
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020011937 srv_drop(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +010011938
Willy Tarreau0f143af2021-03-05 10:41:48 +010011939#ifdef USE_OPENSSL
Amaury Denoyellebc2ebfa2021-08-25 15:34:53 +020011940 srv_drop(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +010011941#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +010011942
11943 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +020011944}
11945
11946REGISTER_POST_DEINIT(hlua_deinit);
11947
Willy Tarreau80713382018-11-26 10:19:54 +010011948static void hlua_register_build_options(void)
11949{
Willy Tarreaubb57d942016-12-21 19:04:56 +010011950 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +010011951
Willy Tarreaubb57d942016-12-21 19:04:56 +010011952 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
11953 hap_register_build_opts(ptr, 1);
11954}
Willy Tarreau80713382018-11-26 10:19:54 +010011955
11956INITCALL0(STG_REGISTER, hlua_register_build_options);