blob: d729c879ca16acf93d9714781fe52621d9e77375 [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>
Willy Tarreau5413a872020-06-02 19:33:08 +020036#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020037#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020038#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020039#include <haproxy/http_ana.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020040#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020041#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020042#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020043#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020044#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020045#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020046#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020047#include <haproxy/payload.h>
Willy Tarreau3d6ee402021-05-08 20:28:07 +020048#include <haproxy/proxy.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020049#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020050#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010051#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020052#include <haproxy/session.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020053#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020054#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020055#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020056#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020057#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020058#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020059#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020060#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020061#include <haproxy/xref.h>
62
Thierry FOURNIER380d0932015-01-23 14:27:52 +010063
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010064/* Lua uses longjmp to perform yield or throwing errors. This
65 * macro is used only for identifying the function that can
66 * not return because a longjmp is executed.
67 * __LJMP marks a prototype of hlua file that can use longjmp.
68 * WILL_LJMP() marks an lua function that will use longjmp.
69 * MAY_LJMP() marks an lua function that may use longjmp.
70 */
71#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020072#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010073#define MAY_LJMP(func) func
74
Thierry FOURNIERbabae282015-09-17 11:36:37 +020075/* This couple of function executes securely some Lua calls outside of
76 * the lua runtime environment. Each Lua call can return a longjmp
77 * if it encounter a memory error.
78 *
79 * Lua documentation extract:
80 *
81 * If an error happens outside any protected environment, Lua calls
82 * a panic function (see lua_atpanic) and then calls abort, thus
83 * exiting the host application. Your panic function can avoid this
84 * exit by never returning (e.g., doing a long jump to your own
85 * recovery point outside Lua).
86 *
87 * The panic function runs as if it were a message handler (see
88 * §2.3); in particular, the error message is at the top of the
89 * stack. However, there is no guarantee about stack space. To push
90 * anything on the stack, the panic function must first check the
91 * available space (see §4.2).
92 *
93 * We must check all the Lua entry point. This includes:
94 * - The include/proto/hlua.h exported functions
95 * - the task wrapper function
96 * - The action wrapper function
97 * - The converters wrapper function
98 * - The sample-fetch wrapper functions
99 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500100 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800101 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200102 *
103 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
104 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
105 * because they must be exists in the program stack when the longjmp
106 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200107 *
108 * Note that the Lua processing is not really thread safe. It provides
109 * heavy system which consists to add our own lock function in the Lua
110 * code and recompile the library. This system will probably not accepted
111 * by maintainers of various distribs.
112 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500113 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200114 * quick looking on the Lua sources displays a lua_lock() a the start
115 * of function and a lua_unlock() at the end of the function. So I
116 * conclude that the Lua thread safe mode just perform a mutex around
117 * all execution. So I prefer to do this in the HAProxy code, it will be
118 * easier for distro maintainers.
119 *
120 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
121 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
122 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200123 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100124__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200125THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200126static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau69c66e32021-07-14 19:41:25 +0200127static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); return 0; }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200128
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100129/* This is the chained list of struct hlua_function referenced
130 * for haproxy action, sample-fetches, converters, cli and
131 * applet bindings. It is used for a post-initialisation control.
132 */
133static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
134
Thierry Fournierc7492592020-11-28 23:57:24 +0100135/* This variable is used only during initialization to identify the Lua state
136 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
137 * states dedicated to each thread (in this case hlua_state_id==tid+1).
138 */
139static int hlua_state_id;
140
Thierry Fournier59f11be2020-11-29 00:37:41 +0100141/* This is a NULL-terminated list of lua file which are referenced to load per thread */
142static char **per_thread_load = NULL;
143
144lua_State *hlua_init_state(int thread_id);
145
Willy Tarreau3eb2e472021-08-20 15:47:25 +0200146/* This function takes the Lua global lock. Keep this function's visibility
147 * global so that it can appear in stack dumps and performance profiles!
148 */
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +0100149static inline void lua_take_global_lock()
Willy Tarreau3eb2e472021-08-20 15:47:25 +0200150{
151 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
152}
153
154static inline void lua_drop_global_lock()
155{
156 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
157}
158
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +0100159/* lua lock helpers: only lock when required
160 *
161 * state_id == 0: we're operating on the main lua stack (shared between
162 * os threads), so we need to acquire the main lock
163 *
164 * If the thread already owns the lock (_hlua_locked != 0), skip the lock
165 * attempt. This could happen if we run under protected lua environment.
166 * Not doing this could result in deadlocks because of nested locking
167 * attempts from the same thread
168 */
169static THREAD_LOCAL int _hlua_locked = 0;
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +0100170static inline void hlua_lock(struct hlua *hlua)
171{
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +0100172 if (hlua->state_id != 0)
173 return;
174 if (!_hlua_locked)
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +0100175 lua_take_global_lock();
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +0100176 _hlua_locked += 1;
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +0100177}
178static inline void hlua_unlock(struct hlua *hlua)
179{
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +0100180 if (hlua->state_id != 0)
181 return;
182 BUG_ON(_hlua_locked <= 0);
183 _hlua_locked--;
184 /* drop the lock once the lock count reaches 0 */
185 if (!_hlua_locked)
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +0100186 lua_drop_global_lock();
187}
188
Aurelien DARRAGONa3741612024-03-01 15:55:17 +0100189/* below is an helper function to retrieve string on on Lua stack at <index>
190 * in a safe way (function may not LJMP). It can be useful to retrieve errors
191 * at the top of the stack from an unprotected environment.
192 *
193 * The returned string will is only valid as long as the value at <index> is
194 * not removed from the stack.
195 *
196 * It is assumed that the calling function is allowed to manipulate <L>
197 */
198__LJMP static int _hlua_tostring_safe(lua_State *L)
199{
200 const char **str = lua_touserdata(L, 1);
201 const char *cur_str = MAY_LJMP(lua_tostring(L, 2));
202
203 if (cur_str)
204 *str = cur_str;
205 return 0;
206}
207static const char *hlua_tostring_safe(lua_State *L, int index)
208{
209 const char *str = NULL;
210
211 if (!lua_checkstack(L, 4))
212 return NULL;
213
214 /* before any stack modification, save the targeted value on the top of
215 * the stack: this will allow us to use relative index to target it.
216 */
217 lua_pushvalue(L, index);
218
219 /* push our custom _hlua_tostring_safe() function on the stack, then push
220 * our own string pointer and targeted value (at <index>) as argument
221 */
222 lua_pushcfunction(L, _hlua_tostring_safe);
223 lua_pushlightuserdata(L, &str); // 1st func argument = string pointer
224 lua_pushvalue(L, -3); // 2nd func argument = targeted value
225
226 lua_remove(L, -4); // remove <index> copy as we're done using it
227
228 /* call our custom function with proper arguments using pcall() to catch
229 * exceptions (if any)
230 */
231 switch (lua_pcall(L, 2, 0, 0)) {
232 case LUA_OK:
233 break;
234 default:
235 /* error was caught */
236 return NULL;
237 }
238 return str;
239}
240
Aurelien DARRAGON159136c2024-06-03 23:18:24 +0200241/* below is an helper function similar to lua_pushvfstring() to push a
242 * formatted string on Lua stack but in a safe way (function may not LJMP).
243 * It can be useful to push allocated strings (ie: error messages) on the
244 * stack and ensure proper cleanup.
245 *
246 * Returns a pointer to the internal copy of the string on success and NULL
247 * on error.
248 *
249 * It is assumed that the calling function is allowed to manipulate <L>
250 */
251__LJMP static int _hlua_pushvfstring_safe(lua_State *L)
252{
253 const char **dst = lua_touserdata(L, 1);
254 const char *fmt = lua_touserdata(L, 2);
255 va_list *argp = lua_touserdata(L, 3);
256
257 *dst = lua_pushvfstring(L, fmt, *argp);
258 return 1;
259}
260static const char *hlua_pushvfstring_safe(lua_State *L, const char *fmt, va_list argp)
261{
262 const char *dst = NULL;
263 va_list cpy_argp; /* required if argp is implemented as array type */
264
265 if (!lua_checkstack(L, 4))
266 return NULL;
267
268 va_copy(cpy_argp, argp);
269
270 /* push our custom _hlua_pushvfstring_safe() function on the stack, then
271 * push our destination string pointer, fmt and arg list
272 */
273 lua_pushcfunction(L, _hlua_pushvfstring_safe);
274 lua_pushlightuserdata(L, &dst); // 1st func argument = dst string pointer
275 lua_pushlightuserdata(L, (void *)fmt); // 2nd func argument = fmt
276 lua_pushlightuserdata(L, &cpy_argp); // 3rd func argument = arg list
277
278 /* call our custom function with proper arguments using pcall() to catch
279 * exceptions (if any)
280 */
281 switch (lua_pcall(L, 3, 1, 0)) {
282 case LUA_OK:
283 break;
284 default:
285 /* error was caught */
286 dst = NULL;
287 }
288 va_end(cpy_argp);
289
290 return dst;
291}
292
293static const char *hlua_pushfstring_safe(lua_State *L, const char *fmt, ...)
294{
295 va_list argp;
296 const char *dst;
297
298 va_start(argp, fmt);
299 dst = hlua_pushvfstring_safe(L, fmt, argp);
300 va_end(argp);
301
302 return dst;
303}
304
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100305#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200306 ({ \
307 int ret; \
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +0100308 hlua_lock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200309 if (setjmp(safe_ljmp_env) != 0) { \
310 lua_atpanic(__L, hlua_panic_safe); \
311 ret = 0; \
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +0100312 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200313 } else { \
314 lua_atpanic(__L, hlua_panic_ljmp); \
315 ret = 1; \
316 } \
317 ret; \
318 })
319
320/* If we are the last function catching Lua errors, we
321 * must reset the panic function.
322 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100323#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200324 do { \
325 lua_atpanic(__L, hlua_panic_safe); \
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +0100326 hlua_unlock(__HLUA); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200327 } while(0)
328
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100329#define SET_SAFE_LJMP(__HLUA) \
330 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
331
332#define RESET_SAFE_LJMP(__HLUA) \
333 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
334
335#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100336 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100337
338#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100339 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100340
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200341/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200342#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100343/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200344#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200345/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100346#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100347#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200348
Thierry Fournierafc63e22020-11-28 17:06:51 +0100349/* The main Lua execution context. The 0 index is the
350 * common state shared by all threads.
351 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100352static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100353
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100354/* This is the memory pool containing struct lua for applets
355 * (including cli).
356 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100357DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100358
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100359/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100360static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100361static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100362#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100363static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100364#endif
365
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100366/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100367struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100368
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100369/* The following variables contains the reference of the different
370 * Lua classes. These references are useful for identify metadata
371 * associated with an object.
372 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100373static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100374static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100375static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100376static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100377static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100378static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200379static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200380static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200381static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100382static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100383
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100384/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200385 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100386 * short timeout. Lua linked with tasks doesn't have a timeout
387 * because a task may remain alive during all the haproxy execution.
388 */
389static unsigned int hlua_timeout_session = 4000; /* session timeout. */
390static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200391static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100392
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100393/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
394 * it is used for preventing infinite loops.
395 *
396 * I test the scheer with an infinite loop containing one incrementation
397 * and one test. I run this loop between 10 seconds, I raise a ceil of
398 * 710M loops from one interrupt each 9000 instructions, so I fix the value
399 * to one interrupt each 10 000 instructions.
400 *
401 * configured | Number of
402 * instructions | loops executed
403 * between two | in milions
404 * forced yields |
405 * ---------------+---------------
406 * 10 | 160
407 * 500 | 670
408 * 1000 | 680
409 * 5000 | 700
410 * 7000 | 700
411 * 8000 | 700
412 * 9000 | 710 <- ceil
413 * 10000 | 710
414 * 100000 | 710
415 * 1000000 | 710
416 *
417 */
418static unsigned int hlua_nb_instruction = 10000;
419
Willy Tarreaucdb53462020-12-02 12:12:00 +0100420/* Descriptor for the memory allocation state. The limit is pre-initialised to
421 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
422 * is replaced with ~0 during post_init after everything was loaded. This way
423 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
424 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100425 */
426struct hlua_mem_allocator {
427 size_t allocated;
428 size_t limit;
429};
430
Willy Tarreaucdb53462020-12-02 12:12:00 +0100431static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100432
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100433/* These functions converts types between HAProxy internal args or
434 * sample and LUA types. Another function permits to check if the
435 * LUA stack contains arguments according with an required ARG_T
436 * format.
437 */
438static int hlua_arg2lua(lua_State *L, const struct arg *arg);
439static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100440__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100441 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100442static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100443static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100444static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
445
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100446__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200447
Thierry Fournier59f11be2020-11-29 00:37:41 +0100448struct prepend_path {
449 struct list l;
450 char *type;
451 char *path;
452};
453
454static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
455
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200456#define SEND_ERR(__be, __fmt, __args...) \
457 do { \
458 send_log(__be, LOG_ERR, __fmt, ## __args); \
459 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100460 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200461 } while (0)
462
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100463static inline struct hlua_function *new_hlua_function()
464{
465 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100466 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100467
468 fcn = calloc(1, sizeof(*fcn));
469 if (!fcn)
470 return NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +0200471 LIST_APPEND(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100472 for (i = 0; i < MAX_THREADS + 1; i++)
473 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100474 return fcn;
475}
476
Christopher Fauletdda44442021-04-12 14:05:43 +0200477static inline void release_hlua_function(struct hlua_function *fcn)
478{
479 if (!fcn)
480 return;
481 if (fcn->name)
482 ha_free(&fcn->name);
Willy Tarreau2b718102021-04-21 07:32:39 +0200483 LIST_DELETE(&fcn->l);
Christopher Fauletdda44442021-04-12 14:05:43 +0200484 ha_free(&fcn);
485}
486
Thierry Fournierc7492592020-11-28 23:57:24 +0100487/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
488static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
489{
490 if (fcn->function_ref[0] == -1)
491 return tid + 1;
492 return 0;
493}
494
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100495/* Used to check an Lua function type in the stack. It creates and
496 * returns a reference of the function. This function throws an
Aurelien DARRAGON5ce11522023-03-02 17:50:49 +0100497 * error if the argument is not a "function".
498 * When no longer used, the ref must be released with hlua_unref()
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100499 */
500__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
501{
502 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100503 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100504 WILL_LJMP(luaL_argerror(L, argno, msg));
505 }
506 lua_pushvalue(L, argno);
507 return luaL_ref(L, LUA_REGISTRYINDEX);
508}
509
Christopher Fauletddc90322020-02-25 10:20:04 +0100510/* Used to check an Lua table type in the stack. It creates and
511 * returns a reference of the table. This function throws an
Aurelien DARRAGON5ce11522023-03-02 17:50:49 +0100512 * error if the argument is not a "table".
513 * When no longer used, the ref must be released with hlua_unref()
Christopher Fauletddc90322020-02-25 10:20:04 +0100514 */
515__LJMP unsigned int hlua_checktable(lua_State *L, int argno)
516{
517 if (!lua_istable(L, argno)) {
518 const char *msg = lua_pushfstring(L, "table expected, got %s", luaL_typename(L, argno));
519 WILL_LJMP(luaL_argerror(L, argno, msg));
520 }
521 lua_pushvalue(L, argno);
522 return luaL_ref(L, LUA_REGISTRYINDEX);
523}
524
Aurelien DARRAGON5ce11522023-03-02 17:50:49 +0100525/* Get a reference to the object that is at the top of the stack
526 * The referenced object will be popped from the stack
527 *
528 * The function returns the reference to the object which must
529 * be cleared using hlua_unref() when no longer used
530 */
531__LJMP int hlua_ref(lua_State *L)
532{
533 return MAY_LJMP(luaL_ref(L, LUA_REGISTRYINDEX));
534}
535
536/* Pushes a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
537 * on <L> stack
538 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
539 *
540 * When the reference is no longer used, it should be released by calling
541 * hlua_unref()
542 *
543 * <L> can be from any co-routine as long as it belongs to the same lua
544 * parent state that the one used to get the reference.
545 */
546void hlua_pushref(lua_State *L, int ref)
547{
548 lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
549}
550
551/* Releases a reference previously created using luaL_ref(L, LUA_REGISTRYINDEX)
552 * (ie: hlua_checkfunction(), hlua_checktable() or hlua_ref())
553 *
554 * This will allow the reference to be reused and the referred object
555 * to be garbage collected.
556 *
557 * <L> can be from any co-routine as long as it belongs to the same lua
558 * parent state that the one used to get the reference.
559 */
560void hlua_unref(lua_State *L, int ref)
561{
562 luaL_unref(L, LUA_REGISTRYINDEX, ref);
563}
564
Aurelien DARRAGON6e53e5d2024-06-04 10:41:32 +0200565__LJMP static int _hlua_traceback(lua_State *L)
566{
567 lua_Debug *ar = lua_touserdata(L, 1);
568
569 /* Fill fields:
570 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
571 * 'l': fills in the field currentline;
572 * 'n': fills in the field name and namewhat;
573 * 't': fills in the field istailcall;
574 */
575 return lua_getinfo(L, "Slnt", ar);
576}
577
578
579/* This function cannot fail (output will simply be truncated upon errors) */
580const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200581{
582 lua_Debug ar;
583 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200584 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200585
586 while (lua_getstack(L, level++, &ar)) {
Aurelien DARRAGON6e53e5d2024-06-04 10:41:32 +0200587 if (!lua_checkstack(L, 2))
588 goto end; // abort
589
590 lua_pushcfunction(L, _hlua_traceback);
591 lua_pushlightuserdata(L, &ar);
592
593 /* safe getinfo */
594 switch (lua_pcall(L, 1, 1, 0)) {
595 case LUA_OK:
596 break;
597 default:
598 goto end; // abort
599 }
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200600
Willy Tarreau61840192022-06-19 17:35:53 +0200601 /* skip these empty entries, usually they come from deep C functions */
602 if (ar.currentline < 0 && *ar.what == 'C' && !*ar.namewhat && !ar.name)
603 continue;
604
605 /* Add separator */
606 if (b_data(msg))
607 chunk_appendf(msg, "%s", sep);
608
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200609 /* Append code localisation */
610 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100611 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200612 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100613 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200614
615 /*
616 * Get function name
617 *
618 * if namewhat is no empty, name is defined.
619 * what contains "Lua" for Lua function, "C" for C function,
620 * or "main" for main code.
621 */
622 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100623 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200624
625 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100626 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200627
628 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100629 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200630
631 else /* nothing left... */
632 chunk_appendf(msg, "?");
633
634
635 /* Display tailed call */
636 if (ar.istailcall)
637 chunk_appendf(msg, " ...");
638 }
639
Aurelien DARRAGON6e53e5d2024-06-04 10:41:32 +0200640 end:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200641 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200642}
643
644
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100645/* This function check the number of arguments available in the
646 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500647 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100648 */
649__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
650{
651 if (lua_gettop(L) == nb)
652 return;
653 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
654}
655
Mark Lakes22154b42018-01-29 14:38:40 -0800656/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100657 * and the line number where the error is encountered.
Aurelien DARRAGON9a205942024-06-04 13:08:59 +0200658 *
659 * It returns 1 on success and 0 on failure (function won't LJMP)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100660 */
Aurelien DARRAGON9a205942024-06-04 13:08:59 +0200661__LJMP static int _hlua_pusherror(lua_State *L)
662{
663 const char *fmt = lua_touserdata(L, 1);
664 va_list *argp = lua_touserdata(L, 2);
665
666 luaL_where(L, 2);
667 lua_pushvfstring(L, fmt, *argp);
668 lua_concat(L, 2);
669
670 return 1;
671}
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100672static int hlua_pusherror(lua_State *L, const char *fmt, ...)
673{
674 va_list argp;
Aurelien DARRAGON9a205942024-06-04 13:08:59 +0200675 int ret = 1;
676
677 if (!lua_checkstack(L, 3))
678 return 0;
679
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100680 va_start(argp, fmt);
Aurelien DARRAGON9a205942024-06-04 13:08:59 +0200681
682 /* push our custom _hlua_pusherror() function on the stack, then
683 * push fmt and arg list
684 */
685 lua_pushcfunction(L, _hlua_pusherror);
686 lua_pushlightuserdata(L, (void *)fmt); // 1st func argument = fmt
687 lua_pushlightuserdata(L, &argp); // 2nd func argument = arg list
688
689 /* call our custom function with proper arguments using pcall() to catch
690 * exceptions (if any)
691 */
692 switch (lua_pcall(L, 2, 1, 0)) {
693 case LUA_OK:
694 break;
695 default:
696 ret = 0;
697 }
698
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100699 va_end(argp);
Aurelien DARRAGON9a205942024-06-04 13:08:59 +0200700
701 return ret;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100702}
703
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100704/* This functions is used with sample fetch and converters. It
705 * converts the HAProxy configuration argument in a lua stack
706 * values.
707 *
708 * It takes an array of "arg", and each entry of the array is
709 * converted and pushed in the LUA stack.
710 */
711static int hlua_arg2lua(lua_State *L, const struct arg *arg)
712{
713 switch (arg->type) {
714 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100715 case ARGT_TIME:
716 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100717 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100718 break;
719
720 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200721 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100722 break;
723
724 case ARGT_IPV4:
725 case ARGT_IPV6:
726 case ARGT_MSK4:
727 case ARGT_MSK6:
728 case ARGT_FE:
729 case ARGT_BE:
730 case ARGT_TAB:
731 case ARGT_SRV:
732 case ARGT_USR:
733 case ARGT_MAP:
734 default:
735 lua_pushnil(L);
736 break;
737 }
738 return 1;
739}
740
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500741/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100742 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500743 * with sample fetch wrappers. The input arguments are given to the
744 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100745 */
746static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
747{
748 switch (lua_type(L, ud)) {
749
750 case LUA_TNUMBER:
751 case LUA_TBOOLEAN:
752 arg->type = ARGT_SINT;
753 arg->data.sint = lua_tointeger(L, ud);
754 break;
755
756 case LUA_TSTRING:
757 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200758 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200759 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200760 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200761 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100762 break;
763
764 case LUA_TUSERDATA:
765 case LUA_TNIL:
766 case LUA_TTABLE:
767 case LUA_TFUNCTION:
768 case LUA_TTHREAD:
769 case LUA_TLIGHTUSERDATA:
770 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200771 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100772 break;
773 }
774 return 1;
775}
776
777/* the following functions are used to convert a struct sample
778 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500779 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100780 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100781static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100782{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200783 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100784 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100785 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200786 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100787 break;
788
789 case SMP_T_BIN:
790 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200791 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100792 break;
793
794 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200795 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100796 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
797 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
798 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
799 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
800 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
801 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
802 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
803 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
804 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200805 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100806 break;
807 default:
808 lua_pushnil(L);
809 break;
810 }
811 break;
812
813 case SMP_T_IPV4:
814 case SMP_T_IPV6:
815 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200816 if (sample_casts[smp->data.type][SMP_T_STR] &&
817 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200818 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100819 else
820 lua_pushnil(L);
821 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100822 default:
823 lua_pushnil(L);
824 break;
825 }
826 return 1;
827}
828
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100829/* the following functions are used to convert a struct sample
830 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500831 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100832 */
833static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
834{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200835 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100836
837 case SMP_T_BIN:
838 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200839 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100840 break;
841
842 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200843 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100844 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
845 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
846 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
847 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
848 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
849 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
850 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
851 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
852 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200853 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100854 break;
855 default:
856 lua_pushstring(L, "");
857 break;
858 }
859 break;
860
861 case SMP_T_SINT:
862 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100863 case SMP_T_IPV4:
864 case SMP_T_IPV6:
865 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200866 if (sample_casts[smp->data.type][SMP_T_STR] &&
867 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200868 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100869 else
870 lua_pushstring(L, "");
871 break;
872 default:
873 lua_pushstring(L, "");
874 break;
875 }
876 return 1;
877}
878
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100879/* the following functions are used to convert an Lua type in a
880 * struct sample. This is useful to provide data from a converter
881 * to the LUA code.
882 */
883static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
884{
885 switch (lua_type(L, ud)) {
886
887 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200888 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200889 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100890 break;
891
892
893 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200894 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200895 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100896 break;
897
898 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200899 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100900 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200901 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200902 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200903 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200904 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100905 break;
906
907 case LUA_TUSERDATA:
908 case LUA_TNIL:
909 case LUA_TTABLE:
910 case LUA_TFUNCTION:
911 case LUA_TTHREAD:
912 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200913 case LUA_TNONE:
914 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200915 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200916 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100917 break;
918 }
919 return 1;
920}
921
Ilya Shipitsind4259502020-04-08 01:07:56 +0500922/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800923 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100924 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100925 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500926 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100927 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100928 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100929__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100930 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100931{
932 int min_arg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200933 int i, idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100934 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200935 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200936 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200937 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200938 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100939
940 idx = 0;
941 min_arg = ARGM(mask);
942 mask >>= ARGM_BITS;
943
944 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200945 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100946
947 /* Check oversize. */
948 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200949 msg = "Malformed argument mask";
950 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100951 }
952
953 /* Check for mandatory arguments. */
954 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100955 if (idx < min_arg) {
956
957 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200958 if (idx > 0) {
959 msg = "Mandatory argument expected";
960 goto error;
961 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100962
963 /* If first argument have a certain type, some default values
964 * may be used. See the function smp_resolve_args().
965 */
966 switch (mask & ARGT_MASK) {
967
968 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200969 if (!(p->cap & PR_CAP_FE)) {
970 msg = "Mandatory argument expected";
971 goto error;
972 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100973 argp[idx].data.prx = p;
974 argp[idx].type = ARGT_FE;
975 argp[idx+1].type = ARGT_STOP;
976 break;
977
978 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200979 if (!(p->cap & PR_CAP_BE)) {
980 msg = "Mandatory argument expected";
981 goto error;
982 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100983 argp[idx].data.prx = p;
984 argp[idx].type = ARGT_BE;
985 argp[idx+1].type = ARGT_STOP;
986 break;
987
988 case ARGT_TAB:
Olivier Houcharda2658272022-09-13 00:35:53 +0200989 if (!p->table) {
990 msg = "Mandatory argument expected";
991 goto error;
992 }
993 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100994 argp[idx].type = ARGT_TAB;
995 argp[idx+1].type = ARGT_STOP;
996 break;
997
998 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200999 msg = "Mandatory argument expected";
1000 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +01001001 break;
1002 }
1003 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001004 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001005 }
1006
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001007 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001008 if ((mask & ARGT_MASK) == ARGT_STOP &&
1009 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001010 msg = "Last argument expected";
1011 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001012 }
1013
1014 if ((mask & ARGT_MASK) == ARGT_STOP &&
1015 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001016 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001017 }
1018
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001019 /* Convert some argument types. All string in argp[] are for not
1020 * duplicated yet.
1021 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001022 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001023 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001024 if (argp[idx].type != ARGT_SINT) {
1025 msg = "integer expected";
1026 goto error;
1027 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001028 argp[idx].type = ARGT_SINT;
1029 break;
1030
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001031 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001032 if (argp[idx].type != ARGT_SINT) {
1033 msg = "integer expected";
1034 goto error;
1035 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001036 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001037 break;
1038
1039 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001040 if (argp[idx].type != ARGT_SINT) {
1041 msg = "integer expected";
1042 goto error;
1043 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +02001044 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001045 break;
1046
1047 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001048 if (argp[idx].type != ARGT_STR) {
1049 msg = "string expected";
1050 goto error;
1051 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001052 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001053 if (!argp[idx].data.prx) {
1054 msg = "frontend doesn't exist";
1055 goto error;
1056 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001057 argp[idx].type = ARGT_FE;
1058 break;
1059
1060 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001061 if (argp[idx].type != ARGT_STR) {
1062 msg = "string expected";
1063 goto error;
1064 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001065 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001066 if (!argp[idx].data.prx) {
1067 msg = "backend doesn't exist";
1068 goto error;
1069 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001070 argp[idx].type = ARGT_BE;
1071 break;
1072
1073 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001074 if (argp[idx].type != ARGT_STR) {
1075 msg = "string expected";
1076 goto error;
1077 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001078 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001079 if (!argp[idx].data.t) {
1080 msg = "table doesn't exist";
1081 goto error;
1082 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001083 argp[idx].type = ARGT_TAB;
1084 break;
1085
1086 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001087 if (argp[idx].type != ARGT_STR) {
1088 msg = "string expected";
1089 goto error;
1090 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001091 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001092 if (sname) {
1093 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001094 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001095 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001096 if (!px) {
1097 msg = "backend doesn't exist";
1098 goto error;
1099 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001100 }
1101 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001102 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001103 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001104 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001105 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001106 if (!argp[idx].data.srv) {
1107 msg = "server doesn't exist";
1108 goto error;
1109 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001110 argp[idx].type = ARGT_SRV;
1111 break;
1112
1113 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001114 if (argp[idx].type != ARGT_STR) {
1115 msg = "string expected";
1116 goto error;
1117 }
1118 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1119 msg = "invalid IPv4 address";
1120 goto error;
1121 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001122 argp[idx].type = ARGT_IPV4;
1123 break;
1124
1125 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001126 if (argp[idx].type == ARGT_SINT)
1127 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1128 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001129 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1130 msg = "invalid IPv4 mask";
1131 goto error;
1132 }
1133 }
1134 else {
1135 msg = "integer or string expected";
1136 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001137 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001138 argp[idx].type = ARGT_MSK4;
1139 break;
1140
1141 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001142 if (argp[idx].type != ARGT_STR) {
1143 msg = "string expected";
1144 goto error;
1145 }
1146 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1147 msg = "invalid IPv6 address";
1148 goto error;
1149 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001150 argp[idx].type = ARGT_IPV6;
1151 break;
1152
1153 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001154 if (argp[idx].type == ARGT_SINT)
1155 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1156 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001157 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1158 msg = "invalid IPv6 mask";
1159 goto error;
1160 }
1161 }
1162 else {
1163 msg = "integer or string expected";
1164 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001165 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001166 argp[idx].type = ARGT_MSK6;
1167 break;
1168
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001169 case ARGT_REG:
1170 if (argp[idx].type != ARGT_STR) {
1171 msg = "string expected";
1172 goto error;
1173 }
1174 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1175 if (!reg) {
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001176 msg = hlua_pushfstring_safe(L, "error compiling regex '%s' : '%s'",
1177 argp[idx].data.str.area, err);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001178 free(err);
1179 goto error;
1180 }
1181 argp[idx].type = ARGT_REG;
1182 argp[idx].data.reg = reg;
1183 break;
1184
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001185 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001186 if (argp[idx].type != ARGT_STR) {
1187 msg = "string expected";
1188 goto error;
1189 }
1190 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001191 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001192 ul = p->uri_auth->userlist;
1193 else
1194 ul = auth_find_userlist(argp[idx].data.str.area);
1195
1196 if (!ul) {
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001197 msg = hlua_pushfstring_safe(L, "unable to find userlist '%s'",
1198 argp[idx].data.str.area);
Christopher Fauletd25d9262020-08-06 11:04:46 +02001199 goto error;
1200 }
1201 argp[idx].type = ARGT_USR;
1202 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001203 break;
1204
1205 case ARGT_STR:
1206 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1207 msg = "unable to duplicate string arg";
1208 goto error;
1209 }
1210 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001211 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001212
Christopher Fauletd25d9262020-08-06 11:04:46 +02001213 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001214 msg = "type not yet supported";
1215 goto error;
1216 break;
1217
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001218 }
1219
1220 /* Check for type of argument. */
1221 if ((mask & ARGT_MASK) != argp[idx].type) {
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001222 msg = hlua_pushfstring_safe(L, "'%s' expected, got '%s'",
1223 arg_type_names[(mask & ARGT_MASK)],
1224 arg_type_names[argp[idx].type & ARGT_MASK]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001225 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001226 }
1227
1228 /* Next argument. */
1229 mask >>= ARGT_BITS;
1230 idx++;
1231 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001232 return 0;
1233
1234 error:
Olivier Houchardda25dac2022-09-13 00:31:17 +02001235 argp[idx].type = ARGT_STOP;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001236 for (i = 0; i < idx; i++) {
1237 if (argp[i].type == ARGT_STR)
1238 chunk_destroy(&argp[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001239 else if (argp[i].type == ARGT_REG)
1240 regex_free(argp[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001241 }
1242 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1243 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001244}
1245
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001246/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001247 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001248 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001249 *
1250 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001251 * - hlua_sethlua : create the association between hlua context and lua_state.
1252 */
1253static inline struct hlua *hlua_gethlua(lua_State *L)
1254{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001255 struct hlua **hlua = lua_getextraspace(L);
1256 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001257}
1258static inline void hlua_sethlua(struct hlua *hlua)
1259{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001260 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1261 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001262}
1263
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001264/* This function is used to send logs. It try to send on screen (stderr)
1265 * and on the default syslog server.
1266 */
1267static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1268{
1269 struct tm tm;
1270 char *p;
1271
1272 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001273 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001274 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001275 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001276 /* Break the message if exceed the buffer size. */
1277 *(p-4) = ' ';
1278 *(p-3) = '.';
1279 *(p-2) = '.';
1280 *(p-1) = '.';
1281 break;
1282 }
Willy Tarreau90807112020-02-25 08:16:33 +01001283 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001284 *p = *msg;
1285 else
1286 *p = '.';
1287 }
1288 *p = '\0';
1289
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001290 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001291 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001292 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1293 return;
1294
Willy Tarreaua678b432015-08-28 10:14:59 +02001295 get_localtime(date.tv_sec, &tm);
1296 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001297 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001298 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001299 fflush(stderr);
1300 }
1301}
1302
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001303/* This function just ensure that the yield will be always
1304 * returned with a timeout and permit to set some flags
1305 */
Aurelien DARRAGONf5d3b312023-07-13 10:18:04 +02001306__LJMP void hlua_yieldk(lua_State *L, int nresults, lua_KContext ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001307 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001308{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001309 struct hlua *hlua;
1310
1311 /* Get hlua struct, or NULL if we execute from main lua state */
1312 hlua = hlua_gethlua(L);
1313 if (!hlua) {
1314 return;
1315 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001316
1317 /* Set the wake timeout. If timeout is required, we set
1318 * the expiration time.
1319 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001320 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001321
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001322 hlua->flags |= flags;
1323
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001324 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001325 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001326}
1327
Willy Tarreau87b09662015-04-03 00:22:06 +02001328/* This function initialises the Lua environment stored in the stream.
1329 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001330 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001331 *
1332 * This function is particular. it initialises a new Lua thread. If the
1333 * initialisation fails (example: out of memory error), the lua function
1334 * throws an error (longjmp).
1335 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001336 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001337 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001338 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001339 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001340 */
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01001341int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001342{
1343 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001344 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001345 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001346 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001347 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001348 LIST_INIT(&lua->com);
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01001349 if (!SET_SAFE_LJMP_PARENT(lua)) {
1350 lua->Tref = LUA_REFNIL;
1351 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001352 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001353 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001354 if (!lua->T) {
1355 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01001356 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001357 return 0;
1358 }
1359 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001360 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001361 lua->task = task;
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01001362 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001363 return 1;
1364}
1365
Willy Tarreau87b09662015-04-03 00:22:06 +02001366/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001367 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGONd5c8a102023-03-01 16:45:50 +01001368 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001369 */
1370void hlua_ctx_destroy(struct hlua *lua)
1371{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001372 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001373 return;
1374
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001375 if (!lua->T)
1376 goto end;
1377
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001378 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001379 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001380
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001381 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001382 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001383 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001384 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001385
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001386 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001387 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001388 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001389 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001390 /* Forces a garbage collecting process. If the Lua program is finished
1391 * without error, we run the GC on the thread pointer. Its freed all
1392 * the unused memory.
1393 * If the thread is finnish with an error or is currently yielded,
1394 * it seems that the GC applied on the thread doesn't clean anything,
1395 * so e run the GC on the main thread.
1396 * NOTE: maybe this action locks all the Lua threads untiml the en of
1397 * the garbage collection.
1398 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001399 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001400 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001401 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001402 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001403 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001404 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001405
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001406 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001407
1408end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001409 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001410}
1411
1412/* This function is used to restore the Lua context when a coroutine
1413 * fails. This function copy the common memory between old coroutine
1414 * and the new coroutine. The old coroutine is destroyed, and its
1415 * replaced by the new coroutine.
1416 * If the flag "keep_msg" is set, the last entry of the old is assumed
1417 * as string error message and it is copied in the new stack.
1418 */
1419static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1420{
1421 lua_State *T;
1422 int new_ref;
1423
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001424 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001425 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001426 if (!T)
1427 return 0;
1428
1429 /* Copy last error message. */
1430 if (keep_msg)
1431 lua_xmove(lua->T, T, 1);
1432
1433 /* Copy data between the coroutines. */
1434 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1435 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001436 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001437
1438 /* Destroy old data. */
1439 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1440
1441 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001442 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001443
1444 /* Fill the struct with the new coroutine values. */
1445 lua->Mref = new_ref;
1446 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001447 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001448
1449 /* Set context. */
1450 hlua_sethlua(lua);
1451
1452 return 1;
1453}
1454
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001455/* Helper function to get the lua ctx for a given stream and state_id */
1456static inline struct hlua *hlua_stream_ctx_get(struct stream *s, int state_id)
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001457{
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001458 /* state_id == 0 -> global runtime ctx
1459 * state_id != 0 -> per-thread runtime ctx
1460 */
1461 return s->hlua[!!state_id];
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001462}
1463
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001464/* Helper function to prepare the lua ctx for a given stream and state id
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001465 *
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001466 * It uses the global or per-thread ctx depending on the expected
1467 * <state_id>.
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001468 *
1469 * Returns hlua ctx on success and NULL on failure
1470 */
1471static struct hlua *hlua_stream_ctx_prepare(struct stream *s, int state_id)
1472{
1473 /* In the execution wrappers linked with a stream, the
1474 * Lua context can be not initialized. This behavior
1475 * permits to save performances because a systematic
1476 * Lua initialization cause 5% performances loss.
1477 */
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001478 if (!s->hlua[!!state_id]) {
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001479 struct hlua *hlua;
1480
1481 hlua = pool_alloc(pool_head_hlua);
1482 if (!hlua)
1483 return NULL;
1484 HLUA_INIT(hlua);
1485 if (!hlua_ctx_init(hlua, state_id, s->task)) {
1486 pool_free(pool_head_hlua, hlua);
1487 return NULL;
1488 }
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001489 s->hlua[!!state_id] = hlua;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001490 }
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001491 return s->hlua[!!state_id];
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001492}
1493
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001494void hlua_hook(lua_State *L, lua_Debug *ar)
1495{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001496 struct hlua *hlua;
1497
1498 /* Get hlua struct, or NULL if we execute from main lua state */
1499 hlua = hlua_gethlua(L);
1500 if (!hlua)
1501 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001502
1503 /* Lua cannot yield when its returning from a function,
1504 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001505 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001506 */
1507 if (lua_gethookmask(L) & LUA_MASKRET) {
1508 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1509 return;
1510 }
1511
1512 /* restore the interrupt condition. */
1513 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1514
1515 /* If we interrupt the Lua processing in yieldable state, we yield.
1516 * If the state is not yieldable, trying yield causes an error.
1517 */
1518 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001519 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001520
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001521 /* If we cannot yield, update the clock and check the timeout. */
1522 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001523 hlua->run_time += now_ms - hlua->start_time;
1524 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001525 lua_pushfstring(L, "execution timeout");
1526 WILL_LJMP(lua_error(L));
1527 }
1528
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001529 /* Update the start time. */
1530 hlua->start_time = now_ms;
1531
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001532 /* Try to interrupt the process at the end of the current
1533 * unyieldable function.
1534 */
1535 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001536}
1537
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001538/* This function start or resumes the Lua stack execution. If the flag
1539 * "yield_allowed" if no set and the LUA stack execution returns a yield
1540 * The function return an error.
1541 *
1542 * The function can returns 4 values:
1543 * - HLUA_E_OK : The execution is terminated without any errors.
1544 * - HLUA_E_AGAIN : The execution must continue at the next associated
1545 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001546 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001547 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001548 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001549 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001550 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001551 * LUA code.
1552 */
1553static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1554{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001555#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1556 int nres;
1557#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001558 int ret;
1559 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001560 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001561
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001562 /* Initialise run time counter. */
1563 if (!HLUA_IS_RUNNING(lua))
1564 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001565
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001566 /* Lock the whole Lua execution. This lock must be before the
1567 * label "resume_execution".
1568 */
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +01001569 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001570
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001571resume_execution:
1572
1573 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1574 * instructions. it is used for preventing infinite loops.
1575 */
1576 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1577
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001578 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001579 HLUA_SET_RUN(lua);
1580 HLUA_CLR_CTRLYIELD(lua);
1581 HLUA_CLR_WAKERESWR(lua);
1582 HLUA_CLR_WAKEREQWR(lua);
Christopher Fauleta6e792f2021-08-04 17:58:21 +02001583 HLUA_CLR_NOYIELD(lua);
1584 if (!yield_allowed)
1585 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001586
Christopher Fauletbc275a92020-02-26 14:55:16 +01001587 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001588 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001589 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001590
Aurelien DARRAGON5d351962024-03-12 00:22:44 +01001591 HLUA_SET_BUSY(lua);
1592
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001593 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001594#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001595 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001596#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001597 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001598#endif
Aurelien DARRAGONfff27962023-09-08 14:00:27 +02001599
Aurelien DARRAGON5d351962024-03-12 00:22:44 +01001600 HLUA_CLR_BUSY(lua);
1601
Aurelien DARRAGONfff27962023-09-08 14:00:27 +02001602 /* reset nargs because those possibly passed to the lua_resume() call
1603 * were already consumed, and since we may call lua_resume() again
1604 * after a successful yield, we don't want to pass stale nargs hint
1605 * to the Lua API. As such, nargs should be set explicitly before each
1606 * lua_resume() (or hlua_ctx_resume()) invocation if needed.
1607 */
1608 lua->nargs = 0;
1609
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001610 switch (ret) {
1611
1612 case LUA_OK:
1613 ret = HLUA_E_OK;
1614 break;
1615
1616 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001617 /* Check if the execution timeout is expired. It it is the case, we
1618 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001619 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001620 tv_update_date(0, 1);
1621 lua->run_time += now_ms - lua->start_time;
1622 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001623 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001624 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001625 break;
1626 }
1627 /* Process the forced yield. if the general yield is not allowed or
1628 * if no task were associated this the current Lua execution
1629 * coroutine, we resume the execution. Else we want to return in the
1630 * scheduler and we want to be waked up again, to continue the
1631 * current Lua execution. So we schedule our own task.
1632 */
1633 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001634 if (!yield_allowed || !lua->task)
1635 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001636 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001637 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001638 if (!yield_allowed) {
1639 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001640 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001641 break;
1642 }
1643 ret = HLUA_E_AGAIN;
1644 break;
1645
1646 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001647
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001648 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001649 * because the errors ares the only one mean to return immediately
1650 * from and lua execution.
1651 */
1652 if (lua->flags & HLUA_EXIT) {
1653 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001654 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001655 break;
1656 }
1657
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001658 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001659 if (!lua_checkstack(lua->T, 1)) {
1660 ret = HLUA_E_ERR;
1661 break;
1662 }
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01001663 msg = hlua_tostring_safe(lua->T, -1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001664 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001665 if (msg)
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001666 hlua_pushfstring_safe(lua->T, "[state-id %d] runtime error: %s from %s",
1667 lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001668 else
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001669 hlua_pushfstring_safe(lua->T, "[state-id %d] unknown runtime error from %s",
1670 lua->state_id, trace);
Aurelien DARRAGONadac9322024-03-01 19:54:16 +01001671
Aurelien DARRAGON0da54202024-06-04 15:52:23 +02001672 /* Move the error msg at the bottom and then empty the stack except last msg */
1673 lua_insert(lua->T, 1);
Aurelien DARRAGONadac9322024-03-01 19:54:16 +01001674 lua_settop(lua->T, 1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001675 ret = HLUA_E_ERRMSG;
1676 break;
1677
1678 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001679 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001680 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001681 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001682 break;
1683
1684 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001685 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001686 if (!lua_checkstack(lua->T, 1)) {
1687 ret = HLUA_E_ERR;
1688 break;
1689 }
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01001690 msg = hlua_tostring_safe(lua->T, -1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001691 if (msg)
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001692 hlua_pushfstring_safe(lua->T, "[state-id %d] message handler error: %s",
1693 lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001694 else
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001695 hlua_pushfstring_safe(lua->T, "[state-id %d] message handler error",
1696 lua->state_id);
Aurelien DARRAGONadac9322024-03-01 19:54:16 +01001697
Aurelien DARRAGON0da54202024-06-04 15:52:23 +02001698 /* Move the error msg at the bottom and then empty the stack except last msg */
1699 lua_insert(lua->T, 1);
Aurelien DARRAGONadac9322024-03-01 19:54:16 +01001700 lua_settop(lua->T, 1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001701 ret = HLUA_E_ERRMSG;
1702 break;
1703
1704 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001705 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001706 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001707 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001708 break;
1709 }
1710
1711 switch (ret) {
1712 case HLUA_E_AGAIN:
1713 break;
1714
1715 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001716 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001717 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001718 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001719 break;
1720
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001721 case HLUA_E_ETMOUT:
1722 case HLUA_E_NOMEM:
1723 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001724 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001725 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001726 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001727 hlua_ctx_renew(lua, 0);
1728 break;
1729
1730 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001731 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001732 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001733 break;
1734 }
1735
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001736 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +01001737 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001738
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001739 return ret;
1740}
1741
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001742/* This function exit the current code. */
1743__LJMP static int hlua_done(lua_State *L)
1744{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001745 struct hlua *hlua;
1746
1747 /* Get hlua struct, or NULL if we execute from main lua state */
1748 hlua = hlua_gethlua(L);
1749 if (!hlua)
1750 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001751
1752 hlua->flags |= HLUA_EXIT;
1753 WILL_LJMP(lua_error(L));
1754
1755 return 0;
1756}
1757
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001758/* This function is an LUA binding. It provides a function
1759 * for deleting ACL from a referenced ACL file.
1760 */
1761__LJMP static int hlua_del_acl(lua_State *L)
1762{
1763 const char *name;
1764 const char *key;
1765 struct pat_ref *ref;
1766
1767 MAY_LJMP(check_args(L, 2, "del_acl"));
1768
1769 name = MAY_LJMP(luaL_checkstring(L, 1));
1770 key = MAY_LJMP(luaL_checkstring(L, 2));
1771
1772 ref = pat_ref_lookup(name);
1773 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001774 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001775
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001776 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001777 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001778 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001779 return 0;
1780}
1781
1782/* This function is an LUA binding. It provides a function
1783 * for deleting map entry from a referenced map file.
1784 */
1785static int hlua_del_map(lua_State *L)
1786{
1787 const char *name;
1788 const char *key;
1789 struct pat_ref *ref;
1790
1791 MAY_LJMP(check_args(L, 2, "del_map"));
1792
1793 name = MAY_LJMP(luaL_checkstring(L, 1));
1794 key = MAY_LJMP(luaL_checkstring(L, 2));
1795
1796 ref = pat_ref_lookup(name);
1797 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001798 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001799
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001800 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001801 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001802 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001803 return 0;
1804}
1805
1806/* This function is an LUA binding. It provides a function
1807 * for adding ACL pattern from a referenced ACL file.
1808 */
1809static int hlua_add_acl(lua_State *L)
1810{
1811 const char *name;
1812 const char *key;
1813 struct pat_ref *ref;
1814
1815 MAY_LJMP(check_args(L, 2, "add_acl"));
1816
1817 name = MAY_LJMP(luaL_checkstring(L, 1));
1818 key = MAY_LJMP(luaL_checkstring(L, 2));
1819
1820 ref = pat_ref_lookup(name);
1821 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001822 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001823
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001824 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001825 if (pat_ref_find_elt(ref, key) == NULL)
1826 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001827 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001828 return 0;
1829}
1830
1831/* This function is an LUA binding. It provides a function
1832 * for setting map pattern and sample from a referenced map
1833 * file.
1834 */
1835static int hlua_set_map(lua_State *L)
1836{
1837 const char *name;
1838 const char *key;
1839 const char *value;
1840 struct pat_ref *ref;
1841
1842 MAY_LJMP(check_args(L, 3, "set_map"));
1843
1844 name = MAY_LJMP(luaL_checkstring(L, 1));
1845 key = MAY_LJMP(luaL_checkstring(L, 2));
1846 value = MAY_LJMP(luaL_checkstring(L, 3));
1847
1848 ref = pat_ref_lookup(name);
1849 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001850 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001851
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001852 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001853 if (pat_ref_find_elt(ref, key) != NULL)
1854 pat_ref_set(ref, key, value, NULL);
1855 else
1856 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001857 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001858 return 0;
1859}
1860
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001861/* A class is a lot of memory that contain data. This data can be a table,
1862 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001863 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001864 * the name of the object (_G[<name>] = <metable> ).
1865 *
1866 * A metable is a table that modify the standard behavior of a standard
1867 * access to the associated data. The entries of this new metatable are
1868 * defined as is:
1869 *
1870 * http://lua-users.org/wiki/MetatableEvents
1871 *
1872 * __index
1873 *
1874 * we access an absent field in a table, the result is nil. This is
1875 * true, but it is not the whole truth. Actually, such access triggers
1876 * the interpreter to look for an __index metamethod: If there is no
1877 * such method, as usually happens, then the access results in nil;
1878 * otherwise, the metamethod will provide the result.
1879 *
1880 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1881 * the key does not appear in the table, but the metatable has an __index
1882 * property:
1883 *
1884 * - if the value is a function, the function is called, passing in the
1885 * table and the key; the return value of that function is returned as
1886 * the result.
1887 *
1888 * - if the value is another table, the value of the key in that table is
1889 * asked for and returned (and if it doesn't exist in that table, but that
1890 * table's metatable has an __index property, then it continues on up)
1891 *
1892 * - Use "rawget(myTable,key)" to skip this metamethod.
1893 *
1894 * http://www.lua.org/pil/13.4.1.html
1895 *
1896 * __newindex
1897 *
1898 * Like __index, but control property assignment.
1899 *
1900 * __mode - Control weak references. A string value with one or both
1901 * of the characters 'k' and 'v' which specifies that the the
1902 * keys and/or values in the table are weak references.
1903 *
1904 * __call - Treat a table like a function. When a table is followed by
1905 * parenthesis such as "myTable( 'foo' )" and the metatable has
1906 * a __call key pointing to a function, that function is invoked
1907 * (passing any specified arguments) and the return value is
1908 * returned.
1909 *
1910 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1911 * called, if the metatable for myTable has a __metatable
1912 * key, the value of that key is returned instead of the
1913 * actual metatable.
1914 *
1915 * __tostring - Control string representation. When the builtin
1916 * "tostring( myTable )" function is called, if the metatable
1917 * for myTable has a __tostring property set to a function,
1918 * that function is invoked (passing myTable to it) and the
1919 * return value is used as the string representation.
1920 *
1921 * __len - Control table length. When the table length is requested using
1922 * the length operator ( '#' ), if the metatable for myTable has
1923 * a __len key pointing to a function, that function is invoked
1924 * (passing myTable to it) and the return value used as the value
1925 * of "#myTable".
1926 *
1927 * __gc - Userdata finalizer code. When userdata is set to be garbage
1928 * collected, if the metatable has a __gc field pointing to a
1929 * function, that function is first invoked, passing the userdata
1930 * to it. The __gc metamethod is not called for tables.
1931 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1932 *
1933 * Special metamethods for redefining standard operators:
1934 * http://www.lua.org/pil/13.1.html
1935 *
1936 * __add "+"
1937 * __sub "-"
1938 * __mul "*"
1939 * __div "/"
1940 * __unm "!"
1941 * __pow "^"
1942 * __concat ".."
1943 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001944 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001945 * http://www.lua.org/pil/13.2.html
1946 *
1947 * __eq "=="
1948 * __lt "<"
1949 * __le "<="
1950 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001951
1952/*
1953 *
1954 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001955 * Class Map
1956 *
1957 *
1958 */
1959
1960/* Returns a struct hlua_map if the stack entry "ud" is
1961 * a class session, otherwise it throws an error.
1962 */
1963__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1964{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001965 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001966}
1967
1968/* This function is the map constructor. It don't need
1969 * the class Map object. It creates and return a new Map
1970 * object. It must be called only during "body" or "init"
1971 * context because it process some filesystem accesses.
1972 */
1973__LJMP static int hlua_map_new(struct lua_State *L)
1974{
1975 const char *fn;
1976 int match = PAT_MATCH_STR;
1977 struct sample_conv conv;
1978 const char *file = "";
1979 int line = 0;
1980 lua_Debug ar;
1981 char *err = NULL;
1982 struct arg args[2];
1983
1984 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1985 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1986
1987 fn = MAY_LJMP(luaL_checkstring(L, 1));
1988
1989 if (lua_gettop(L) >= 2) {
1990 match = MAY_LJMP(luaL_checkinteger(L, 2));
1991 if (match < 0 || match >= PAT_MATCH_NUM)
1992 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1993 }
1994
1995 /* Get Lua filename and line number. */
1996 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1997 lua_getinfo(L, "Sl", &ar); /* get info about it */
1998 if (ar.currentline > 0) { /* is there info? */
1999 file = ar.short_src;
2000 line = ar.currentline;
2001 }
2002 }
2003
2004 /* fill fake sample_conv struct. */
2005 conv.kw = ""; /* unused. */
2006 conv.process = NULL; /* unused. */
2007 conv.arg_mask = 0; /* unused. */
2008 conv.val_args = NULL; /* unused. */
2009 conv.out_type = SMP_T_STR;
2010 conv.private = (void *)(long)match;
2011 switch (match) {
2012 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
2013 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
2014 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
2015 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
2016 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
2017 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
2018 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002019 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002020 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
2021 default:
2022 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
2023 }
2024
2025 /* fill fake args. */
2026 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02002027 args[0].data.str.area = strdup(fn);
2028 args[0].data.str.data = strlen(fn);
2029 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002030 args[1].type = ARGT_STOP;
2031
2032 /* load the map. */
2033 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002034 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002035 * free the err variable.
2036 */
Aurelien DARRAGONca0cdfe2024-06-04 12:48:45 +02002037 hlua_pusherror(L, "'new': %s.", err);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002038 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02002039 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002040 WILL_LJMP(lua_error(L));
2041 }
2042
2043 /* create the lua object. */
2044 lua_newtable(L);
2045 lua_pushlightuserdata(L, args[0].data.map);
2046 lua_rawseti(L, -2, 0);
2047
2048 /* Pop a class Map metatable and affect it to the userdata. */
2049 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
2050 lua_setmetatable(L, -2);
2051
2052
2053 return 1;
2054}
2055
2056__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
2057{
2058 struct map_descriptor *desc;
2059 struct pattern *pat;
2060 struct sample smp;
2061
2062 MAY_LJMP(check_args(L, 2, "lookup"));
2063 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002064 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002065 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002066 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002067 }
2068 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002069 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002070 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002071 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 +01002072 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002073 }
2074
2075 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002076 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002077 if (str)
2078 lua_pushstring(L, "");
2079 else
2080 lua_pushnil(L);
2081 return 1;
2082 }
2083
2084 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002085 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002086 return 1;
2087}
2088
2089__LJMP static int hlua_map_lookup(struct lua_State *L)
2090{
2091 return _hlua_map_lookup(L, 0);
2092}
2093
2094__LJMP static int hlua_map_slookup(struct lua_State *L)
2095{
2096 return _hlua_map_lookup(L, 1);
2097}
2098
2099/*
2100 *
2101 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002102 * Class Socket
2103 *
2104 *
2105 */
2106
2107__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2108{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002109 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002110}
2111
2112/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002113 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002114 * received.
2115 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002116static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117{
Willy Tarreau00a37f02015-04-13 12:05:19 +02002118 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002119
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002120 if (appctx->ctx.hlua_cosocket.die) {
2121 si_shutw(si);
2122 si_shutr(si);
2123 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002124 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
2125 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002126 stream_shutdown(si_strm(si), SF_ERR_KILLED);
2127 }
2128
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002129 /* If we can't write, wakeup the pending write signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002130 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002131 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002132
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002133 /* If we can't read, wakeup the pending read signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002134 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002135 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002136
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002137 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002138 * to be notified whenever the connection completes.
2139 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002140 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002141 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01002142 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01002143 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002144 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002145 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146
2147 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002148 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002150 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02002151 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002152 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002153
2154 /* Wake the tasks which wants to read if the buffer contains data. */
Christopher Faulet174144c2024-02-16 15:33:44 +01002155 if (!channel_is_empty(si_oc(si))) {
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002156 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Christopher Faulet174144c2024-02-16 15:33:44 +01002157 si_cant_get(si);
2158 }
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002159
2160 /* Some data were injected in the buffer, notify the stream
2161 * interface.
2162 */
2163 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01002164 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002165
2166 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002167 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002168 */
2169 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01002170 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002171}
2172
Willy Tarreau87b09662015-04-03 00:22:06 +02002173/* This function is called when the "struct stream" is destroyed.
2174 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175 * Wake all the pending signals.
2176 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002177static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002179 struct xref *peer;
2180
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002182 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
2183 if (peer)
2184 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002185
2186 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002187 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
2188 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002189}
2190
2191/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002192 * uses this object. If the stream does not exists, just quit.
2193 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 * pending signal can rest in the read and write lists. destroy
2195 * it.
2196 */
2197__LJMP static int hlua_socket_gc(lua_State *L)
2198{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002199 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002201 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002203 MAY_LJMP(check_args(L, 1, "__gc"));
2204
2205 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002206 peer = xref_get_peer_and_lock(&socket->xref);
2207 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002209 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002210
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002211 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002212 appctx->ctx.hlua_cosocket.die = 1;
2213 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002215 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002216 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217 return 0;
2218}
2219
2220/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002221 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002222 */
sada05ed3302018-05-11 11:48:18 -07002223__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002225 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002227 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002228 struct hlua *hlua;
2229
2230 /* Get hlua struct, or NULL if we execute from main lua state */
2231 hlua = hlua_gethlua(L);
2232 if (!hlua)
2233 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002234
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002235 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002236
2237 /* Check if we run on the same thread than the xreator thread.
2238 * We cannot access to the socket if the thread is different.
2239 */
2240 if (socket->tid != tid)
2241 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2242
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002243 peer = xref_get_peer_and_lock(&socket->xref);
2244 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002246
2247 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002248 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002250 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002251 appctx->ctx.hlua_cosocket.die = 1;
2252 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002254 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002255 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002256 return 0;
2257}
2258
sada05ed3302018-05-11 11:48:18 -07002259/* The close function calls close_helper.
2260 */
2261__LJMP static int hlua_socket_close(lua_State *L)
2262{
2263 MAY_LJMP(check_args(L, 1, "close"));
2264 return hlua_socket_close_helper(L);
2265}
2266
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002267/* This Lua function assumes that the stack contain three parameters.
2268 * 1 - USERDATA containing a struct socket
2269 * 2 - INTEGER with values of the macro defined below
2270 * If the integer is -1, we must read at most one line.
2271 * If the integer is -2, we ust read all the data until the
2272 * end of the stream.
2273 * If the integer is positive value, we must read a number of
2274 * bytes corresponding to this value.
2275 */
2276#define HLSR_READ_LINE (-1)
2277#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002278__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279{
2280 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2281 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002282 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002284 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002285 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002286 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002287 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002288 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002289 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002290 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002291 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002292 struct stream_interface *si;
2293 struct stream *s;
2294 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002295 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002297 /* Get hlua struct, or NULL if we execute from main lua state */
2298 hlua = hlua_gethlua(L);
2299
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300 /* Check if this lua stack is schedulable. */
2301 if (!hlua || !hlua->task)
2302 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2303 "'frontend', 'backend' or 'task'"));
2304
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002305 /* Check if we run on the same thread than the xreator thread.
2306 * We cannot access to the socket if the thread is different.
2307 */
2308 if (socket->tid != tid)
2309 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2310
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002311 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002312 peer = xref_get_peer_and_lock(&socket->xref);
2313 if (!peer)
2314 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002315 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2316 si = appctx->owner;
2317 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002318
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002319 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002320 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002322 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 if (nblk < 0) /* Connection close. */
2324 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002325 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002327
2328 /* remove final \r\n. */
2329 if (nblk == 1) {
2330 if (blk1[len1-1] == '\n') {
2331 len1--;
2332 skip_at_end++;
2333 if (blk1[len1-1] == '\r') {
2334 len1--;
2335 skip_at_end++;
2336 }
2337 }
2338 }
2339 else {
2340 if (blk2[len2-1] == '\n') {
2341 len2--;
2342 skip_at_end++;
2343 if (blk2[len2-1] == '\r') {
2344 len2--;
2345 skip_at_end++;
2346 }
2347 }
2348 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 }
2350
2351 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002353 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002354 if (nblk < 0) /* Connection close. */
2355 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002356 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357 goto connection_empty;
2358 }
2359
2360 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002362 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002363 if (nblk < 0) /* Connection close. */
2364 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002365 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366 goto connection_empty;
2367
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002368 missing_bytes = wanted - socket->b.n;
2369 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002370 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002371 len1 = missing_bytes;
2372 } if (nblk == 2 && len1 + len2 > missing_bytes)
2373 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374 }
2375
2376 len = len1;
2377
2378 luaL_addlstring(&socket->b, blk1, len1);
2379 if (nblk == 2) {
2380 len += len2;
2381 luaL_addlstring(&socket->b, blk2, len2);
2382 }
2383
2384 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002385 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002386
2387 /* Don't wait anything. */
Christopher Faulet174144c2024-02-16 15:33:44 +01002388 si_want_get(si);
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002389 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002390
2391 /* If the pattern reclaim to read all the data
2392 * in the connection, got out.
2393 */
2394 if (wanted == HLSR_READ_ALL)
2395 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002396 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002397 goto connection_empty;
2398
2399 /* Return result. */
2400 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002401 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002402 return 1;
2403
2404connection_closed:
2405
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002406 xref_unlock(&socket->xref, peer);
2407
2408no_peer:
2409
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002410 /* If the buffer containds data. */
2411 if (socket->b.n > 0) {
2412 luaL_pushresult(&socket->b);
2413 return 1;
2414 }
2415 lua_pushnil(L);
2416 lua_pushstring(L, "connection closed.");
2417 return 2;
2418
2419connection_empty:
2420
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002421 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
2422 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002423 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002424 }
2425 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002426 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002427 return 0;
2428}
2429
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002430/* This Lua function gets two parameters. The first one can be string
2431 * or a number. If the string is "*l", the user requires one line. If
2432 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002433 * If the value is a number, the user require a number of bytes equal
2434 * to the value. The default value is "*l" (a line).
2435 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002436 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002437 * integer takes this values:
2438 * -1 : read a line
2439 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002440 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002441 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002442 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002443 * concatenated with the read data.
2444 */
2445__LJMP static int hlua_socket_receive(struct lua_State *L)
2446{
2447 int wanted = HLSR_READ_LINE;
2448 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002449 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002450 char *error;
2451 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002452 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002453
2454 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2455 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2456
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002457 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002458
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002459 /* Check if we run on the same thread than the xreator thread.
2460 * We cannot access to the socket if the thread is different.
2461 */
2462 if (socket->tid != tid)
2463 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2464
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465 /* check for pattern. */
2466 if (lua_gettop(L) >= 2) {
2467 type = lua_type(L, 2);
2468 if (type == LUA_TSTRING) {
2469 pattern = lua_tostring(L, 2);
2470 if (strcmp(pattern, "*a") == 0)
2471 wanted = HLSR_READ_ALL;
2472 else if (strcmp(pattern, "*l") == 0)
2473 wanted = HLSR_READ_LINE;
2474 else {
2475 wanted = strtoll(pattern, &error, 10);
2476 if (*error != '\0')
2477 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2478 }
2479 }
2480 else if (type == LUA_TNUMBER) {
2481 wanted = lua_tointeger(L, 2);
2482 if (wanted < 0)
2483 WILL_LJMP(luaL_error(L, "Unsupported size."));
2484 }
2485 }
2486
2487 /* Set pattern. */
2488 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002489
2490 /* Check if we would replace the top by itself. */
2491 if (lua_gettop(L) != 2)
2492 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002493
Christopher Fauletc31b2002021-05-03 10:11:13 +02002494 /* Save index of the top of the stack because since buffers are used, it
2495 * may change
2496 */
2497 lastarg = lua_gettop(L);
2498
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002499 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500 luaL_buffinit(L, &socket->b);
2501
2502 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002503 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002504 if (lua_type(L, 3) != LUA_TSTRING)
2505 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2506 pattern = lua_tolstring(L, 3, &len);
2507 luaL_addlstring(&socket->b, pattern, len);
2508 }
2509
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002510 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002511}
2512
2513/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002514 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002516static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002517{
2518 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002519 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002520 struct appctx *appctx;
2521 size_t buf_len;
2522 const char *buf;
2523 int len;
2524 int send_len;
2525 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002526 struct xref *peer;
2527 struct stream_interface *si;
2528 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002529
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002530 /* Get hlua struct, or NULL if we execute from main lua state */
2531 hlua = hlua_gethlua(L);
2532
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002533 /* Check if this lua stack is schedulable. */
2534 if (!hlua || !hlua->task)
2535 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2536 "'frontend', 'backend' or 'task'"));
2537
2538 /* Get object */
2539 socket = MAY_LJMP(hlua_checksocket(L, 1));
2540 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002541 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002543 /* Check if we run on the same thread than the xreator thread.
2544 * We cannot access to the socket if the thread is different.
2545 */
2546 if (socket->tid != tid)
2547 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2548
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002549 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002550 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002551 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002552 lua_pushinteger(L, -1);
2553 return 1;
2554 }
2555 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2556 si = appctx->owner;
2557 s = si_strm(si);
2558
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002559 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002560 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002561 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002562 lua_pushinteger(L, -1);
2563 return 1;
2564 }
2565
2566 /* Update the input buffer data. */
2567 buf += sent;
2568 send_len = buf_len - sent;
2569
2570 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002571 if (sent >= buf_len) {
2572 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002573 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002574 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002576 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002577 * the request buffer if its not required.
2578 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002579 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002580 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002581 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002582 }
2583
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002584 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002585 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002586 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002587 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002588 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002589
2590 /* send data */
2591 if (len < send_len)
2592 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002593 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594
2595 /* "Not enough space" (-1), "Buffer too little to contain
2596 * the data" (-2) are not expected because the available length
2597 * is tested.
2598 * Other unknown error are also not expected.
2599 */
2600 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002601 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002602 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002603
sada05ed3302018-05-11 11:48:18 -07002604 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002605 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002606 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002607 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002608 return 1;
2609 }
2610
2611 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002612 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002613
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002614 s->req.rex = TICK_ETERNITY;
2615 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002616
2617 /* Update length sent. */
2618 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002619 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002620
2621 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002622 if (sent + len >= buf_len) {
2623 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002624 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002625 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002626
2627hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002628 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2629 xref_unlock(&socket->xref, peer);
2630 WILL_LJMP(luaL_error(L, "out of memory"));
2631 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002632 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002633 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634 return 0;
2635}
2636
2637/* This function initiate the send of data. It just check the input
2638 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002639 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002640 * "hlua_socket_write_yield" that can yield.
2641 *
2642 * The Lua function gets between 3 and 4 parameters. The first one is
2643 * the associated object. The second is a string buffer. The third is
2644 * a facultative integer that represents where is the buffer position
2645 * of the start of the data that can send. The first byte is the
2646 * position "1". The default value is "1". The fourth argument is a
2647 * facultative integer that represents where is the buffer position
2648 * of the end of the data that can send. The default is the last byte.
2649 */
2650static int hlua_socket_send(struct lua_State *L)
2651{
2652 int i;
2653 int j;
2654 const char *buf;
2655 size_t buf_len;
2656
2657 /* Check number of arguments. */
2658 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2659 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2660
2661 /* Get the string. */
2662 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2663
2664 /* Get and check j. */
2665 if (lua_gettop(L) == 4) {
2666 j = MAY_LJMP(luaL_checkinteger(L, 4));
2667 if (j < 0)
2668 j = buf_len + j + 1;
2669 if (j > buf_len)
2670 j = buf_len + 1;
2671 lua_pop(L, 1);
2672 }
2673 else
2674 j = buf_len;
2675
2676 /* Get and check i. */
2677 if (lua_gettop(L) == 3) {
2678 i = MAY_LJMP(luaL_checkinteger(L, 3));
2679 if (i < 0)
2680 i = buf_len + i + 1;
2681 if (i > buf_len)
2682 i = buf_len + 1;
2683 lua_pop(L, 1);
2684 } else
2685 i = 1;
2686
2687 /* Check bth i and j. */
2688 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002689 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002690 return 1;
2691 }
2692 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002693 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002694 return 1;
2695 }
2696 if (i == 0)
2697 i = 1;
2698 if (j == 0)
2699 j = 1;
2700
2701 /* Pop the string. */
2702 lua_pop(L, 1);
2703
2704 /* Update the buffer length. */
2705 buf += i - 1;
2706 buf_len = j - i + 1;
2707 lua_pushlstring(L, buf, buf_len);
2708
2709 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002710 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002711
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002712 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002713}
2714
Willy Tarreau22b0a682015-06-17 19:43:49 +02002715#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002716__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2717{
2718 static char buffer[SOCKET_INFO_MAX_LEN];
2719 int ret;
2720 int len;
2721 char *p;
2722
2723 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2724 if (ret <= 0) {
2725 lua_pushnil(L);
2726 return 1;
2727 }
2728
2729 if (ret == AF_UNIX) {
2730 lua_pushstring(L, buffer+1);
2731 return 1;
2732 }
2733 else if (ret == AF_INET6) {
2734 buffer[0] = '[';
2735 len = strlen(buffer);
2736 buffer[len] = ']';
2737 len++;
2738 buffer[len] = ':';
2739 len++;
2740 p = buffer;
2741 }
2742 else if (ret == AF_INET) {
2743 p = buffer + 1;
2744 len = strlen(p);
2745 p[len] = ':';
2746 len++;
2747 }
2748 else {
2749 lua_pushnil(L);
2750 return 1;
2751 }
2752
2753 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2754 lua_pushnil(L);
2755 return 1;
2756 }
2757
2758 lua_pushstring(L, p);
2759 return 1;
2760}
2761
2762/* Returns information about the peer of the connection. */
2763__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2764{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002765 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002766 struct xref *peer;
2767 struct appctx *appctx;
2768 struct stream_interface *si;
2769 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002770 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002771
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002772 MAY_LJMP(check_args(L, 1, "getpeername"));
2773
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002774 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002775
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002776 /* Check if we run on the same thread than the xreator thread.
2777 * We cannot access to the socket if the thread is different.
2778 */
2779 if (socket->tid != tid)
2780 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2781
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002782 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002783 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002784 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002785 lua_pushnil(L);
2786 return 1;
2787 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002788 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2789 si = appctx->owner;
2790 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002791
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002792 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002793 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002794 lua_pushnil(L);
2795 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002796 }
2797
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002798 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002799 xref_unlock(&socket->xref, peer);
2800 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002801}
2802
2803/* Returns information about my connection side. */
2804static int hlua_socket_getsockname(struct lua_State *L)
2805{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002806 struct hlua_socket *socket;
2807 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002808 struct appctx *appctx;
2809 struct xref *peer;
2810 struct stream_interface *si;
2811 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002812 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002813
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002814 MAY_LJMP(check_args(L, 1, "getsockname"));
2815
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002816 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002817
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002818 /* Check if we run on the same thread than the xreator thread.
2819 * We cannot access to the socket if the thread is different.
2820 */
2821 if (socket->tid != tid)
2822 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2823
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002824 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002825 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002826 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002827 lua_pushnil(L);
2828 return 1;
2829 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002830 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2831 si = appctx->owner;
2832 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002833
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002834 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002835 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002836 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002837 lua_pushnil(L);
2838 return 1;
2839 }
2840
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002841 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002842 xref_unlock(&socket->xref, peer);
2843 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002844}
2845
2846/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002847static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002848 .obj_type = OBJ_TYPE_APPLET,
2849 .name = "<LUA_TCP>",
2850 .fct = hlua_socket_handler,
2851 .release = hlua_socket_release,
2852};
2853
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002854__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002855{
2856 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002857 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002858 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002859 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002860 struct stream_interface *si;
2861 struct stream *s;
2862
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002863 /* Get hlua struct, or NULL if we execute from main lua state */
2864 hlua = hlua_gethlua(L);
2865 if (!hlua)
2866 return 0;
2867
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002868 /* Check if we run on the same thread than the xreator thread.
2869 * We cannot access to the socket if the thread is different.
2870 */
2871 if (socket->tid != tid)
2872 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2873
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002874 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002875 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002876 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002877 lua_pushnil(L);
2878 lua_pushstring(L, "Can't connect");
2879 return 2;
2880 }
2881 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2882 si = appctx->owner;
2883 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002884
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002885 /* Check if we run on the same thread than the xreator thread.
2886 * We cannot access to the socket if the thread is different.
2887 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002888 if (socket->tid != tid) {
2889 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002890 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002891 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002892
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002893 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002894 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002895 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002896 lua_pushnil(L);
2897 lua_pushstring(L, "Can't connect");
2898 return 2;
2899 }
2900
Willy Tarreaue09101e2018-10-16 17:37:12 +02002901 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002902
2903 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002904 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002905 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002906 lua_pushinteger(L, 1);
2907 return 1;
2908 }
2909
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002910 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2911 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002912 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002913 }
2914 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002915 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002916 return 0;
2917}
2918
2919/* This function fail or initite the connection. */
2920__LJMP static int hlua_socket_connect(struct lua_State *L)
2921{
2922 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002923 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002924 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002925 struct hlua *hlua;
2926 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002927 int low, high;
2928 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002929 struct xref *peer;
2930 struct stream_interface *si;
2931 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002932
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002933 if (lua_gettop(L) < 2)
2934 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002935
2936 /* Get args. */
2937 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002938
2939 /* Check if we run on the same thread than the xreator thread.
2940 * We cannot access to the socket if the thread is different.
2941 */
2942 if (socket->tid != tid)
2943 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2944
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002945 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002946 if (lua_gettop(L) >= 3) {
2947 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002948 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002949
Tim Duesterhus6edab862018-01-06 19:04:45 +01002950 /* Force the ip to end with a colon, to support IPv6 addresses
2951 * that are not enclosed within square brackets.
2952 */
2953 if (port > 0) {
2954 luaL_buffinit(L, &b);
2955 luaL_addstring(&b, ip);
2956 luaL_addchar(&b, ':');
2957 luaL_pushresult(&b);
2958 ip = lua_tolstring(L, lua_gettop(L), NULL);
2959 }
2960 }
2961
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002962 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002963 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002964 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002965 lua_pushnil(L);
2966 return 1;
2967 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002968
2969 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002970 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 +02002971 if (!addr) {
2972 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002973 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002974 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002975
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002976 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002977 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002978 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002979 if (port == -1) {
2980 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002981 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002982 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002983 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2984 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002985 if (port == -1) {
2986 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002987 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002988 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002989 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002990 }
2991 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002992
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002993 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2994 si = appctx->owner;
2995 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002996
Willy Tarreau9b7587a2020-10-15 07:32:10 +02002997 if (!sockaddr_alloc(&s->target_addr, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002998 xref_unlock(&socket->xref, peer);
2999 WILL_LJMP(luaL_error(L, "connect: internal error"));
3000 }
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02003001 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003002
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003003 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003004 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003005 if (!hlua)
3006 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003007
3008 /* inform the stream that we want to be notified whenever the
3009 * connection completes.
3010 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003011 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01003012 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02003013 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02003014
Willy Tarreauf31af932020-01-14 09:59:38 +01003015 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02003016
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003017 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
3018 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01003019 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003020 }
3021 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02003022
3023 task_wakeup(s->task, TASK_WOKEN_INIT);
3024 /* Return yield waiting for connection. */
3025
Willy Tarreau9635e032018-10-16 17:52:55 +02003026 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003027
3028 return 0;
3029}
3030
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003031#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003032__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
3033{
3034 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003035 struct xref *peer;
3036 struct appctx *appctx;
3037 struct stream_interface *si;
3038 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003039
3040 MAY_LJMP(check_args(L, 3, "connect_ssl"));
3041 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003042
3043 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003044 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003045 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003046 lua_pushnil(L);
3047 return 1;
3048 }
3049 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
3050 si = appctx->owner;
3051 s = si_strm(si);
3052
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003053 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003054 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003055 return MAY_LJMP(hlua_socket_connect(L));
3056}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003057#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003058
3059__LJMP static int hlua_socket_setoption(struct lua_State *L)
3060{
3061 return 0;
3062}
3063
3064__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3065{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003066 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003067 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003068 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003069 struct xref *peer;
3070 struct appctx *appctx;
3071 struct stream_interface *si;
3072 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003073
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003074 MAY_LJMP(check_args(L, 2, "settimeout"));
3075
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003076 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003077
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003078 /* convert the timeout to millis */
3079 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003080
Thierry Fournier17a921b2018-03-08 09:59:02 +01003081 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003082 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003083 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3084
Mark Lakes56cc1252018-03-27 09:48:06 +02003085 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003086 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003087
3088 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003089 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003090 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003091
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003092 /* Check if we run on the same thread than the xreator thread.
3093 * We cannot access to the socket if the thread is different.
3094 */
3095 if (socket->tid != tid)
3096 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3097
Mark Lakes56cc1252018-03-27 09:48:06 +02003098 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003099 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003100 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003101 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3102 WILL_LJMP(lua_error(L));
3103 return 0;
3104 }
3105 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
3106 si = appctx->owner;
3107 s = si_strm(si);
3108
Cyril Bonté7bb63452018-08-17 23:51:02 +02003109 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003110 s->req.rto = tmout;
3111 s->req.wto = tmout;
3112 s->res.rto = tmout;
3113 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003114 s->req.rex = tick_add_ifset(now_ms, tmout);
3115 s->req.wex = tick_add_ifset(now_ms, tmout);
3116 s->res.rex = tick_add_ifset(now_ms, tmout);
3117 s->res.wex = tick_add_ifset(now_ms, tmout);
3118
3119 s->task->expire = tick_add_ifset(now_ms, tmout);
3120 task_queue(s->task);
3121
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003122 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003123
Thierry Fourniere9636f12018-03-08 09:54:32 +01003124 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003125 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003126}
3127
3128__LJMP static int hlua_socket_new(lua_State *L)
3129{
3130 struct hlua_socket *socket;
3131 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02003132 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003133 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003134
3135 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003136 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003137 hlua_pusherror(L, "socket: full stack");
3138 goto out_fail_conf;
3139 }
3140
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003141 /* Create the object: obj[0] = userdata. */
3142 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003143 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003144 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003145 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003146 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003147
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003148 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003149 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003150 hlua_pusherror(L, "socket: uninitialized pools.");
3151 goto out_fail_conf;
3152 }
3153
Willy Tarreau87b09662015-04-03 00:22:06 +02003154 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003155 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3156 lua_setmetatable(L, -2);
3157
Willy Tarreaud420a972015-04-06 00:39:18 +02003158 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01003159 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003160 if (!appctx) {
3161 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02003162 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003163 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003164
Thierry FOURNIER18d09902016-12-16 09:25:38 +01003165 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02003166 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01003167 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
3168 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003169
Willy Tarreaud420a972015-04-06 00:39:18 +02003170 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01003171 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02003172 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003173 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02003174 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003175 }
3176
Christopher Faulet26256f82020-09-14 11:40:13 +02003177 strm = stream_new(sess, &appctx->obj_type, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003178 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003179 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02003180 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003181 }
3182
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003183 /* Initialise cross reference between stream and Lua socket object. */
3184 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003185
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003186 /* Configure "right" stream interface. this "si" is used to connect
3187 * and retrieve data from the server. The connection is initialized
3188 * with the "struct server".
3189 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003190 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003191
3192 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02003193 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003194 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003195
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003196 return 1;
3197
Willy Tarreaud420a972015-04-06 00:39:18 +02003198 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02003199 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02003200 out_fail_sess:
3201 appctx_free(appctx);
3202 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003203 WILL_LJMP(lua_error(L));
3204 return 0;
3205}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003206
3207/*
3208 *
3209 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003210 * Class Channel
3211 *
3212 *
3213 */
3214
3215/* Returns the struct hlua_channel join to the class channel in the
3216 * stack entry "ud" or throws an argument error.
3217 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003218__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003219{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003220 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003221}
3222
Willy Tarreau47860ed2015-03-10 14:07:50 +01003223/* Pushes the channel onto the top of the stack. If the stask does not have a
3224 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003225 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003226static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003227{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003228 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003229 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003230 return 0;
3231
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003232 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003233 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003234 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003235
3236 /* Pop a class sesison metatable and affect it to the userdata. */
3237 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3238 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003239 return 1;
3240}
3241
3242/* Duplicate all the data present in the input channel and put it
3243 * in a string LUA variables. Returns -1 and push a nil value in
3244 * the stack if the channel is closed and all the data are consumed,
3245 * returns 0 if no data are available, otherwise it returns the length
Ilya Shipitsind4259502020-04-08 01:07:56 +05003246 * of the built string.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003247 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003248static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003249{
3250 char *blk1;
3251 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003252 size_t len1;
3253 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003254 int ret;
3255 luaL_Buffer b;
3256
Willy Tarreau06d80a92017-10-19 14:32:15 +02003257 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Christopher Faulet055310f2021-08-05 11:58:37 +02003258 if (unlikely(ret <= 0)) {
3259 if (ret < 0 || HLUA_CANT_YIELD(hlua_gethlua(L))) {
3260 lua_pushnil(L);
3261 return -1;
3262 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003263 return 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003264 }
3265
3266 luaL_buffinit(L, &b);
3267 luaL_addlstring(&b, blk1, len1);
3268 if (unlikely(ret == 2))
3269 luaL_addlstring(&b, blk2, len2);
3270 luaL_pushresult(&b);
3271
3272 if (unlikely(ret == 2))
3273 return len1 + len2;
3274 return len1;
3275}
3276
3277/* "_hlua_channel_dup" wrapper. If no data are available, it returns
3278 * a yield. This function keep the data in the buffer.
3279 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003280__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003281{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003282 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003283
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003284 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3285
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003286 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003287 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003288 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003289 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003290
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003291 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02003292 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003293 return 1;
3294}
3295
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003296/* Check arguments for the function "hlua_channel_dup_yield". */
3297__LJMP static int hlua_channel_dup(lua_State *L)
3298{
3299 MAY_LJMP(check_args(L, 1, "dup"));
3300 MAY_LJMP(hlua_checkchannel(L, 1));
3301 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
3302}
3303
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003304/* "_hlua_channel_dup" wrapper. If no data are available, it returns
3305 * a yield. This function consumes the data in the buffer. It returns
3306 * a string containing the data or a nil pointer if no data are available
3307 * and the channel is closed.
3308 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003309__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003310{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003311 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003312 int ret;
3313
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003314 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003315
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003316 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003317 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003318 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003319 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003320
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003321 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003322 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02003323 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003324
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003325 if (unlikely(ret == -1))
3326 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003327
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003328 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003329 return 1;
3330}
3331
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003332/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003333__LJMP static int hlua_channel_get(lua_State *L)
3334{
3335 MAY_LJMP(check_args(L, 1, "get"));
3336 MAY_LJMP(hlua_checkchannel(L, 1));
3337 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
3338}
3339
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003340/* This functions consumes and returns one line. If the channel is closed,
3341 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003342 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003343 * value.
3344 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003345__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003346{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003347 char *blk1;
3348 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003349 size_t len1;
3350 size_t len2;
3351 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01003352 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003353 int ret;
3354 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003355
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003356 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3357
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003358 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003359 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003360 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003361 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003362
Willy Tarreau06d80a92017-10-19 14:32:15 +02003363 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Christopher Faulet055310f2021-08-05 11:58:37 +02003364 if (ret == 0) {
3365 if (HLUA_CANT_YIELD(hlua_gethlua(L))) {
3366 _hlua_channel_dup(chn, L);
3367 return 1;
3368 }
Willy Tarreau9635e032018-10-16 17:52:55 +02003369 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet055310f2021-08-05 11:58:37 +02003370 }
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003371
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003372 if (ret == -1) {
3373 lua_pushnil(L);
3374 return 1;
3375 }
3376
3377 luaL_buffinit(L, &b);
3378 luaL_addlstring(&b, blk1, len1);
3379 len = len1;
3380 if (unlikely(ret == 2)) {
3381 luaL_addlstring(&b, blk2, len2);
3382 len += len2;
3383 }
3384 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003385 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003386 return 1;
3387}
3388
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003389/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003390__LJMP static int hlua_channel_getline(lua_State *L)
3391{
3392 MAY_LJMP(check_args(L, 1, "getline"));
3393 MAY_LJMP(hlua_checkchannel(L, 1));
3394 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3395}
3396
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003397/* This function takes a string as argument, and append it at the input side of
3398 * channel. If data cannot be copied, because there is not enough space to do so
3399 * or because the channel is closed, it returns -1. Otherwise, it returns the
3400 * amount of data written (the string length). This function does not yield.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003401 */
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003402__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003403{
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003404 struct channel *chn;
3405 const char *str;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003406 size_t len;
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003407
3408 MAY_LJMP(check_args(L, 2, "append"));
3409 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3410 str = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003411
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003412 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003413 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003414 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003415 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003416
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003417 if (len > c_room(chn) || ci_putblk(chn, str, len) < 0)
3418 lua_pushinteger(L, -1);
3419 else
3420 lua_pushinteger(L, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003421 return 1;
3422}
3423
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003424/* The function replaces input data from the channel by the string passed as
3425 * argument. Before clearing the buffer, we take care the copy will be
3426 * possible. It returns the amount of data written (the string length) on
3427 * success or -1 if the copy is not performed. This function does not yield.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003428 */
3429__LJMP static int hlua_channel_set(lua_State *L)
3430{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003431 struct channel *chn;
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003432 const char *str;
3433 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003434
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003435 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003436 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003437 str = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003438
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003439 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003440 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003441 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003442 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003443
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003444 /* Be sure we can copied the string once input data will be removed. */
3445 if (len > ci_data(chn) || channel_input_closed(chn))
3446 lua_pushinteger(L, -1);
3447 else {
3448 b_set_data(&chn->buf, co_data(chn));
3449 if (ci_putblk(chn, str, len) < 0)
3450 lua_pushinteger(L, -1);
3451 else
3452 lua_pushinteger(L, len);
3453 }
3454 return -1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003455}
3456
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003457/* Append data in the output side of the buffer. This data is immediately
3458 * sent. The function returns the amount of data written. If the buffer
3459 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003460 * if the channel is closed.
3461 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003462__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003463{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003464 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003465 size_t len;
3466 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3467 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3468 int max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003469 struct hlua *hlua;
3470
3471 /* Get hlua struct, or NULL if we execute from main lua state */
3472 hlua = hlua_gethlua(L);
3473 if (!hlua) {
3474 lua_pushnil(L);
3475 return 1;
3476 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003477
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003478 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003479 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003480 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003481 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003482
Willy Tarreau47860ed2015-03-10 14:07:50 +01003483 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003484 lua_pushinteger(L, -1);
3485 return 1;
3486 }
3487
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003488 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003489 * the request buffer if its not required.
3490 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003491 if (chn->buf.size == 0) {
Christopher Faulet055310f2021-08-05 11:58:37 +02003492 if (HLUA_CANT_YIELD(hlua_gethlua(L)))
3493 return 1;
Willy Tarreau4b962a42018-11-15 11:03:21 +01003494 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003495 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003496 }
3497
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003498 /* The written data will be immediately sent, so we can check
3499 * the available space without taking in account the reserve.
3500 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003501 * data, because the buffer will be flushed.
3502 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003503 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003504
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003505 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003506 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003507 * we return the amount of copied data.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003508 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003509 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003510 return 1;
3511
3512 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003513 if (max > len - l)
3514 max = len - l;
3515
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003516 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003517 * detects a non contiguous buffer and realign it.
3518 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003519 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003520 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003521
3522 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003523 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003524
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003525 /* buffer replace considers that the input part is filled.
3526 * so, I must forward these new data in the output part.
3527 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003528 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003529
3530 l += max;
3531 lua_pop(L, 1);
3532 lua_pushinteger(L, l);
3533
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003534 if (l < len) {
Christopher Faulet055310f2021-08-05 11:58:37 +02003535 /* If there is no space available, and the output buffer is empty.
3536 * in this case, we cannot add more data, so we cannot yield,
3537 * we return the amount of copied data.
3538 */
3539 max = b_room(&chn->buf);
3540 if ((max == 0 && co_data(chn) == 0) || HLUA_CANT_YIELD(hlua_gethlua(L)))
3541 return 1;
3542
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003543 /* If we are waiting for space in the response buffer, we
3544 * must set the flag WAKERESWR. This flag required the task
3545 * wake up if any activity is detected on the response buffer.
3546 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003547 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003548 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003549 else
3550 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003551 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003552 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003553
3554 return 1;
3555}
3556
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003557/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003558 * yield the LUA process, and resume it without checking the
3559 * input arguments.
3560 */
3561__LJMP static int hlua_channel_send(lua_State *L)
3562{
3563 MAY_LJMP(check_args(L, 2, "send"));
3564 lua_pushinteger(L, 0);
3565
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003566 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003567}
3568
3569/* This function forward and amount of butes. The data pass from
3570 * the input side of the buffer to the output side, and can be
3571 * forwarded. This function never fails.
3572 *
3573 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003574 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003575 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003576__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003577{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003578 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003579 int len;
3580 int l;
3581 int max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003582 struct hlua *hlua;
3583
3584 /* Get hlua struct, or NULL if we execute from main lua state */
3585 hlua = hlua_gethlua(L);
3586 if (!hlua)
3587 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003588
3589 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003590
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003591 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003592 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003593 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003594 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003595
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003596 len = MAY_LJMP(luaL_checkinteger(L, 2));
3597 l = MAY_LJMP(luaL_checkinteger(L, -1));
3598
3599 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003600 if (max > ci_data(chn))
3601 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003602 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003603 l += max;
3604
3605 lua_pop(L, 1);
3606 lua_pushinteger(L, l);
3607
3608 /* Check if it miss bytes to forward. */
3609 if (l < len) {
3610 /* The the input channel or the output channel are closed, we
3611 * must return the amount of data forwarded.
3612 */
Christopher Faulet055310f2021-08-05 11:58:37 +02003613 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003614 return 1;
3615
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003616 /* If we are waiting for space data in the response buffer, we
3617 * must set the flag WAKERESWR. This flag required the task
3618 * wake up if any activity is detected on the response buffer.
3619 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003620 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003621 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003622 else
3623 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003624
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003625 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003626 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003627 }
3628
3629 return 1;
3630}
3631
3632/* Just check the input and prepare the stack for the previous
3633 * function "hlua_channel_forward_yield"
3634 */
3635__LJMP static int hlua_channel_forward(lua_State *L)
3636{
3637 MAY_LJMP(check_args(L, 2, "forward"));
3638 MAY_LJMP(hlua_checkchannel(L, 1));
3639 MAY_LJMP(luaL_checkinteger(L, 2));
3640
3641 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003642 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003643}
3644
3645/* Just returns the number of bytes available in the input
3646 * side of the buffer. This function never fails.
3647 */
3648__LJMP static int hlua_channel_get_in_len(lua_State *L)
3649{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003650 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003651
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003652 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003653 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003654 if (IS_HTX_STRM(chn_strm(chn))) {
3655 struct htx *htx = htxbuf(&chn->buf);
3656 lua_pushinteger(L, htx->data - co_data(chn));
3657 }
3658 else
3659 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003660 return 1;
3661}
3662
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003663/* Returns true if the channel is full. */
3664__LJMP static int hlua_channel_is_full(lua_State *L)
3665{
3666 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003667
3668 MAY_LJMP(check_args(L, 1, "is_full"));
3669 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003670 /* ignore the reserve, we are not on a producer side (ie in an
3671 * applet).
3672 */
3673 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003674 return 1;
3675}
3676
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003677/* Returns true if the channel is the response channel. */
3678__LJMP static int hlua_channel_is_resp(lua_State *L)
3679{
3680 struct channel *chn;
3681
3682 MAY_LJMP(check_args(L, 1, "is_resp"));
3683 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3684
3685 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3686 return 1;
3687}
3688
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003689/* Just returns the number of bytes available in the output
3690 * side of the buffer. This function never fails.
3691 */
3692__LJMP static int hlua_channel_get_out_len(lua_State *L)
3693{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003694 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003695
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003696 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003697 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003698 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003699 return 1;
3700}
3701
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003702/*
3703 *
3704 *
3705 * Class Fetches
3706 *
3707 *
3708 */
3709
3710/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003711 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003712 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003713__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003714{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003715 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003716}
3717
3718/* This function creates and push in the stack a fetch object according
3719 * with a current TXN.
3720 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003721static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003722{
Willy Tarreau7073c472015-04-06 11:15:40 +02003723 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003724
3725 /* Check stack size. */
3726 if (!lua_checkstack(L, 3))
3727 return 0;
3728
3729 /* Create the object: obj[0] = userdata.
3730 * Note that the base of the Fetches object is the
3731 * transaction object.
3732 */
3733 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003734 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003735 lua_rawseti(L, -2, 0);
3736
Willy Tarreau7073c472015-04-06 11:15:40 +02003737 hsmp->s = txn->s;
3738 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003739 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003740 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003741
3742 /* Pop a class sesison metatable and affect it to the userdata. */
3743 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3744 lua_setmetatable(L, -2);
3745
3746 return 1;
3747}
3748
3749/* This function is an LUA binding. It is called with each sample-fetch.
3750 * It uses closure argument to store the associated sample-fetch. It
3751 * returns only one argument or throws an error. An error is thrown
3752 * only if an error is encountered during the argument parsing. If
3753 * the "sample-fetch" function fails, nil is returned.
3754 */
3755__LJMP static int hlua_run_sample_fetch(lua_State *L)
3756{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003757 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003758 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003759 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003760 int i;
3761 struct sample smp;
3762
3763 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003764 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003765
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003766 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003767 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003768
Thierry FOURNIERca988662015-12-20 18:43:03 +01003769 /* Check execution authorization. */
3770 if (f->use & SMP_USE_HTTP_ANY &&
3771 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3772 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3773 "is not available in Lua services", f->kw);
3774 WILL_LJMP(lua_error(L));
3775 }
3776
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003777 /* Get extra arguments. */
3778 for (i = 0; i < lua_gettop(L) - 1; i++) {
3779 if (i >= ARGM_NBARGS)
3780 break;
3781 hlua_lua2arg(L, i + 2, &args[i]);
3782 }
3783 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003784 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003785
3786 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003787 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003788
3789 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003790 if (f->val_args && !f->val_args(args, NULL)) {
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02003791 hlua_pushfstring_safe(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003792 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003793 }
3794
3795 /* Initialise the sample. */
3796 memset(&smp, 0, sizeof(smp));
3797
3798 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003799 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003800 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003801 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003802 lua_pushstring(L, "");
3803 else
3804 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003805 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003806 }
3807
3808 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003809 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003810 hlua_smp2lua_str(L, &smp);
3811 else
3812 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003813
3814 end:
3815 for (i = 0; args[i].type != ARGT_STOP; i++) {
3816 if (args[i].type == ARGT_STR)
3817 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003818 else if (args[i].type == ARGT_REG)
3819 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003820 }
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003821 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003822
3823 error:
3824 for (i = 0; args[i].type != ARGT_STOP; i++) {
3825 if (args[i].type == ARGT_STR)
3826 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003827 else if (args[i].type == ARGT_REG)
3828 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003829 }
3830 WILL_LJMP(lua_error(L));
3831 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003832}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003833
3834/*
3835 *
3836 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003837 * Class Converters
3838 *
3839 *
3840 */
3841
3842/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003843 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003844 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003845__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003846{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003847 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003848}
3849
3850/* This function creates and push in the stack a Converters object
3851 * according with a current TXN.
3852 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003853static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003854{
Willy Tarreau7073c472015-04-06 11:15:40 +02003855 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003856
3857 /* Check stack size. */
3858 if (!lua_checkstack(L, 3))
3859 return 0;
3860
3861 /* Create the object: obj[0] = userdata.
3862 * Note that the base of the Converters object is the
3863 * same than the TXN object.
3864 */
3865 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003866 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003867 lua_rawseti(L, -2, 0);
3868
Willy Tarreau7073c472015-04-06 11:15:40 +02003869 hsmp->s = txn->s;
3870 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003871 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003872 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003873
Willy Tarreau87b09662015-04-03 00:22:06 +02003874 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003875 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3876 lua_setmetatable(L, -2);
3877
3878 return 1;
3879}
3880
3881/* This function is an LUA binding. It is called with each converter.
3882 * It uses closure argument to store the associated converter. It
3883 * returns only one argument or throws an error. An error is thrown
3884 * only if an error is encountered during the argument parsing. If
3885 * the converter function function fails, nil is returned.
3886 */
3887__LJMP static int hlua_run_sample_conv(lua_State *L)
3888{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003889 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003890 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003891 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003892 int i;
3893 struct sample smp;
3894
3895 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003896 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003897
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003898 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003899 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003900
3901 /* Get extra arguments. */
3902 for (i = 0; i < lua_gettop(L) - 2; i++) {
3903 if (i >= ARGM_NBARGS)
3904 break;
3905 hlua_lua2arg(L, i + 3, &args[i]);
3906 }
3907 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003908 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003909
3910 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003911 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003912
3913 /* Run the special args checker. */
3914 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3915 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003916 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003917 }
3918
3919 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01003920 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003921 if (!hlua_lua2smp(L, 2, &smp)) {
3922 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003923 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003924 }
3925
Willy Tarreau1777ea62016-03-10 16:15:46 +01003926 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3927
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003928 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003929 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003930 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003931 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003932 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003933 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003934 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3935 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003936 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003937 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003938 }
3939
3940 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003941 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003942 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003943 lua_pushstring(L, "");
3944 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003945 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003946 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003947 }
3948
3949 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003950 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003951 hlua_smp2lua_str(L, &smp);
3952 else
3953 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003954 end:
3955 for (i = 0; args[i].type != ARGT_STOP; i++) {
3956 if (args[i].type == ARGT_STR)
3957 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003958 else if (args[i].type == ARGT_REG)
3959 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003960 }
Willy Tarreaua678b432015-08-28 10:14:59 +02003961 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003962
3963 error:
3964 for (i = 0; args[i].type != ARGT_STOP; i++) {
3965 if (args[i].type == ARGT_STR)
3966 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003967 else if (args[i].type == ARGT_REG)
3968 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003969 }
3970 WILL_LJMP(lua_error(L));
3971 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003972}
3973
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003974/*
3975 *
3976 *
3977 * Class AppletTCP
3978 *
3979 *
3980 */
3981
3982/* Returns a struct hlua_txn if the stack entry "ud" is
3983 * a class stream, otherwise it throws an error.
3984 */
3985__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3986{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003987 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003988}
3989
3990/* This function creates and push in the stack an Applet object
3991 * according with a current TXN.
3992 */
3993static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3994{
Willy Tarreau7e702d12021-04-28 17:59:21 +02003995 struct hlua_appctx *luactx;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003996 struct stream_interface *si = ctx->owner;
3997 struct stream *s = si_strm(si);
3998 struct proxy *p = s->be;
3999
4000 /* Check stack size. */
4001 if (!lua_checkstack(L, 3))
4002 return 0;
4003
4004 /* Create the object: obj[0] = userdata.
4005 * Note that the base of the Converters object is the
4006 * same than the TXN object.
4007 */
4008 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004009 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004010 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004011 luactx->appctx = ctx;
4012 luactx->htxn.s = s;
4013 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004014
4015 /* Create the "f" field that contains a list of fetches. */
4016 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004017 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004018 return 0;
4019 lua_settable(L, -3);
4020
4021 /* Create the "sf" field that contains a list of stringsafe fetches. */
4022 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004023 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004024 return 0;
4025 lua_settable(L, -3);
4026
4027 /* Create the "c" field that contains a list of converters. */
4028 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004029 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004030 return 0;
4031 lua_settable(L, -3);
4032
4033 /* Create the "sc" field that contains a list of stringsafe converters. */
4034 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004035 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004036 return 0;
4037 lua_settable(L, -3);
4038
4039 /* Pop a class stream metatable and affect it to the table. */
4040 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
4041 lua_setmetatable(L, -2);
4042
4043 return 1;
4044}
4045
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004046__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
4047{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004048 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004049 struct stream *s;
4050 const char *name;
4051 size_t len;
4052 struct sample smp;
4053
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004054 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4055 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004056
4057 /* It is useles to retrieve the stream, but this function
4058 * runs only in a stream context.
4059 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004060 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004061 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004062 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004063
4064 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004065 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004066 hlua_lua2smp(L, 3, &smp);
4067
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02004068 /* Store the sample in a variable. We don't need to dup the smp, vars API
4069 * already takes care of duplicating dynamic var data.
4070 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004071 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004072
4073 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4074 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4075 else
4076 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4077
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004078 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004079}
4080
4081__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4082{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004083 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004084 struct stream *s;
4085 const char *name;
4086 size_t len;
4087 struct sample smp;
4088
4089 MAY_LJMP(check_args(L, 2, "unset_var"));
4090
4091 /* It is useles to retrieve the stream, but this function
4092 * runs only in a stream context.
4093 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004094 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004095 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004096 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004097
4098 /* Unset the variable. */
4099 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004100 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4101 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004102}
4103
4104__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4105{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004106 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004107 struct stream *s;
4108 const char *name;
4109 size_t len;
4110 struct sample smp;
4111
4112 MAY_LJMP(check_args(L, 2, "get_var"));
4113
4114 /* It is useles to retrieve the stream, but this function
4115 * runs only in a stream context.
4116 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004117 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004118 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004119 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004120
4121 smp_set_owner(&smp, s->be, s->sess, s, 0);
4122 if (!vars_get_by_name(name, len, &smp)) {
4123 lua_pushnil(L);
4124 return 1;
4125 }
4126
4127 return hlua_smp2lua(L, &smp);
4128}
4129
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004130__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4131{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004132 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4133 struct stream *s = luactx->htxn.s;
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01004134 struct hlua *hlua = hlua_stream_ctx_get(s, luactx->appctx->ctx.hlua_apptcp.hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004135
4136 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01004137 if (!hlua)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004138 return 0;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004139
4140 MAY_LJMP(check_args(L, 2, "set_priv"));
4141
4142 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004143 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004144
4145 /* Get and store new value. */
4146 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4147 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4148
4149 return 0;
4150}
4151
4152__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4153{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004154 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4155 struct stream *s = luactx->htxn.s;
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01004156 struct hlua *hlua = hlua_stream_ctx_get(s, luactx->appctx->ctx.hlua_apptcp.hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004157
4158 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01004159 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004160 lua_pushnil(L);
4161 return 1;
4162 }
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004163
4164 /* Push configuration index in the stack. */
4165 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4166
4167 return 1;
4168}
4169
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004170/* If expected data not yet available, it returns a yield. This function
4171 * consumes the data in the buffer. It returns a string containing the
4172 * data. This string can be empty.
4173 */
4174__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4175{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004176 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4177 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004178 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004179 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004180 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004181 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004182 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004183
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004184 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004185 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004186
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004187 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004188 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004189 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004190 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004191 }
4192
4193 /* End of data: commit the total strings and return. */
4194 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004195 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004196 return 1;
4197 }
4198
4199 /* Ensure that the block 2 length is usable. */
4200 if (ret == 1)
4201 len2 = 0;
4202
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004203 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004204 luaL_addlstring(&luactx->b, blk1, len1);
4205 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004206
4207 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004208 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004209 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004210 return 1;
4211}
4212
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004213/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004214__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4215{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004216 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004217
4218 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004219 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004220
4221 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4222}
4223
4224/* If expected data not yet available, it returns a yield. This function
4225 * consumes the data in the buffer. It returns a string containing the
4226 * data. This string can be empty.
4227 */
4228__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4229{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004230 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4231 struct stream_interface *si = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004232 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004233 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004234 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004235 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004236 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004237 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004238
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004239 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004240 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004241
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004242 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004243 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004244 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004245 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004246 }
4247
4248 /* End of data: commit the total strings and return. */
4249 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004250 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004251 return 1;
4252 }
4253
4254 /* Ensure that the block 2 length is usable. */
4255 if (ret == 1)
4256 len2 = 0;
4257
4258 if (len == -1) {
4259
4260 /* If len == -1, catenate all the data avalaile and
4261 * yield because we want to get all the data until
4262 * the end of data stream.
4263 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004264 luaL_addlstring(&luactx->b, blk1, len1);
4265 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004266 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004267 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004268 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004269
4270 } else {
4271
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004272 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004273 if (len1 > len)
4274 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004275 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004276 len -= len1;
4277
4278 /* Copy the second block. */
4279 if (len2 > len)
4280 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004281 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004282 len -= len2;
4283
4284 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004285 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004286
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004287 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004288 if (len > 0) {
4289 lua_pushinteger(L, len);
4290 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004291 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004292 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004293 }
4294
4295 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004296 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004297 return 1;
4298 }
4299
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004300 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004301 hlua_pusherror(L, "Lua: internal error");
4302 WILL_LJMP(lua_error(L));
4303 return 0;
4304}
4305
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004306/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004307__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4308{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004309 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004310 int len = -1;
4311
4312 if (lua_gettop(L) > 2)
4313 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4314 if (lua_gettop(L) >= 2) {
4315 len = MAY_LJMP(luaL_checkinteger(L, 2));
4316 lua_pop(L, 1);
4317 }
4318
4319 /* Confirm or set the required length */
4320 lua_pushinteger(L, len);
4321
4322 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004323 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004324
4325 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4326}
4327
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004328/* Append data in the output side of the buffer. This data is immediately
4329 * sent. The function returns the amount of data written. If the buffer
4330 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004331 * if the channel is closed.
4332 */
4333__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4334{
4335 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004336 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004337 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4338 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004339 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004340 struct channel *chn = si_ic(si);
4341 int max;
4342
4343 /* Get the max amount of data which can write as input in the channel. */
4344 max = channel_recv_max(chn);
4345 if (max > (len - l))
4346 max = len - l;
4347
4348 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004349 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004350
4351 /* update counters. */
4352 l += max;
4353 lua_pop(L, 1);
4354 lua_pushinteger(L, l);
4355
4356 /* If some data is not send, declares the situation to the
4357 * applet, and returns a yield.
4358 */
4359 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004360 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004361 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004362 }
4363
4364 return 1;
4365}
4366
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004367/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004368 * yield the LUA process, and resume it without checking the
4369 * input arguments.
4370 */
4371__LJMP static int hlua_applet_tcp_send(lua_State *L)
4372{
4373 MAY_LJMP(check_args(L, 2, "send"));
4374 lua_pushinteger(L, 0);
4375
4376 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4377}
4378
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004379/*
4380 *
4381 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004382 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004383 *
4384 *
4385 */
4386
4387/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004388 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004389 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004390__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004391{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004392 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004393}
4394
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004395/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004396 * according with a current TXN.
4397 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004398static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004399{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004400 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004401 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004402 struct stream_interface *si = ctx->owner;
4403 struct stream *s = si_strm(si);
4404 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004405 struct htx *htx;
4406 struct htx_blk *blk;
4407 struct htx_sl *sl;
4408 struct ist path;
4409 unsigned long long len = 0;
4410 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004411
4412 /* Check stack size. */
4413 if (!lua_checkstack(L, 3))
4414 return 0;
4415
4416 /* Create the object: obj[0] = userdata.
4417 * Note that the base of the Converters object is the
4418 * same than the TXN object.
4419 */
4420 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004421 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004422 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004423 luactx->appctx = ctx;
4424 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4425 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4426 luactx->htxn.s = s;
4427 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004428
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004429 /* Create the "f" field that contains a list of fetches. */
4430 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004431 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004432 return 0;
4433 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004434
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004435 /* Create the "sf" field that contains a list of stringsafe fetches. */
4436 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004437 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004438 return 0;
4439 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004440
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004441 /* Create the "c" field that contains a list of converters. */
4442 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004443 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004444 return 0;
4445 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004446
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004447 /* Create the "sc" field that contains a list of stringsafe converters. */
4448 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004449 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004450 return 0;
4451 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004452
Christopher Fauleta2097962019-07-15 16:25:33 +02004453 htx = htxbuf(&s->req.buf);
4454 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004455 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004456 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004457
Christopher Fauleta2097962019-07-15 16:25:33 +02004458 /* Stores the request method. */
4459 lua_pushstring(L, "method");
4460 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4461 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004462
Christopher Fauleta2097962019-07-15 16:25:33 +02004463 /* Stores the http version. */
4464 lua_pushstring(L, "version");
4465 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4466 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004467
Christopher Fauleta2097962019-07-15 16:25:33 +02004468 /* creates an array of headers. hlua_http_get_headers() crates and push
4469 * the array on the top of the stack.
4470 */
4471 lua_pushstring(L, "headers");
4472 htxn.s = s;
4473 htxn.p = px;
4474 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004475 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004476 return 0;
4477 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004478
Christopher Fauleta2097962019-07-15 16:25:33 +02004479 path = http_get_path(htx_sl_req_uri(sl));
Tim Duesterhused526372020-03-05 17:56:33 +01004480 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004481 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004482
Christopher Fauleta2097962019-07-15 16:25:33 +02004483 p = path.ptr;
4484 end = path.ptr + path.len;
4485 q = p;
4486 while (q < end && *q != '?')
4487 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004488
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004489 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004490 lua_pushstring(L, "path");
4491 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004492 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004493
Christopher Fauleta2097962019-07-15 16:25:33 +02004494 /* Stores the query string. */
4495 lua_pushstring(L, "qs");
4496 if (*q == '?')
4497 q++;
4498 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004499 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004500 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004501
Christopher Fauleta2097962019-07-15 16:25:33 +02004502 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4503 struct htx_blk *blk = htx_get_blk(htx, pos);
4504 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004505
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004506 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004507 break;
4508 if (type == HTX_BLK_DATA)
4509 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004510 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004511 if (htx->extra != ULLONG_MAX)
4512 len += htx->extra;
4513
4514 /* Stores the request path. */
4515 lua_pushstring(L, "length");
4516 lua_pushinteger(L, len);
4517 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004518
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004519 /* Create an empty array of HTTP request headers. */
4520 lua_pushstring(L, "response");
4521 lua_newtable(L);
4522 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004523
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004524 /* Pop a class stream metatable and affect it to the table. */
4525 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4526 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004527
4528 return 1;
4529}
4530
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004531__LJMP static int hlua_applet_http_set_var(lua_State *L)
4532{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004533 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004534 struct stream *s;
4535 const char *name;
4536 size_t len;
4537 struct sample smp;
4538
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004539 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4540 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004541
4542 /* It is useles to retrieve the stream, but this function
4543 * runs only in a stream context.
4544 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004545 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004546 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004547 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004548
4549 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004550 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004551 hlua_lua2smp(L, 3, &smp);
4552
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02004553 /* Store the sample in a variable. We don't need to dup the smp, vars API
4554 * already takes care of duplicating dynamic var data.
4555 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004556 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004557
4558 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4559 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4560 else
4561 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4562
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004563 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004564}
4565
4566__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4567{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004568 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004569 struct stream *s;
4570 const char *name;
4571 size_t len;
4572 struct sample smp;
4573
4574 MAY_LJMP(check_args(L, 2, "unset_var"));
4575
4576 /* It is useles to retrieve the stream, but this function
4577 * runs only in a stream context.
4578 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004579 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004580 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004581 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004582
4583 /* Unset the variable. */
4584 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004585 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4586 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004587}
4588
4589__LJMP static int hlua_applet_http_get_var(lua_State *L)
4590{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004591 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004592 struct stream *s;
4593 const char *name;
4594 size_t len;
4595 struct sample smp;
4596
4597 MAY_LJMP(check_args(L, 2, "get_var"));
4598
4599 /* It is useles to retrieve the stream, but this function
4600 * runs only in a stream context.
4601 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004602 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004603 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004604 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004605
4606 smp_set_owner(&smp, s->be, s->sess, s, 0);
4607 if (!vars_get_by_name(name, len, &smp)) {
4608 lua_pushnil(L);
4609 return 1;
4610 }
4611
4612 return hlua_smp2lua(L, &smp);
4613}
4614
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004615__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4616{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004617 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4618 struct stream *s = luactx->htxn.s;
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01004619 struct hlua *hlua = hlua_stream_ctx_get(s, luactx->appctx->ctx.hlua_apphttp.hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004620
4621 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01004622 if (!hlua)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004623 return 0;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004624
4625 MAY_LJMP(check_args(L, 2, "set_priv"));
4626
4627 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004628 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004629
4630 /* Get and store new value. */
4631 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4632 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4633
4634 return 0;
4635}
4636
4637__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4638{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004639 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4640 struct stream *s = luactx->htxn.s;
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01004641 struct hlua *hlua = hlua_stream_ctx_get(s, luactx->appctx->ctx.hlua_apphttp.hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004642
4643 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01004644 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004645 lua_pushnil(L);
4646 return 1;
4647 }
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004648
4649 /* Push configuration index in the stack. */
4650 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4651
4652 return 1;
4653}
4654
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004655/* If expected data not yet available, it returns a yield. This function
4656 * consumes the data in the buffer. It returns a string containing the
4657 * data. This string can be empty.
4658 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004659__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004660{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004661 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4662 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004663 struct channel *req = si_oc(si);
4664 struct htx *htx;
4665 struct htx_blk *blk;
4666 size_t count;
4667 int stop = 0;
4668
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004669 htx = htx_from_buf(&req->buf);
4670 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004671 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004672
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004673 while (count && !stop && blk) {
4674 enum htx_blk_type type = htx_get_blk_type(blk);
4675 uint32_t sz = htx_get_blksz(blk);
4676 struct ist v;
4677 uint32_t vlen;
4678 char *nl;
4679
4680 vlen = sz;
4681 if (vlen > count) {
4682 if (type != HTX_BLK_DATA)
4683 break;
4684 vlen = count;
4685 }
4686
4687 switch (type) {
4688 case HTX_BLK_UNUSED:
4689 break;
4690
4691 case HTX_BLK_DATA:
4692 v = htx_get_blk_value(htx, blk);
4693 v.len = vlen;
4694 nl = istchr(v, '\n');
4695 if (nl != NULL) {
4696 stop = 1;
4697 vlen = nl - v.ptr + 1;
4698 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004699 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004700 break;
4701
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004702 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004703 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004704 stop = 1;
4705 break;
4706
4707 default:
4708 break;
4709 }
4710
4711 co_set_data(req, co_data(req) - vlen);
4712 count -= vlen;
4713 if (sz == vlen)
4714 blk = htx_remove_blk(htx, blk);
4715 else {
4716 htx_cut_data_blk(htx, blk, vlen);
4717 break;
4718 }
4719 }
4720
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004721 /* The message was fully consumed and no more data are expected
4722 * (EOM flag set).
4723 */
Christopher Fauleta5a25b12022-08-29 15:37:16 +02004724 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004725 stop = 1;
4726
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004727 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004728 if (!stop) {
4729 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004730 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004731 }
4732
4733 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004734 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004735 return 1;
4736}
4737
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004738
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004739/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004740__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004741{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004742 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004743
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004744 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004745 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004746
Christopher Fauleta2097962019-07-15 16:25:33 +02004747 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004748}
4749
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004750/* If expected data not yet available, it returns a yield. This function
4751 * consumes the data in the buffer. It returns a string containing the
4752 * data. This string can be empty.
4753 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004754__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004755{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004756 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4757 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004758 struct channel *req = si_oc(si);
4759 struct htx *htx;
4760 struct htx_blk *blk;
4761 size_t count;
4762 int len;
4763
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004764 htx = htx_from_buf(&req->buf);
4765 len = MAY_LJMP(luaL_checkinteger(L, 2));
4766 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004767 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004768 while (count && len && blk) {
4769 enum htx_blk_type type = htx_get_blk_type(blk);
4770 uint32_t sz = htx_get_blksz(blk);
4771 struct ist v;
4772 uint32_t vlen;
4773
4774 vlen = sz;
4775 if (len > 0 && vlen > len)
4776 vlen = len;
4777 if (vlen > count) {
4778 if (type != HTX_BLK_DATA)
4779 break;
4780 vlen = count;
4781 }
4782
4783 switch (type) {
4784 case HTX_BLK_UNUSED:
4785 break;
4786
4787 case HTX_BLK_DATA:
4788 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004789 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004790 break;
4791
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004792 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004793 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004794 len = 0;
4795 break;
4796
4797 default:
4798 break;
4799 }
4800
4801 co_set_data(req, co_data(req) - vlen);
4802 count -= vlen;
4803 if (len > 0)
4804 len -= vlen;
4805 if (sz == vlen)
4806 blk = htx_remove_blk(htx, blk);
4807 else {
4808 htx_cut_data_blk(htx, blk, vlen);
4809 break;
4810 }
4811 }
4812
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004813 /* The message was fully consumed and no more data are expected
4814 * (EOM flag set).
4815 */
Christopher Fauleta5a25b12022-08-29 15:37:16 +02004816 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004817 len = 0;
4818
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004819 htx_to_buf(htx, &req->buf);
4820
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004821 /* If we are no other data available, yield waiting for new data. */
4822 if (len) {
4823 if (len > 0) {
4824 lua_pushinteger(L, len);
4825 lua_replace(L, 2);
4826 }
4827 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004828 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004829 }
4830
4831 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004832 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004833 return 1;
4834}
4835
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004836/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004837__LJMP static int hlua_applet_http_recv(lua_State *L)
4838{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004839 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004840 int len = -1;
4841
4842 /* Check arguments. */
4843 if (lua_gettop(L) > 2)
4844 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4845 if (lua_gettop(L) >= 2) {
4846 len = MAY_LJMP(luaL_checkinteger(L, 2));
4847 lua_pop(L, 1);
4848 }
4849
Christopher Fauleta2097962019-07-15 16:25:33 +02004850 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004851
Christopher Fauleta2097962019-07-15 16:25:33 +02004852 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004853 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004854
Christopher Fauleta2097962019-07-15 16:25:33 +02004855 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004856}
4857
4858/* Append data in the output side of the buffer. This data is immediately
4859 * sent. The function returns the amount of data written. If the buffer
4860 * cannot contain the data, the function yields. The function returns -1
4861 * if the channel is closed.
4862 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004863__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004864{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004865 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4866 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004867 struct channel *res = si_ic(si);
4868 struct htx *htx = htx_from_buf(&res->buf);
4869 const char *data;
4870 size_t len;
4871 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4872 int max;
4873
Christopher Faulet9060fc02019-07-03 11:39:30 +02004874 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004875 if (!max)
4876 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004877
4878 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4879
4880 /* Get the max amount of data which can write as input in the channel. */
4881 if (max > (len - l))
4882 max = len - l;
4883
4884 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004885 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004886 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004887
4888 /* update counters. */
4889 l += max;
4890 lua_pop(L, 1);
4891 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004892
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004893 /* If some data is not send, declares the situation to the
4894 * applet, and returns a yield.
4895 */
4896 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004897 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004898 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004899 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004900 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004901 }
4902
Christopher Fauleta2097962019-07-15 16:25:33 +02004903 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004904 return 1;
4905}
4906
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004907/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004908 * yield the LUA process, and resume it without checking the
4909 * input arguments.
4910 */
4911__LJMP static int hlua_applet_http_send(lua_State *L)
4912{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004913 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004914
4915 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004916 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004917 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4918 WILL_LJMP(lua_error(L));
4919 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004920
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004921 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004922 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004923
Christopher Fauleta2097962019-07-15 16:25:33 +02004924 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004925}
4926
4927__LJMP static int hlua_applet_http_addheader(lua_State *L)
4928{
4929 const char *name;
4930 int ret;
4931
4932 MAY_LJMP(hlua_checkapplet_http(L, 1));
4933 name = MAY_LJMP(luaL_checkstring(L, 2));
4934 MAY_LJMP(luaL_checkstring(L, 3));
4935
4936 /* Push in the stack the "response" entry. */
4937 ret = lua_getfield(L, 1, "response");
4938 if (ret != LUA_TTABLE) {
4939 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4940 "is expected as an array. %s found", lua_typename(L, ret));
4941 WILL_LJMP(lua_error(L));
4942 }
4943
4944 /* check if the header is already registered if it is not
4945 * the case, register it.
4946 */
4947 ret = lua_getfield(L, -1, name);
4948 if (ret == LUA_TNIL) {
4949
4950 /* Entry not found. */
4951 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4952
4953 /* Insert the new header name in the array in the top of the stack.
4954 * It left the new array in the top of the stack.
4955 */
4956 lua_newtable(L);
4957 lua_pushvalue(L, 2);
4958 lua_pushvalue(L, -2);
4959 lua_settable(L, -4);
4960
4961 } else if (ret != LUA_TTABLE) {
4962
4963 /* corruption error. */
4964 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4965 "is expected as an array. %s found", name, lua_typename(L, ret));
4966 WILL_LJMP(lua_error(L));
4967 }
4968
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004969 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004970 * the header value as new entry.
4971 */
4972 lua_pushvalue(L, 3);
4973 ret = lua_rawlen(L, -2);
4974 lua_rawseti(L, -2, ret + 1);
4975 lua_pushboolean(L, 1);
4976 return 1;
4977}
4978
4979__LJMP static int hlua_applet_http_status(lua_State *L)
4980{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004981 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004982 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004983 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004984
4985 if (status < 100 || status > 599) {
4986 lua_pushboolean(L, 0);
4987 return 1;
4988 }
4989
Willy Tarreau7e702d12021-04-28 17:59:21 +02004990 luactx->appctx->ctx.hlua_apphttp.status = status;
4991 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004992 lua_pushboolean(L, 1);
4993 return 1;
4994}
4995
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004996
Christopher Fauleta2097962019-07-15 16:25:33 +02004997__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004998{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004999 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5000 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005001 struct channel *res = si_ic(si);
5002 struct htx *htx;
5003 struct htx_sl *sl;
5004 struct h1m h1m;
5005 const char *status, *reason;
5006 const char *name, *value;
5007 size_t nlen, vlen;
5008 unsigned int flags;
5009
5010 /* Send the message at once. */
5011 htx = htx_from_buf(&res->buf);
5012 h1m_init_res(&h1m);
5013
5014 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005015 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
5016 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005017 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02005018 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
5019 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005020 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5021 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
5022 }
5023 else {
5024 flags = HTX_SL_F_IS_RESP;
5025 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
5026 }
5027 if (!sl) {
5028 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005029 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005030 WILL_LJMP(lua_error(L));
5031 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02005032 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005033
5034 /* Get the array associated to the field "response" in the object AppletHTTP. */
5035 lua_pushvalue(L, 0);
5036 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5037 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005038 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005039 WILL_LJMP(lua_error(L));
5040 }
5041
5042 /* Browse the list of headers. */
5043 lua_pushnil(L);
5044 while(lua_next(L, -2) != 0) {
5045 /* We expect a string as -2. */
5046 if (lua_type(L, -2) != LUA_TSTRING) {
5047 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005048 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005049 lua_typename(L, lua_type(L, -2)));
5050 WILL_LJMP(lua_error(L));
5051 }
5052 name = lua_tolstring(L, -2, &nlen);
5053
5054 /* We expect an array as -1. */
5055 if (lua_type(L, -1) != LUA_TTABLE) {
5056 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 +02005057 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005058 name,
5059 lua_typename(L, lua_type(L, -1)));
5060 WILL_LJMP(lua_error(L));
5061 }
5062
5063 /* Browse the table who is on the top of the stack. */
5064 lua_pushnil(L);
5065 while(lua_next(L, -2) != 0) {
5066 int id;
5067
5068 /* We expect a number as -2. */
5069 if (lua_type(L, -2) != LUA_TNUMBER) {
5070 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 +02005071 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005072 name,
5073 lua_typename(L, lua_type(L, -2)));
5074 WILL_LJMP(lua_error(L));
5075 }
5076 id = lua_tointeger(L, -2);
5077
5078 /* We expect a string as -2. */
5079 if (lua_type(L, -1) != LUA_TSTRING) {
5080 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 +02005081 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005082 name, id,
5083 lua_typename(L, lua_type(L, -1)));
5084 WILL_LJMP(lua_error(L));
5085 }
5086 value = lua_tolstring(L, -1, &vlen);
5087
5088 /* Simple Protocol checks. */
5089 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01005090 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005091 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5092 struct ist v = ist2(value, vlen);
5093 int ret;
5094
5095 ret = h1_parse_cont_len_header(&h1m, &v);
5096 if (ret < 0) {
5097 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005098 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005099 name);
5100 WILL_LJMP(lua_error(L));
5101 }
5102 else if (ret == 0)
5103 goto next; /* Skip it */
5104 }
5105
5106 /* Add a new header */
5107 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5108 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005109 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005110 name);
5111 WILL_LJMP(lua_error(L));
5112 }
5113 next:
5114 /* Remove the array from the stack, and get next element with a remaining string. */
5115 lua_pop(L, 1);
5116 }
5117
5118 /* Remove the array from the stack, and get next element with a remaining string. */
5119 lua_pop(L, 1);
5120 }
5121
5122 if (h1m.flags & H1_MF_CHNK)
5123 h1m.flags &= ~H1_MF_CLEN;
5124 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5125 h1m.flags |= H1_MF_XFER_LEN;
5126
5127 /* Uset HTX start-line flags */
5128 if (h1m.flags & H1_MF_XFER_ENC)
5129 flags |= HTX_SL_F_XFER_ENC;
5130 if (h1m.flags & H1_MF_XFER_LEN) {
5131 flags |= HTX_SL_F_XFER_LEN;
5132 if (h1m.flags & H1_MF_CHNK)
5133 flags |= HTX_SL_F_CHNK;
5134 else if (h1m.flags & H1_MF_CLEN)
5135 flags |= HTX_SL_F_CLEN;
5136 if (h1m.body_len == 0)
5137 flags |= HTX_SL_F_BODYLESS;
5138 }
5139 sl->flags |= flags;
5140
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005141 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005142 * and the status code implies the presence of a message body, we must
5143 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005144 * for the keepalive compliance. If the applet announces a transfer-encoding
5145 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005146 */
5147 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005148 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5149 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5150 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005151 /* Add a new header */
5152 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5153 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5154 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005155 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005156 WILL_LJMP(lua_error(L));
5157 }
5158 }
5159
5160 /* Finalize headers. */
5161 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5162 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005163 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005164 WILL_LJMP(lua_error(L));
5165 }
5166
5167 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5168 b_reset(&res->buf);
5169 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5170 WILL_LJMP(lua_error(L));
5171 }
5172
5173 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005174 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005175
5176 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005177 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005178 return 0;
5179
5180}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005181/* We will build the status line and the headers of the HTTP response.
5182 * We will try send at once if its not possible, we give back the hand
5183 * waiting for more room.
5184 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005185__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005186{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005187 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5188 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005189 struct channel *res = si_ic(si);
5190
5191 if (co_data(res)) {
5192 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005193 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005194 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005195 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005196}
5197
5198
Christopher Fauleta2097962019-07-15 16:25:33 +02005199__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005200{
Christopher Fauleta2097962019-07-15 16:25:33 +02005201 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005202}
5203
Christopher Fauleta2097962019-07-15 16:25:33 +02005204/*
5205 *
5206 *
5207 * Class HTTP
5208 *
5209 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005210 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005211
5212/* Returns a struct hlua_txn if the stack entry "ud" is
5213 * a class stream, otherwise it throws an error.
5214 */
5215__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005216{
Christopher Fauleta2097962019-07-15 16:25:33 +02005217 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5218}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005219
Christopher Fauleta2097962019-07-15 16:25:33 +02005220/* This function creates and push in the stack a HTTP object
5221 * according with a current TXN.
5222 */
5223static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5224{
5225 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005226
Christopher Fauleta2097962019-07-15 16:25:33 +02005227 /* Check stack size. */
5228 if (!lua_checkstack(L, 3))
5229 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005230
Christopher Fauleta2097962019-07-15 16:25:33 +02005231 /* Create the object: obj[0] = userdata.
5232 * Note that the base of the Converters object is the
5233 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005234 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005235 lua_newtable(L);
5236 htxn = lua_newuserdata(L, sizeof(*htxn));
5237 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005238
5239 htxn->s = txn->s;
5240 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005241 htxn->dir = txn->dir;
5242 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005243
5244 /* Pop a class stream metatable and affect it to the table. */
5245 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5246 lua_setmetatable(L, -2);
5247
5248 return 1;
5249}
5250
5251/* This function creates ans returns an array of HTTP headers.
5252 * This function does not fails. It is used as wrapper with the
5253 * 2 following functions.
5254 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005255__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005256{
Christopher Fauleta2097962019-07-15 16:25:33 +02005257 struct htx *htx;
5258 int32_t pos;
5259
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005260 /* Create the table. */
5261 lua_newtable(L);
5262
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005263
Christopher Fauleta2097962019-07-15 16:25:33 +02005264 htx = htxbuf(&msg->chn->buf);
5265 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5266 struct htx_blk *blk = htx_get_blk(htx, pos);
5267 enum htx_blk_type type = htx_get_blk_type(blk);
5268 struct ist n, v;
5269 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005270
Christopher Fauleta2097962019-07-15 16:25:33 +02005271 if (type == HTX_BLK_HDR) {
5272 n = htx_get_blk_name(htx,blk);
5273 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005274 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005275 else if (type == HTX_BLK_EOH)
5276 break;
5277 else
5278 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005279
Christopher Fauleta2097962019-07-15 16:25:33 +02005280 /* Check for existing entry:
5281 * assume that the table is on the top of the stack, and
5282 * push the key in the stack, the function lua_gettable()
5283 * perform the lookup.
5284 */
5285 lua_pushlstring(L, n.ptr, n.len);
5286 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005287
Christopher Fauleta2097962019-07-15 16:25:33 +02005288 switch (lua_type(L, -1)) {
5289 case LUA_TNIL:
5290 /* Table not found, create it. */
5291 lua_pop(L, 1); /* remove the nil value. */
5292 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5293 lua_newtable(L); /* create and push empty table. */
5294 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5295 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5296 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005297 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005298
Christopher Fauleta2097962019-07-15 16:25:33 +02005299 case LUA_TTABLE:
5300 /* Entry found: push the value in the table. */
5301 len = lua_rawlen(L, -1);
5302 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5303 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5304 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5305 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005306
Christopher Fauleta2097962019-07-15 16:25:33 +02005307 default:
5308 /* Other cases are errors. */
5309 hlua_pusherror(L, "internal error during the parsing of headers.");
5310 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005311 }
5312 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005313 return 1;
5314}
5315
5316__LJMP static int hlua_http_req_get_headers(lua_State *L)
5317{
5318 struct hlua_txn *htxn;
5319
5320 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5321 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5322
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005323 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005324 WILL_LJMP(lua_error(L));
5325
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005326 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005327}
5328
5329__LJMP static int hlua_http_res_get_headers(lua_State *L)
5330{
5331 struct hlua_txn *htxn;
5332
5333 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5334 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5335
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005336 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005337 WILL_LJMP(lua_error(L));
5338
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005339 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005340}
5341
5342/* This function replace full header, or just a value in
5343 * the request or in the response. It is a wrapper fir the
5344 * 4 following functions.
5345 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005346__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005347{
5348 size_t name_len;
5349 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5350 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5351 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005352 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005353 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005354
Dragan Dosen26743032019-04-30 15:54:36 +02005355 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005356 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5357
Christopher Fauleta2097962019-07-15 16:25:33 +02005358 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005359 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005360 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005361 return 0;
5362}
5363
5364__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5365{
5366 struct hlua_txn *htxn;
5367
5368 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5369 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5370
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005371 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005372 WILL_LJMP(lua_error(L));
5373
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005374 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005375}
5376
5377__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5378{
5379 struct hlua_txn *htxn;
5380
5381 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5382 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5383
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005384 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005385 WILL_LJMP(lua_error(L));
5386
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005387 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005388}
5389
5390__LJMP static int hlua_http_req_rep_val(lua_State *L)
5391{
5392 struct hlua_txn *htxn;
5393
5394 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5395 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5396
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005397 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005398 WILL_LJMP(lua_error(L));
5399
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005400 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005401}
5402
5403__LJMP static int hlua_http_res_rep_val(lua_State *L)
5404{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005405 struct hlua_txn *htxn;
5406
5407 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5408 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5409
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005410 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005411 WILL_LJMP(lua_error(L));
5412
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005413 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005414}
5415
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005416/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005417 * It is a wrapper for the 2 following functions.
5418 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005419__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005420{
5421 size_t len;
5422 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005423 struct htx *htx = htxbuf(&msg->chn->buf);
5424 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005425
Christopher Fauleta2097962019-07-15 16:25:33 +02005426 ctx.blk = NULL;
5427 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5428 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005429 return 0;
5430}
5431
5432__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5433{
5434 struct hlua_txn *htxn;
5435
5436 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5437 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5438
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005439 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005440 WILL_LJMP(lua_error(L));
5441
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005442 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005443}
5444
5445__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5446{
5447 struct hlua_txn *htxn;
5448
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005449 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005450 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5451
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005452 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005453 WILL_LJMP(lua_error(L));
5454
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005455 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005456}
5457
5458/* This function adds an header. It is a wrapper used by
5459 * the 2 following functions.
5460 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005461__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005462{
5463 size_t name_len;
5464 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5465 size_t value_len;
5466 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005467 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005468
Christopher Fauleta2097962019-07-15 16:25:33 +02005469 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5470 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005471 return 0;
5472}
5473
5474__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5475{
5476 struct hlua_txn *htxn;
5477
5478 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5479 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5480
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005481 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005482 WILL_LJMP(lua_error(L));
5483
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005484 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005485}
5486
5487__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5488{
5489 struct hlua_txn *htxn;
5490
5491 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5492 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5493
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005494 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005495 WILL_LJMP(lua_error(L));
5496
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005497 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005498}
5499
5500static int hlua_http_req_set_hdr(lua_State *L)
5501{
5502 struct hlua_txn *htxn;
5503
5504 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5505 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5506
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005507 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005508 WILL_LJMP(lua_error(L));
5509
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005510 hlua_http_del_hdr(L, &htxn->s->txn->req);
5511 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005512}
5513
5514static int hlua_http_res_set_hdr(lua_State *L)
5515{
5516 struct hlua_txn *htxn;
5517
5518 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5519 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5520
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005521 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005522 WILL_LJMP(lua_error(L));
5523
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005524 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5525 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005526}
5527
5528/* This function set the method. */
5529static int hlua_http_req_set_meth(lua_State *L)
5530{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005531 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005532 size_t name_len;
5533 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005534
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005535 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005536 WILL_LJMP(lua_error(L));
5537
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005538 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005539 return 1;
5540}
5541
5542/* This function set the method. */
5543static int hlua_http_req_set_path(lua_State *L)
5544{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005545 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005546 size_t name_len;
5547 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005548
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005549 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005550 WILL_LJMP(lua_error(L));
5551
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005552 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005553 return 1;
5554}
5555
5556/* This function set the query-string. */
5557static int hlua_http_req_set_query(lua_State *L)
5558{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005559 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005560 size_t name_len;
5561 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005562
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005563 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005564 WILL_LJMP(lua_error(L));
5565
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005566 /* Check length. */
5567 if (name_len > trash.size - 1) {
5568 lua_pushboolean(L, 0);
5569 return 1;
5570 }
5571
5572 /* Add the mark question as prefix. */
5573 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005574 trash.area[trash.data++] = '?';
5575 memcpy(trash.area + trash.data, name, name_len);
5576 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005577
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005578 lua_pushboolean(L,
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005579 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005580 return 1;
5581}
5582
5583/* This function set the uri. */
5584static int hlua_http_req_set_uri(lua_State *L)
5585{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005586 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005587 size_t name_len;
5588 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005589
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005590 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005591 WILL_LJMP(lua_error(L));
5592
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005593 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005594 return 1;
5595}
5596
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005597/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005598static int hlua_http_res_set_status(lua_State *L)
5599{
5600 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5601 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Faulet96bff762019-12-17 13:46:18 +01005602 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5603 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005604
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005605 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005606 WILL_LJMP(lua_error(L));
5607
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005608 http_res_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005609 return 0;
5610}
5611
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005612/*
5613 *
5614 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005615 * Class TXN
5616 *
5617 *
5618 */
5619
5620/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005621 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005622 */
5623__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5624{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005625 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005626}
5627
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005628__LJMP static int hlua_set_var(lua_State *L)
5629{
5630 struct hlua_txn *htxn;
5631 const char *name;
5632 size_t len;
5633 struct sample smp;
5634
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005635 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5636 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005637
5638 /* It is useles to retrieve the stream, but this function
5639 * runs only in a stream context.
5640 */
5641 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5642 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5643
5644 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005645 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005646 hlua_lua2smp(L, 3, &smp);
5647
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02005648 /* Store the sample in a variable. We don't need to dup the smp, vars API
5649 * already takes care of duplicating dynamic var data.
5650 */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005651 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005652
5653 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5654 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5655 else
5656 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5657
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005658 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005659}
5660
Christopher Faulet85d79c92016-11-09 16:54:56 +01005661__LJMP static int hlua_unset_var(lua_State *L)
5662{
5663 struct hlua_txn *htxn;
5664 const char *name;
5665 size_t len;
5666 struct sample smp;
5667
5668 MAY_LJMP(check_args(L, 2, "unset_var"));
5669
5670 /* It is useles to retrieve the stream, but this function
5671 * runs only in a stream context.
5672 */
5673 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5674 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5675
5676 /* Unset the variable. */
5677 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005678 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5679 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01005680}
5681
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005682__LJMP static int hlua_get_var(lua_State *L)
5683{
5684 struct hlua_txn *htxn;
5685 const char *name;
5686 size_t len;
5687 struct sample smp;
5688
5689 MAY_LJMP(check_args(L, 2, "get_var"));
5690
5691 /* It is useles to retrieve the stream, but this function
5692 * runs only in a stream context.
5693 */
5694 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5695 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5696
Willy Tarreau7560dd42016-03-10 16:28:58 +01005697 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005698 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005699 lua_pushnil(L);
5700 return 1;
5701 }
5702
5703 return hlua_smp2lua(L, &smp);
5704}
5705
Willy Tarreau59551662015-03-10 14:23:13 +01005706__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005707{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005708 struct hlua *hlua;
5709
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005710 MAY_LJMP(check_args(L, 2, "set_priv"));
5711
Willy Tarreau87b09662015-04-03 00:22:06 +02005712 /* It is useles to retrieve the stream, but this function
5713 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005714 */
5715 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005716
5717 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005718 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005719 if (!hlua)
5720 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005721
5722 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005723 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005724
5725 /* Get and store new value. */
5726 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5727 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5728
5729 return 0;
5730}
5731
Willy Tarreau59551662015-03-10 14:23:13 +01005732__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005733{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005734 struct hlua *hlua;
5735
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005736 MAY_LJMP(check_args(L, 1, "get_priv"));
5737
Willy Tarreau87b09662015-04-03 00:22:06 +02005738 /* It is useles to retrieve the stream, but this function
5739 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005740 */
5741 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005742
5743 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005744 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005745 if (!hlua) {
5746 lua_pushnil(L);
5747 return 1;
5748 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005749
5750 /* Push configuration index in the stack. */
5751 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5752
5753 return 1;
5754}
5755
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005756/* Create stack entry containing a class TXN. This function
5757 * return 0 if the stack does not contains free slots,
5758 * otherwise it returns 1.
5759 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005760static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005761{
Willy Tarreaude491382015-04-06 11:04:28 +02005762 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005763
5764 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005765 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005766 return 0;
5767
5768 /* NOTE: The allocation never fails. The failure
5769 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005770 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005771 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005772 /* Create the object: obj[0] = userdata. */
5773 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005774 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005775 lua_rawseti(L, -2, 0);
5776
Willy Tarreaude491382015-04-06 11:04:28 +02005777 htxn->s = s;
5778 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005779 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005780 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005781
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005782 /* Create the "f" field that contains a list of fetches. */
5783 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005784 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005785 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005786 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005787
5788 /* Create the "sf" field that contains a list of stringsafe fetches. */
5789 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005790 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005791 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005792 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005793
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005794 /* Create the "c" field that contains a list of converters. */
5795 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005796 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005797 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005798 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005799
5800 /* Create the "sc" field that contains a list of stringsafe converters. */
5801 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005802 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005803 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005804 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005805
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005806 /* Create the "req" field that contains the request channel object. */
5807 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005808 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005809 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005810 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005811
5812 /* Create the "res" field that contains the response channel object. */
5813 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005814 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005815 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005816 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005817
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005818 /* Creates the HTTP object is the current proxy allows http. */
5819 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01005820 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02005821 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005822 return 0;
5823 }
5824 else
5825 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005826 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005827
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005828 /* Pop a class sesison metatable and affect it to the userdata. */
5829 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5830 lua_setmetatable(L, -2);
5831
5832 return 1;
5833}
5834
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005835__LJMP static int hlua_txn_deflog(lua_State *L)
5836{
5837 const char *msg;
5838 struct hlua_txn *htxn;
5839
5840 MAY_LJMP(check_args(L, 2, "deflog"));
5841 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5842 msg = MAY_LJMP(luaL_checkstring(L, 2));
5843
5844 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5845 return 0;
5846}
5847
5848__LJMP static int hlua_txn_log(lua_State *L)
5849{
5850 int level;
5851 const char *msg;
5852 struct hlua_txn *htxn;
5853
5854 MAY_LJMP(check_args(L, 3, "log"));
5855 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5856 level = MAY_LJMP(luaL_checkinteger(L, 2));
5857 msg = MAY_LJMP(luaL_checkstring(L, 3));
5858
5859 if (level < 0 || level >= NB_LOG_LEVELS)
5860 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5861
5862 hlua_sendlog(htxn->s->be, level, msg);
5863 return 0;
5864}
5865
5866__LJMP static int hlua_txn_log_debug(lua_State *L)
5867{
5868 const char *msg;
5869 struct hlua_txn *htxn;
5870
5871 MAY_LJMP(check_args(L, 2, "Debug"));
5872 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5873 msg = MAY_LJMP(luaL_checkstring(L, 2));
5874 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5875 return 0;
5876}
5877
5878__LJMP static int hlua_txn_log_info(lua_State *L)
5879{
5880 const char *msg;
5881 struct hlua_txn *htxn;
5882
5883 MAY_LJMP(check_args(L, 2, "Info"));
5884 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5885 msg = MAY_LJMP(luaL_checkstring(L, 2));
5886 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5887 return 0;
5888}
5889
5890__LJMP static int hlua_txn_log_warning(lua_State *L)
5891{
5892 const char *msg;
5893 struct hlua_txn *htxn;
5894
5895 MAY_LJMP(check_args(L, 2, "Warning"));
5896 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5897 msg = MAY_LJMP(luaL_checkstring(L, 2));
5898 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5899 return 0;
5900}
5901
5902__LJMP static int hlua_txn_log_alert(lua_State *L)
5903{
5904 const char *msg;
5905 struct hlua_txn *htxn;
5906
5907 MAY_LJMP(check_args(L, 2, "Alert"));
5908 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5909 msg = MAY_LJMP(luaL_checkstring(L, 2));
5910 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5911 return 0;
5912}
5913
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005914__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5915{
5916 struct hlua_txn *htxn;
5917 int ll;
5918
5919 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5920 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5921 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5922
Christopher Faulet8263e942024-02-29 15:41:17 +01005923 if (ll < -1 || ll > NB_LOG_LEVELS)
5924 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be one of the following value:"
5925 " core.silent(-1), core.emerg(0), core.alert(1), core.crit(2), core.error(3),"
5926 " core.warning(4), core.notice(5), core.info(6) or core.debug(7)"));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005927
Christopher Faulet8263e942024-02-29 15:41:17 +01005928 htxn->s->logs.level = (ll == -1) ? ll : ll + 1;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005929 return 0;
5930}
5931
5932__LJMP static int hlua_txn_set_tos(lua_State *L)
5933{
5934 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005935 int tos;
5936
5937 MAY_LJMP(check_args(L, 2, "set_tos"));
5938 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5939 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5940
Willy Tarreau1a18b542018-12-11 16:37:42 +01005941 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005942 return 0;
5943}
5944
5945__LJMP static int hlua_txn_set_mark(lua_State *L)
5946{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005947 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005948 int mark;
5949
5950 MAY_LJMP(check_args(L, 2, "set_mark"));
5951 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5952 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5953
Lukas Tribus579e3e32019-08-11 18:03:45 +02005954 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005955 return 0;
5956}
5957
Patrick Hemmer268a7072018-05-11 12:52:31 -04005958__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5959{
5960 struct hlua_txn *htxn;
5961
5962 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5963 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5964 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5965 return 0;
5966}
5967
5968__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5969{
5970 struct hlua_txn *htxn;
5971
5972 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5973 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5974 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5975 return 0;
5976}
5977
Christopher Faulet700d9e82020-01-31 12:21:52 +01005978/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005979 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01005980 * message and terminate the transaction. It returns 1 on success and 0 on
5981 * error. The Reply must be on top of the stack.
5982 */
5983__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
5984{
5985 struct htx *htx;
5986 struct htx_sl *sl;
5987 struct h1m h1m;
5988 const char *status, *reason, *body;
5989 size_t status_len, reason_len, body_len;
5990 int ret, code, flags;
5991
5992 code = 200;
5993 status = "200";
5994 status_len = 3;
5995 ret = lua_getfield(L, -1, "status");
5996 if (ret == LUA_TNUMBER) {
5997 code = lua_tointeger(L, -1);
5998 status = lua_tolstring(L, -1, &status_len);
5999 }
6000 lua_pop(L, 1);
6001
6002 reason = http_get_reason(code);
6003 reason_len = strlen(reason);
6004 ret = lua_getfield(L, -1, "reason");
6005 if (ret == LUA_TSTRING)
6006 reason = lua_tolstring(L, -1, &reason_len);
6007 lua_pop(L, 1);
6008
6009 body = NULL;
6010 body_len = 0;
6011 ret = lua_getfield(L, -1, "body");
6012 if (ret == LUA_TSTRING)
6013 body = lua_tolstring(L, -1, &body_len);
6014 lua_pop(L, 1);
6015
6016 /* Prepare the response before inserting the headers */
6017 h1m_init_res(&h1m);
6018 htx = htx_from_buf(&s->res.buf);
6019 channel_htx_truncate(&s->res, htx);
6020 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
6021 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
6022 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
6023 ist2(status, status_len), ist2(reason, reason_len));
6024 }
6025 else {
6026 flags = HTX_SL_F_IS_RESP;
6027 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
6028 ist2(status, status_len), ist2(reason, reason_len));
6029 }
6030 if (!sl)
6031 goto fail;
6032 sl->info.res.status = code;
6033
6034 /* Push in the stack the "headers" entry. */
6035 ret = lua_getfield(L, -1, "headers");
6036 if (ret != LUA_TTABLE)
6037 goto skip_headers;
6038
6039 lua_pushnil(L);
6040 while (lua_next(L, -2) != 0) {
6041 struct ist name, value;
6042 const char *n, *v;
6043 size_t nlen, vlen;
6044
6045 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
6046 /* Skip element if the key is not a string or if the value is not a table */
6047 goto next_hdr;
6048 }
6049
6050 n = lua_tolstring(L, -2, &nlen);
6051 name = ist2(n, nlen);
6052 if (isteqi(name, ist("content-length"))) {
6053 /* Always skip content-length header. It will be added
6054 * later with the correct len
6055 */
6056 goto next_hdr;
6057 }
6058
6059 /* Loop on header's values */
6060 lua_pushnil(L);
6061 while (lua_next(L, -2)) {
6062 if (!lua_isstring(L, -1)) {
6063 /* Skip the value if it is not a string */
6064 goto next_value;
6065 }
6066
6067 v = lua_tolstring(L, -1, &vlen);
6068 value = ist2(v, vlen);
6069
6070 if (isteqi(name, ist("transfer-encoding")))
6071 h1_parse_xfer_enc_header(&h1m, value);
6072 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
6073 goto fail;
6074
6075 next_value:
6076 lua_pop(L, 1);
6077 }
6078
6079 next_hdr:
6080 lua_pop(L, 1);
6081 }
6082 skip_headers:
6083 lua_pop(L, 1);
6084
6085 /* Update h1m flags: CLEN is set if CHNK is not present */
6086 if (!(h1m.flags & H1_MF_CHNK)) {
6087 const char *clen = ultoa(body_len);
6088
6089 h1m.flags |= H1_MF_CLEN;
6090 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
6091 goto fail;
6092 }
6093 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
6094 h1m.flags |= H1_MF_XFER_LEN;
6095
6096 /* Update HTX start-line flags */
6097 if (h1m.flags & H1_MF_XFER_ENC)
6098 flags |= HTX_SL_F_XFER_ENC;
6099 if (h1m.flags & H1_MF_XFER_LEN) {
6100 flags |= HTX_SL_F_XFER_LEN;
6101 if (h1m.flags & H1_MF_CHNK)
6102 flags |= HTX_SL_F_CHNK;
6103 else if (h1m.flags & H1_MF_CLEN)
6104 flags |= HTX_SL_F_CLEN;
6105 if (h1m.body_len == 0)
6106 flags |= HTX_SL_F_BODYLESS;
6107 }
6108 sl->flags |= flags;
6109
6110
6111 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01006112 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01006113 goto fail;
6114
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01006115 htx->flags |= HTX_FL_EOM;
6116
Christopher Faulet700d9e82020-01-31 12:21:52 +01006117 /* Now, forward the response and terminate the transaction */
6118 s->txn->status = code;
6119 htx_to_buf(htx, &s->res.buf);
6120 if (!http_forward_proxy_resp(s, 1))
6121 goto fail;
6122
6123 return 1;
6124
6125 fail:
6126 channel_htx_truncate(&s->res, htx);
6127 return 0;
6128}
6129
6130/* Terminate a transaction if called from a lua action. For TCP streams,
6131 * processing is just aborted. Nothing is returned to the client and all
6132 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
6133 * is forwarded to the client before terminating the transaction. On success,
6134 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
6135 * with ACT_RET_ERR code. If this function is not called from a lua action, it
6136 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006137 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006138__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006139{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006140 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01006141 struct stream *s;
6142 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006143
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006144 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006145
Christopher Faulet700d9e82020-01-31 12:21:52 +01006146 /* If the flags NOTERM is set, we cannot terminate the session, so we
6147 * just end the execution of the current lua code. */
6148 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006149 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006150
Christopher Faulet700d9e82020-01-31 12:21:52 +01006151 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006152 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01006153 struct channel *req = &s->req;
6154 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006155
Christopher Faulet700d9e82020-01-31 12:21:52 +01006156 channel_auto_read(req);
6157 channel_abort(req);
6158 channel_auto_close(req);
6159 channel_erase(req);
6160
6161 res->wex = tick_add_ifset(now_ms, res->wto);
6162 channel_auto_read(res);
6163 channel_auto_close(res);
6164 channel_shutr_now(res);
6165
6166 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
6167 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02006168 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006169
Christopher Faulet700d9e82020-01-31 12:21:52 +01006170 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
6171 /* No reply or invalid reply */
6172 s->txn->status = 0;
6173 http_reply_and_close(s, 0, NULL);
6174 }
6175 else {
6176 /* Remove extra args to have the reply on top of the stack */
6177 if (lua_gettop(L) > 2)
6178 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006179
Christopher Faulet700d9e82020-01-31 12:21:52 +01006180 if (!hlua_txn_forward_reply(L, s)) {
6181 if (!(s->flags & SF_ERR_MASK))
6182 s->flags |= SF_ERR_PRXCOND;
6183 lua_pushinteger(L, ACT_RET_ERR);
6184 WILL_LJMP(hlua_done(L));
6185 return 0; /* Never reached */
6186 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02006187 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006188
Christopher Faulet700d9e82020-01-31 12:21:52 +01006189 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
6190 if (htxn->dir == SMP_OPT_DIR_REQ) {
6191 /* let's log the request time */
6192 s->logs.tv_request = now;
6193 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02006194 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01006195 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02006196
Christopher Faulet700d9e82020-01-31 12:21:52 +01006197 done:
6198 if (!(s->flags & SF_ERR_MASK))
6199 s->flags |= SF_ERR_LOCAL;
6200 if (!(s->flags & SF_FINST_MASK))
6201 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02006202
Christopher Faulet4ad73102020-03-05 11:07:31 +01006203 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006204 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006205 return 0;
6206}
6207
Christopher Faulet700d9e82020-01-31 12:21:52 +01006208/*
6209 *
6210 *
6211 * Class REPLY
6212 *
6213 *
6214 */
6215
6216/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
6217 * free slots, the function fails and returns 0;
6218 */
6219static int hlua_txn_reply_new(lua_State *L)
6220{
6221 struct hlua_txn *htxn;
6222 const char *reason, *body = NULL;
6223 int ret, status;
6224
6225 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006226 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01006227 hlua_pusherror(L, "txn object is not an HTTP transaction.");
6228 WILL_LJMP(lua_error(L));
6229 }
6230
6231 /* Default value */
6232 status = 200;
6233 reason = http_get_reason(status);
6234
6235 if (lua_istable(L, 2)) {
6236 /* load status and reason from the table argument at index 2 */
6237 ret = lua_getfield(L, 2, "status");
6238 if (ret == LUA_TNIL)
6239 goto reason;
6240 else if (ret != LUA_TNUMBER) {
6241 /* invalid status: ignore the reason */
6242 goto body;
6243 }
6244 status = lua_tointeger(L, -1);
6245
6246 reason:
6247 lua_pop(L, 1); /* restore the stack: remove status */
6248 ret = lua_getfield(L, 2, "reason");
6249 if (ret == LUA_TSTRING)
6250 reason = lua_tostring(L, -1);
6251
6252 body:
6253 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
6254 ret = lua_getfield(L, 2, "body");
6255 if (ret == LUA_TSTRING)
6256 body = lua_tostring(L, -1);
6257 lua_pop(L, 1); /* restore the stack: remove body */
6258 }
6259
6260 /* Create the Reply table */
6261 lua_newtable(L);
6262
6263 /* Add status element */
6264 lua_pushstring(L, "status");
6265 lua_pushinteger(L, status);
6266 lua_settable(L, -3);
6267
6268 /* Add reason element */
6269 reason = http_get_reason(status);
6270 lua_pushstring(L, "reason");
6271 lua_pushstring(L, reason);
6272 lua_settable(L, -3);
6273
6274 /* Add body element, nil if undefined */
6275 lua_pushstring(L, "body");
6276 if (body)
6277 lua_pushstring(L, body);
6278 else
6279 lua_pushnil(L);
6280 lua_settable(L, -3);
6281
6282 /* Add headers element */
6283 lua_pushstring(L, "headers");
6284 lua_newtable(L);
6285
6286 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
6287 if (lua_istable(L, 2)) {
6288 /* load headers from the table argument at index 2. If it is a table, copy it. */
6289 ret = lua_getfield(L, 2, "headers");
6290 if (ret == LUA_TTABLE) {
6291 /* stack: [ ... <headers:table>, <table> ] */
6292 lua_pushnil(L);
6293 while (lua_next(L, -2) != 0) {
6294 /* stack: [ ... <headers:table>, <table>, k, v] */
6295 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
6296 /* invalid value type, skip it */
6297 lua_pop(L, 1);
6298 continue;
6299 }
6300
6301
6302 /* Duplicate the key and swap it with the value. */
6303 lua_pushvalue(L, -2);
6304 lua_insert(L, -2);
6305 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
6306
6307 lua_newtable(L);
6308 lua_insert(L, -2);
6309 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
6310
6311 if (lua_isstring(L, -1)) {
6312 /* push the value in the inner table */
6313 lua_rawseti(L, -2, 1);
6314 }
6315 else { /* table */
6316 lua_pushnil(L);
6317 while (lua_next(L, -2) != 0) {
6318 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
6319 if (!lua_isstring(L, -1)) {
6320 /* invalid value type, skip it*/
6321 lua_pop(L, 1);
6322 continue;
6323 }
6324 /* push the value in the inner table */
6325 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
6326 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
6327 }
6328 lua_pop(L, 1);
6329 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
6330 }
6331
6332 /* push (k,v) on the stack in the headers table:
6333 * stack: [ ... <headers:table>, <table>, k, k, v ]
6334 */
6335 lua_settable(L, -5);
6336 /* stack: [ ... <headers:table>, <table>, k ] */
6337 }
6338 }
6339 lua_pop(L, 1);
6340 }
6341 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
6342 lua_settable(L, -3);
6343 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
6344
6345 /* Pop a class sesison metatable and affect it to the userdata. */
6346 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
6347 lua_setmetatable(L, -2);
6348 return 1;
6349}
6350
6351/* Set the reply status code, and optionally the reason. If no reason is
6352 * provided, the default one corresponding to the status code is used.
6353 */
6354__LJMP static int hlua_txn_reply_set_status(lua_State *L)
6355{
6356 int status = MAY_LJMP(luaL_checkinteger(L, 2));
6357 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6358
6359 /* First argument (self) must be a table */
6360 luaL_checktype(L, 1, LUA_TTABLE);
6361
6362 if (status < 100 || status > 599) {
6363 lua_pushboolean(L, 0);
6364 return 1;
6365 }
6366 if (!reason)
6367 reason = http_get_reason(status);
6368
6369 lua_pushinteger(L, status);
6370 lua_setfield(L, 1, "status");
6371
6372 lua_pushstring(L, reason);
6373 lua_setfield(L, 1, "reason");
6374
6375 lua_pushboolean(L, 1);
6376 return 1;
6377}
6378
6379/* Add a header into the reply object. Each header name is associated to an
6380 * array of values in the "headers" table. If the header name is not found, a
6381 * new entry is created.
6382 */
6383__LJMP static int hlua_txn_reply_add_header(lua_State *L)
6384{
6385 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
6386 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
6387 int ret;
6388
6389 /* First argument (self) must be a table */
6390 luaL_checktype(L, 1, LUA_TTABLE);
6391
6392 /* Push in the stack the "headers" entry. */
6393 ret = lua_getfield(L, 1, "headers");
6394 if (ret != LUA_TTABLE) {
6395 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
6396 WILL_LJMP(lua_error(L));
6397 }
6398
6399 /* check if the header is already registered. If not, register it. */
6400 ret = lua_getfield(L, -1, name);
6401 if (ret == LUA_TNIL) {
6402 /* Entry not found. */
6403 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
6404
6405 /* Insert the new header name in the array in the top of the stack.
6406 * It left the new array in the top of the stack.
6407 */
6408 lua_newtable(L);
6409 lua_pushstring(L, name);
6410 lua_pushvalue(L, -2);
6411 lua_settable(L, -4);
6412 }
6413 else if (ret != LUA_TTABLE) {
6414 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
6415 WILL_LJMP(lua_error(L));
6416 }
6417
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07006418 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01006419 * the header value as new entry.
6420 */
6421 lua_pushstring(L, value);
6422 ret = lua_rawlen(L, -2);
6423 lua_rawseti(L, -2, ret + 1);
6424
6425 lua_pushboolean(L, 1);
6426 return 1;
6427}
6428
6429/* Remove all occurrences of a given header name. */
6430__LJMP static int hlua_txn_reply_del_header(lua_State *L)
6431{
6432 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
6433 int ret;
6434
6435 /* First argument (self) must be a table */
6436 luaL_checktype(L, 1, LUA_TTABLE);
6437
6438 /* Push in the stack the "headers" entry. */
6439 ret = lua_getfield(L, 1, "headers");
6440 if (ret != LUA_TTABLE) {
6441 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
6442 WILL_LJMP(lua_error(L));
6443 }
6444
6445 lua_pushstring(L, name);
6446 lua_pushnil(L);
6447 lua_settable(L, -3);
6448
6449 lua_pushboolean(L, 1);
6450 return 1;
6451}
6452
6453/* Set the reply's body. Overwrite any existing entry. */
6454__LJMP static int hlua_txn_reply_set_body(lua_State *L)
6455{
6456 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
6457
6458 /* First argument (self) must be a table */
6459 luaL_checktype(L, 1, LUA_TTABLE);
6460
6461 lua_pushstring(L, payload);
6462 lua_setfield(L, 1, "body");
6463
6464 lua_pushboolean(L, 1);
6465 return 1;
6466}
6467
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006468__LJMP static int hlua_log(lua_State *L)
6469{
6470 int level;
6471 const char *msg;
6472
6473 MAY_LJMP(check_args(L, 2, "log"));
6474 level = MAY_LJMP(luaL_checkinteger(L, 1));
6475 msg = MAY_LJMP(luaL_checkstring(L, 2));
6476
6477 if (level < 0 || level >= NB_LOG_LEVELS)
6478 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6479
6480 hlua_sendlog(NULL, level, msg);
6481 return 0;
6482}
6483
6484__LJMP static int hlua_log_debug(lua_State *L)
6485{
6486 const char *msg;
6487
6488 MAY_LJMP(check_args(L, 1, "debug"));
6489 msg = MAY_LJMP(luaL_checkstring(L, 1));
6490 hlua_sendlog(NULL, LOG_DEBUG, msg);
6491 return 0;
6492}
6493
6494__LJMP static int hlua_log_info(lua_State *L)
6495{
6496 const char *msg;
6497
6498 MAY_LJMP(check_args(L, 1, "info"));
6499 msg = MAY_LJMP(luaL_checkstring(L, 1));
6500 hlua_sendlog(NULL, LOG_INFO, msg);
6501 return 0;
6502}
6503
6504__LJMP static int hlua_log_warning(lua_State *L)
6505{
6506 const char *msg;
6507
6508 MAY_LJMP(check_args(L, 1, "warning"));
6509 msg = MAY_LJMP(luaL_checkstring(L, 1));
6510 hlua_sendlog(NULL, LOG_WARNING, msg);
6511 return 0;
6512}
6513
6514__LJMP static int hlua_log_alert(lua_State *L)
6515{
6516 const char *msg;
6517
6518 MAY_LJMP(check_args(L, 1, "alert"));
6519 msg = MAY_LJMP(luaL_checkstring(L, 1));
6520 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006521 return 0;
6522}
6523
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006524__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006525{
6526 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau9cc2e4c2021-09-30 16:12:31 +02006527 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02006528 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006529 return 0;
6530}
6531
6532__LJMP static int hlua_sleep(lua_State *L)
6533{
6534 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006535 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006536
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006537 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006538
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006539 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006540 wakeup_ms = tick_add(now_ms, delay);
6541 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006542
Willy Tarreau9635e032018-10-16 17:52:55 +02006543 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006544 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006545}
6546
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006547__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006548{
6549 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006550 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006551
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006552 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006553
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006554 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006555 wakeup_ms = tick_add(now_ms, delay);
6556 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006557
Willy Tarreau9635e032018-10-16 17:52:55 +02006558 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006559 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006560}
6561
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006562/* This functionis an LUA binding. it permits to give back
6563 * the hand at the HAProxy scheduler. It is used when the
6564 * LUA processing consumes a lot of time.
6565 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006566__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006567{
6568 return 0;
6569}
6570
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006571__LJMP static int hlua_yield(lua_State *L)
6572{
Willy Tarreau9635e032018-10-16 17:52:55 +02006573 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006574 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006575}
6576
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006577/* This function change the nice of the currently executed
6578 * task. It is used set low or high priority at the current
6579 * task.
6580 */
Willy Tarreau59551662015-03-10 14:23:13 +01006581__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006582{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006583 struct hlua *hlua;
6584 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006585
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006586 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006587 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006588
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006589 /* Get hlua struct, or NULL if we execute from main lua state */
6590 hlua = hlua_gethlua(L);
6591
6592 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006593 if (!hlua || !hlua->task)
6594 return 0;
6595
6596 if (nice < -1024)
6597 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006598 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006599 nice = 1024;
6600
6601 hlua->task->nice = nice;
6602 return 0;
6603}
6604
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006605/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006606 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6607 * return an E_AGAIN signal, the emmiter of this signal must set a
6608 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006609 *
6610 * Task wrapper are longjmp safe because the only one Lua code
6611 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006612 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01006613struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006614{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006615 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006616 enum hlua_exec status;
6617
Christopher Faulet5bc99722018-04-25 10:34:45 +02006618 if (task->thread_mask == MAX_THREADS_MASK)
6619 task_set_affinity(task, tid_bit);
6620
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006621 /* If it is the first call to the task, we must initialize the
6622 * execution timeouts.
6623 */
6624 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006625 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006626
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006627 /* Execute the Lua code. */
6628 status = hlua_ctx_resume(hlua, 1);
6629
6630 switch (status) {
6631 /* finished or yield */
6632 case HLUA_E_OK:
6633 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006634 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006635 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006636 break;
6637
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006638 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006639 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006640 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006641 break;
6642
6643 /* finished with error. */
6644 case HLUA_E_ERRMSG:
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01006645 hlua_lock(hlua);
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01006646 SEND_ERR(NULL, "Lua task: %s.\n", hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006647 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006648 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006649 task = NULL;
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01006650 hlua_unlock(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006651 break;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006652 case HLUA_E_ERR:
6653 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006654 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006655 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006656 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006657 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006658 break;
6659 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006660 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006661}
6662
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006663/* This function is an LUA binding that register LUA function to be
6664 * executed after the HAProxy configuration parsing and before the
6665 * HAProxy scheduler starts. This function expect only one LUA
6666 * argument that is a function. This function returns nothing, but
6667 * throws if an error is encountered.
6668 */
6669__LJMP static int hlua_register_init(lua_State *L)
6670{
6671 struct hlua_init_function *init;
6672 int ref;
6673
6674 MAY_LJMP(check_args(L, 1, "register_init"));
6675
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01006676 if (hlua_gethlua(L)) {
6677 /* runtime processing */
6678 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
6679 }
6680
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006681 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6682
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006683 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006684 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006685 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006686
6687 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02006688 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006689 return 0;
6690}
6691
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006692/* This functio is an LUA binding. It permits to register a task
6693 * executed in parallel of the main HAroxy activity. The task is
6694 * created and it is set in the HAProxy scheduler. It can be called
6695 * from the "init" section, "post init" or during the runtime.
6696 *
6697 * Lua prototype:
6698 *
6699 * <none> core.register_task(<function>)
6700 */
6701static int hlua_register_task(lua_State *L)
6702{
Christopher Faulet5294ec02021-04-12 12:24:47 +02006703 struct hlua *hlua = NULL;
6704 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006705 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01006706 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006707
6708 MAY_LJMP(check_args(L, 1, "register_task"));
6709
6710 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6711
Thierry Fournier75fc0292020-11-28 13:18:56 +01006712 /* Get the reference state. If the reference is NULL, L is the master
6713 * state, otherwise hlua->T is.
6714 */
6715 hlua = hlua_gethlua(L);
6716 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01006717 /* we are in runtime processing */
6718 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01006719 else
Thierry Fournier021d9862020-11-28 23:42:03 +01006720 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01006721 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01006722
Willy Tarreaubafbe012017-11-24 17:34:44 +01006723 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006724 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02006725 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01006726 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006727
Thierry Fournier59f11be2020-11-29 00:37:41 +01006728 /* We are in the common lua state, execute the task anywhere,
6729 * otherwise, inherit the current thread identifier
6730 */
6731 if (state_id == 0)
6732 task = task_new(MAX_THREADS_MASK);
6733 else
6734 task = task_new(tid_bit);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006735 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02006736 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02006737
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006738 task->context = hlua;
6739 task->process = hlua_process_task;
6740
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01006741 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02006742 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006743
6744 /* Restore the function in the stack. */
6745 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
Aurelien DARRAGONb6aade32023-03-13 14:09:21 +01006746 /* function ref not needed anymore since it was pushed to the substack */
6747 hlua_unref(L, ref);
6748
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006749 hlua->nargs = 0;
6750
6751 /* Schedule task. */
Willy Tarreau790810f2021-09-30 16:17:37 +02006752 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006753
6754 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02006755
6756 alloc_error:
6757 task_destroy(task);
6758 hlua_ctx_destroy(hlua);
6759 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6760 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006761}
6762
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006763/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6764 * doesn't allow "yield" functions because the HAProxy engine cannot
6765 * resume converters.
6766 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006767static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006768{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006769 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006770 struct stream *stream = smp->strm;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006771 struct hlua *hlua = NULL;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006772 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006773
Willy Tarreaube508f12016-03-10 11:47:01 +01006774 if (!stream)
6775 return 0;
6776
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006777 if (!(hlua = hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn)))) {
Aurelien DARRAGON4a7a5d82023-08-09 14:56:19 +02006778 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6779 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006780 }
6781
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006782 /* If it is the first run, initialize the data for the call. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006783 if (!HLUA_IS_RUNNING(hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006784
6785 /* The following Lua calls can fail. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006786 if (!SET_SAFE_LJMP(hlua)) {
6787 hlua_lock(hlua);
6788 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6789 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006790 else
6791 error = "critical error";
6792 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006793 hlua_unlock(hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006794 return 0;
6795 }
6796
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006797 /* Check stack available size. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006798 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006799 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006800 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006801 return 0;
6802 }
6803
6804 /* Restore the function in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006805 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006806
6807 /* convert input sample and pust-it in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006808 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006809 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006810 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006811 return 0;
6812 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006813 hlua_smp2lua(hlua->T, smp);
6814 hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006815
6816 /* push keywords in the stack. */
6817 if (arg_p) {
6818 for (; arg_p->type != ARGT_STOP; arg_p++) {
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006819 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006820 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006821 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006822 return 0;
6823 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006824 hlua_arg2lua(hlua->T, arg_p);
6825 hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006826 }
6827 }
6828
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006829 /* We must initialize the execution timeouts. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006830 hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006831
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006832 /* At this point the execution is safe. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006833 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006834 }
6835
6836 /* Execute the function. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006837 switch (hlua_ctx_resume(hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006838 /* finished. */
6839 case HLUA_E_OK:
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006840 hlua_lock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006841 /* If the stack is empty, the function fails. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006842 if (lua_gettop(hlua->T) <= 0) {
6843 hlua_unlock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006844 return 0;
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01006845 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006846
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006847 /* Convert the returned value in sample. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006848 hlua_lua2smp(hlua->T, -1, smp);
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02006849 /* dup the smp before popping the related lua value and
6850 * returning it to haproxy
6851 */
6852 smp_dup(smp);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006853 lua_pop(hlua->T, 1);
6854 hlua_unlock(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006855 return 1;
6856
6857 /* yield. */
6858 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006859 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006860 return 0;
6861
6862 /* finished with error. */
6863 case HLUA_E_ERRMSG:
6864 /* Display log. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006865 hlua_lock(hlua);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006866 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006867 fcn->name, hlua_tostring_safe(hlua->T, -1));
6868 lua_pop(hlua->T, 1);
6869 hlua_unlock(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006870 return 0;
6871
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006872 case HLUA_E_ETMOUT:
6873 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6874 return 0;
6875
6876 case HLUA_E_NOMEM:
6877 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6878 return 0;
6879
6880 case HLUA_E_YIELD:
6881 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6882 return 0;
6883
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006884 case HLUA_E_ERR:
6885 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006886 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02006887 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006888
6889 default:
6890 return 0;
6891 }
6892}
6893
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006894/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6895 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006896 * resume sample-fetches. This function will be called by the sample
6897 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006898 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006899static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6900 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006901{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006902 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006903 struct stream *stream = smp->strm;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006904 struct hlua *hlua = NULL;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006905 const char *error;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006906 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006907
Willy Tarreaube508f12016-03-10 11:47:01 +01006908 if (!stream)
6909 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006910
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006911 if (!(hlua = hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn)))) {
Aurelien DARRAGON4a7a5d82023-08-09 14:56:19 +02006912 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6913 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006914 }
6915
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006916 /* If it is the first run, initialize the data for the call. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006917 if (!HLUA_IS_RUNNING(hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006918
6919 /* The following Lua calls can fail. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006920 if (!SET_SAFE_LJMP(hlua)) {
6921 hlua_lock(hlua);
6922 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6923 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006924 else
6925 error = "critical error";
6926 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006927 hlua_unlock(hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006928 return 0;
6929 }
6930
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006931 /* Check stack available size. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006932 if (!lua_checkstack(hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006933 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006934 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006935 return 0;
6936 }
6937
6938 /* Restore the function in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006939 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006940
6941 /* push arguments in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006942 if (!hlua_txn_new(hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006943 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006944 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006945 return 0;
6946 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006947 hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006948
6949 /* push keywords in the stack. */
6950 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6951 /* Check stack available size. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006952 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006953 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006954 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006955 return 0;
6956 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006957 hlua_arg2lua(hlua->T, arg_p);
6958 hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006959 }
6960
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006961 /* We must initialize the execution timeouts. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006962 hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006963
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006964 /* At this point the execution is safe. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006965 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006966 }
6967
6968 /* Execute the function. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006969 switch (hlua_ctx_resume(hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006970 /* finished. */
6971 case HLUA_E_OK:
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006972 hlua_lock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006973 /* If the stack is empty, the function fails. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006974 if (lua_gettop(hlua->T) <= 0) {
6975 hlua_unlock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006976 return 0;
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01006977 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006978
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006979 /* Convert the returned value in sample. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006980 hlua_lua2smp(hlua->T, -1, smp);
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02006981 /* dup the smp before popping the related lua value and
6982 * returning it to haproxy
6983 */
6984 smp_dup(smp);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006985 lua_pop(hlua->T, 1);
6986 hlua_unlock(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006987
6988 /* Set the end of execution flag. */
6989 smp->flags &= ~SMP_F_MAY_CHANGE;
6990 return 1;
6991
6992 /* yield. */
6993 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006994 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006995 return 0;
6996
6997 /* finished with error. */
6998 case HLUA_E_ERRMSG:
6999 /* Display log. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007000 hlua_lock(hlua);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007001 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007002 fcn->name, hlua_tostring_safe(hlua->T, -1));
7003 lua_pop(hlua->T, 1);
7004 hlua_unlock(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007005 return 0;
7006
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007007 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007008 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
7009 return 0;
7010
7011 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007012 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
7013 return 0;
7014
7015 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007016 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
7017 return 0;
7018
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007019 case HLUA_E_ERR:
7020 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007021 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02007022 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007023
7024 default:
7025 return 0;
7026 }
7027}
7028
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007029/* This function is an LUA binding used for registering
7030 * "sample-conv" functions. It expects a converter name used
7031 * in the haproxy configuration file, and an LUA function.
7032 */
7033__LJMP static int hlua_register_converters(lua_State *L)
7034{
7035 struct sample_conv_kw_list *sck;
7036 const char *name;
7037 int ref;
7038 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02007039 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007040 struct sample_conv *sc;
7041 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007042
7043 MAY_LJMP(check_args(L, 2, "register_converters"));
7044
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01007045 if (hlua_gethlua(L)) {
7046 /* runtime processing */
7047 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
7048 }
7049
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007050 /* First argument : converter name. */
7051 name = MAY_LJMP(luaL_checkstring(L, 1));
7052
7053 /* Second argument : lua function. */
7054 ref = MAY_LJMP(hlua_checkfunction(L, 2));
7055
Thierry Fournierf67442e2020-11-28 20:41:07 +01007056 /* Check if the converter is already registered */
7057 trash = get_trash_chunk();
7058 chunk_printf(trash, "lua.%s", name);
7059 sc = find_sample_conv(trash->area, trash->data);
7060 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01007061 fcn = sc->private;
7062 if (fcn->function_ref[hlua_state_id] != -1) {
7063 ha_warning("Trying to register converter 'lua.%s' more than once. "
7064 "This will become a hard error in version 2.5.\n", name);
7065 }
7066 fcn->function_ref[hlua_state_id] = ref;
7067 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007068 }
7069
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007070 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007071 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007072 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02007073 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01007074 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007075 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02007076 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007077
7078 /* Fill fcn. */
7079 fcn->name = strdup(name);
7080 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02007081 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01007082 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007083
7084 /* List head */
7085 sck->list.n = sck->list.p = NULL;
7086
7087 /* converter keyword. */
7088 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007089 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007090 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02007091 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007092
7093 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
7094 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01007095 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 +01007096 sck->kw[0].val_args = NULL;
7097 sck->kw[0].in_type = SMP_T_STR;
7098 sck->kw[0].out_type = SMP_T_STR;
7099 sck->kw[0].private = fcn;
7100
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007101 /* Register this new converter */
7102 sample_register_convs(sck);
7103
7104 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02007105
7106 alloc_error:
7107 release_hlua_function(fcn);
7108 ha_free(&sck);
7109 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
7110 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007111}
7112
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007113/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007114 * "sample-fetch" functions. It expects a converter name used
7115 * in the haproxy configuration file, and an LUA function.
7116 */
7117__LJMP static int hlua_register_fetches(lua_State *L)
7118{
7119 const char *name;
7120 int ref;
7121 int len;
7122 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02007123 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007124 struct sample_fetch *sf;
7125 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007126
7127 MAY_LJMP(check_args(L, 2, "register_fetches"));
7128
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01007129 if (hlua_gethlua(L)) {
7130 /* runtime processing */
7131 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
7132 }
7133
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007134 /* First argument : sample-fetch name. */
7135 name = MAY_LJMP(luaL_checkstring(L, 1));
7136
7137 /* Second argument : lua function. */
7138 ref = MAY_LJMP(hlua_checkfunction(L, 2));
7139
Thierry Fournierf67442e2020-11-28 20:41:07 +01007140 /* Check if the sample-fetch is already registered */
7141 trash = get_trash_chunk();
7142 chunk_printf(trash, "lua.%s", name);
7143 sf = find_sample_fetch(trash->area, trash->data);
7144 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01007145 fcn = sf->private;
7146 if (fcn->function_ref[hlua_state_id] != -1) {
7147 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
7148 "This will become a hard error in version 2.5.\n", name);
7149 }
7150 fcn->function_ref[hlua_state_id] = ref;
7151 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007152 }
7153
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007154 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007155 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007156 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02007157 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01007158 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007159 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02007160 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007161
7162 /* Fill fcn. */
7163 fcn->name = strdup(name);
7164 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02007165 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01007166 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007167
7168 /* List head */
7169 sfk->list.n = sfk->list.p = NULL;
7170
7171 /* sample-fetch keyword. */
7172 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007173 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007174 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02007175 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007176
7177 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
7178 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01007179 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 +01007180 sfk->kw[0].val_args = NULL;
7181 sfk->kw[0].out_type = SMP_T_STR;
7182 sfk->kw[0].use = SMP_USE_HTTP_ANY;
7183 sfk->kw[0].val = 0;
7184 sfk->kw[0].private = fcn;
7185
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007186 /* Register this new fetch. */
7187 sample_register_fetches(sfk);
7188
7189 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02007190
7191 alloc_error:
7192 release_hlua_function(fcn);
7193 ha_free(&sfk);
7194 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
7195 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007196}
7197
Christopher Faulet501465d2020-02-26 14:54:16 +01007198/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007199 */
Christopher Faulet501465d2020-02-26 14:54:16 +01007200__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007201{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007202 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007203 unsigned int delay;
7204 unsigned int wakeup_ms;
7205
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007206 /* Get hlua struct, or NULL if we execute from main lua state */
7207 hlua = hlua_gethlua(L);
7208 if (!hlua) {
7209 return 0;
7210 }
7211
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007212 MAY_LJMP(check_args(L, 1, "wake_time"));
7213
7214 delay = MAY_LJMP(luaL_checkinteger(L, 1));
7215 wakeup_ms = tick_add(now_ms, delay);
7216 hlua->wake_time = wakeup_ms;
7217 return 0;
7218}
7219
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007220/* This function is a wrapper to execute each LUA function declared as an action
7221 * wrapper during the initialisation period. This function may return any
7222 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
7223 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
7224 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007225 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007226static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02007227 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007228{
7229 char **arg;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02007230 unsigned int hflags = 0;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007231 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007232 const char *error;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007233 struct hlua *hlua = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007234
7235 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007236 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
7237 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
7238 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
7239 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007240 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007241 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007242 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007243 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007244
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007245 if (!(hlua = hlua_stream_ctx_prepare(s, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn)))) {
Aurelien DARRAGON4a7a5d82023-08-09 14:56:19 +02007246 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
7247 rule->arg.hlua_rule->fcn->name);
7248 goto end;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01007249 }
7250
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007251 /* If it is the first run, initialize the data for the call. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007252 if (!HLUA_IS_RUNNING(hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007253
7254 /* The following Lua calls can fail. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007255 if (!SET_SAFE_LJMP(hlua)) {
7256 hlua_lock(hlua);
7257 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7258 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007259 else
7260 error = "critical error";
7261 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007262 rule->arg.hlua_rule->fcn->name, error);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007263 hlua_unlock(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007264 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007265 }
7266
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007267 /* Check stack available size. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007268 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007269 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007270 rule->arg.hlua_rule->fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007271 RESET_SAFE_LJMP(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007272 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007273 }
7274
7275 /* Restore the function in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007276 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007277
Willy Tarreau87b09662015-04-03 00:22:06 +02007278 /* Create and and push object stream in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007279 if (!hlua_txn_new(hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007280 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007281 rule->arg.hlua_rule->fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007282 RESET_SAFE_LJMP(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007283 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007284 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007285 hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007286
7287 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007288 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007289 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007290 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007291 rule->arg.hlua_rule->fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007292 RESET_SAFE_LJMP(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007293 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007294 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007295 lua_pushstring(hlua->T, *arg);
7296 hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007297 }
7298
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007299 /* Now the execution is safe. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007300 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007301
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007302 /* We must initialize the execution timeouts. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007303 hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007304 }
7305
7306 /* Execute the function. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007307 switch (hlua_ctx_resume(hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007308 /* finished. */
7309 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007310 /* Catch the return value */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007311 hlua_lock(hlua);
7312 if (lua_gettop(hlua->T) > 0)
7313 act_ret = lua_tointeger(hlua->T, -1);
7314 hlua_unlock(hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007315
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007316 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02007317 if (act_ret == ACT_RET_YIELD) {
7318 if (flags & ACT_OPT_FINAL)
7319 goto err_yield;
7320
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007321 if (dir == SMP_OPT_DIR_REQ)
7322 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007323 hlua->wake_time);
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007324 else
7325 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007326 hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007327 }
7328 goto end;
7329
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007330 /* yield. */
7331 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01007332 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007333 if (dir == SMP_OPT_DIR_REQ)
7334 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007335 hlua->wake_time);
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007336 else
7337 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007338 hlua->wake_time);
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007339
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007340 /* Some actions can be wake up when a "write" event
7341 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007342 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007343 */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007344 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01007345 s->res.flags |= CF_WAKE_WRITE;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007346 if (HLUA_IS_WAKEREQWR(hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01007347 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007348 act_ret = ACT_RET_YIELD;
7349 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007350
7351 /* finished with error. */
7352 case HLUA_E_ERRMSG:
7353 /* Display log. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007354 hlua_lock(hlua);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007355 SEND_ERR(px, "Lua function '%s': %s.\n",
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007356 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
7357 lua_pop(hlua->T, 1);
7358 hlua_unlock(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007359 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007360
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007361 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01007362 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007363 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007364
7365 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01007366 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007367 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007368
7369 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02007370 err_yield:
7371 act_ret = ACT_RET_CONT;
Aurelien DARRAGON602c4af2023-08-31 21:45:21 +02007372 SEND_ERR(px, "Lua function '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007373 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007374 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007375
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007376 case HLUA_E_ERR:
7377 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007378 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007379 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007380
7381 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007382 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007383 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007384
7385 end:
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007386 if (act_ret != ACT_RET_YIELD && hlua)
7387 hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007388 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007389}
7390
Willy Tarreau144f84a2021-03-02 16:09:26 +01007391struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007392{
Olivier Houchard9f6af332018-05-25 14:04:04 +02007393 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007394
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007395 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02007396 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02007397 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007398}
7399
7400static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7401{
7402 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007403 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007404 struct task *task;
7405 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007406 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007407
Willy Tarreaubafbe012017-11-24 17:34:44 +01007408 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007409 if (!hlua) {
7410 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007411 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007412 return 0;
7413 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007414 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007415 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007416 ctx->ctx.hlua_apptcp.flags = 0;
7417
7418 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007419 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007420 if (!task) {
7421 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007422 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007423 return 0;
7424 }
7425 task->nice = 0;
7426 task->context = ctx;
7427 task->process = hlua_applet_wakeup;
7428 ctx->ctx.hlua_apptcp.task = task;
7429
7430 /* In the execution wrappers linked with a stream, the
7431 * Lua context can be not initialized. This behavior
7432 * permits to save performances because a systematic
7433 * Lua initialization cause 5% performances loss.
7434 */
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01007435 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007436 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007437 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007438 return 0;
7439 }
7440
7441 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007442 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007443
7444 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007445 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01007446 hlua_lock(hlua);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007447 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01007448 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007449 else
7450 error = "critical error";
7451 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007452 ctx->rule->arg.hlua_rule->fcn->name, error);
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01007453 hlua_unlock(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007454 return 0;
7455 }
7456
7457 /* Check stack available size. */
7458 if (!lua_checkstack(hlua->T, 1)) {
7459 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007460 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007461 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007462 return 0;
7463 }
7464
7465 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01007466 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007467
7468 /* Create and and push object stream in the stack. */
7469 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7470 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007471 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007472 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007473 return 0;
7474 }
7475 hlua->nargs = 1;
7476
7477 /* push keywords in the stack. */
7478 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7479 if (!lua_checkstack(hlua->T, 1)) {
7480 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007481 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007482 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007483 return 0;
7484 }
7485 lua_pushstring(hlua->T, *arg);
7486 hlua->nargs++;
7487 }
7488
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007489 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007490
7491 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007492 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007493 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007494
7495 return 1;
7496}
7497
Willy Tarreau60409db2019-08-21 14:14:50 +02007498void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007499{
7500 struct stream_interface *si = ctx->owner;
7501 struct stream *strm = si_strm(si);
7502 struct channel *res = si_ic(si);
7503 struct act_rule *rule = ctx->rule;
7504 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007505 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007506
7507 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007508 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7509 /* eat the whole request */
7510 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007511 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007512 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007513
7514 /* If the stream is disconnect or closed, ldo nothing. */
7515 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7516 return;
7517
7518 /* Execute the function. */
7519 switch (hlua_ctx_resume(hlua, 1)) {
7520 /* finished. */
7521 case HLUA_E_OK:
7522 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7523
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007524 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007525 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007526 res->flags |= CF_READ_NULL;
7527 si_shutr(si);
7528 return;
7529
7530 /* yield. */
7531 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007532 if (hlua->wake_time != TICK_ETERNITY)
7533 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007534 return;
7535
7536 /* finished with error. */
7537 case HLUA_E_ERRMSG:
7538 /* Display log. */
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01007539 hlua_lock(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007540 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01007541 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007542 lua_pop(hlua->T, 1);
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01007543 hlua_unlock(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007544 goto error;
7545
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007546 case HLUA_E_ETMOUT:
7547 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007548 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007549 goto error;
7550
7551 case HLUA_E_NOMEM:
7552 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007553 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007554 goto error;
7555
7556 case HLUA_E_YIELD: /* unexpected */
7557 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007558 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007559 goto error;
7560
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007561 case HLUA_E_ERR:
7562 /* Display log. */
7563 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007564 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007565 goto error;
7566
7567 default:
7568 goto error;
7569 }
7570
7571error:
7572
7573 /* For all other cases, just close the stream. */
7574 si_shutw(si);
7575 si_shutr(si);
7576 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7577}
7578
7579static void hlua_applet_tcp_release(struct appctx *ctx)
7580{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007581 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007582 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007583 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007584 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007585}
7586
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007587/* The function returns 1 if the initialisation is complete, 0 if
7588 * an errors occurs and -1 if more data are required for initializing
7589 * the applet.
7590 */
7591static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7592{
7593 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007594 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007595 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007596 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007597 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007598 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007599
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007600 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01007601 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007602 if (!hlua) {
7603 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007604 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007605 return 0;
7606 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007607 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007608 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007609 ctx->ctx.hlua_apphttp.left_bytes = -1;
7610 ctx->ctx.hlua_apphttp.flags = 0;
7611
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007612 if (txn->req.flags & HTTP_MSGF_VER_11)
7613 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7614
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007615 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007616 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007617 if (!task) {
7618 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007619 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007620 return 0;
7621 }
7622 task->nice = 0;
7623 task->context = ctx;
7624 task->process = hlua_applet_wakeup;
7625 ctx->ctx.hlua_apphttp.task = task;
7626
7627 /* In the execution wrappers linked with a stream, the
7628 * Lua context can be not initialized. This behavior
7629 * permits to save performances because a systematic
7630 * Lua initialization cause 5% performances loss.
7631 */
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01007632 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007633 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007634 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007635 return 0;
7636 }
7637
7638 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007639 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007640
7641 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007642 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01007643 hlua_lock(hlua);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007644 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01007645 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007646 else
7647 error = "critical error";
7648 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007649 ctx->rule->arg.hlua_rule->fcn->name, error);
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01007650 hlua_unlock(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007651 return 0;
7652 }
7653
7654 /* Check stack available size. */
7655 if (!lua_checkstack(hlua->T, 1)) {
7656 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007657 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007658 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007659 return 0;
7660 }
7661
7662 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01007663 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007664
7665 /* Create and and push object stream in the stack. */
7666 if (!hlua_applet_http_new(hlua->T, ctx)) {
7667 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007668 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007669 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007670 return 0;
7671 }
7672 hlua->nargs = 1;
7673
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007674 /* push keywords in the stack. */
7675 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7676 if (!lua_checkstack(hlua->T, 1)) {
7677 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007678 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007679 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007680 return 0;
7681 }
7682 lua_pushstring(hlua->T, *arg);
7683 hlua->nargs++;
7684 }
7685
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007686 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007687
7688 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007689 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007690
7691 return 1;
7692}
7693
Willy Tarreau60409db2019-08-21 14:14:50 +02007694void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007695{
7696 struct stream_interface *si = ctx->owner;
7697 struct stream *strm = si_strm(si);
7698 struct channel *req = si_oc(si);
7699 struct channel *res = si_ic(si);
7700 struct act_rule *rule = ctx->rule;
7701 struct proxy *px = strm->be;
7702 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7703 struct htx *req_htx, *res_htx;
7704
7705 res_htx = htx_from_buf(&res->buf);
7706
7707 /* If the stream is disconnect or closed, ldo nothing. */
7708 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7709 goto out;
7710
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007711 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007712 if (!b_size(&res->buf)) {
7713 si_rx_room_blk(si);
7714 goto out;
7715 }
7716 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007717 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007718 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7719
7720 /* Set the currently running flag. */
7721 if (!HLUA_IS_RUNNING(hlua) &&
7722 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02007723 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007724 si_cant_get(si);
7725 goto out;
7726 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007727 }
7728
7729 /* Executes The applet if it is not done. */
7730 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7731
7732 /* Execute the function. */
7733 switch (hlua_ctx_resume(hlua, 1)) {
7734 /* finished. */
7735 case HLUA_E_OK:
7736 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7737 break;
7738
7739 /* yield. */
7740 case HLUA_E_AGAIN:
7741 if (hlua->wake_time != TICK_ETERNITY)
7742 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007743 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007744
7745 /* finished with error. */
7746 case HLUA_E_ERRMSG:
7747 /* Display log. */
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01007748 hlua_lock(hlua);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007749 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01007750 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007751 lua_pop(hlua->T, 1);
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01007752 hlua_unlock(hlua);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007753 goto error;
7754
7755 case HLUA_E_ETMOUT:
7756 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007757 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007758 goto error;
7759
7760 case HLUA_E_NOMEM:
7761 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007762 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007763 goto error;
7764
7765 case HLUA_E_YIELD: /* unexpected */
7766 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007767 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007768 goto error;
7769
7770 case HLUA_E_ERR:
7771 /* Display log. */
7772 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007773 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007774 goto error;
7775
7776 default:
7777 goto error;
7778 }
7779 }
7780
7781 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007782 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7783 goto done;
7784
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007785 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7786 goto error;
7787
Christopher Faulet868b3b12022-04-07 10:07:18 +02007788 /* no more data are expected. If the response buffer is empty
7789 * for a chunked message, be sure to add something (EOT block in
7790 * this case) to have something to send. It is important to be
7791 * sure the EOM flags will be handled by the endpoint.
7792 */
7793 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
7794 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
7795 si_rx_room_blk(si);
7796 goto out;
7797 }
7798 channel_add_input(res, 1);
7799 }
7800
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007801 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet79c0fc72022-03-07 15:50:54 +01007802 res->flags |= CF_EOI;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007803 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7804 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007805 }
7806
7807 done:
7808 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007809 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007810 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007811 si_shutr(si);
7812 }
7813
7814 /* eat the whole request */
7815 if (co_data(req)) {
7816 req_htx = htx_from_buf(&req->buf);
7817 co_htx_skip(req, req_htx, co_data(req));
7818 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007819 }
7820 }
7821
7822 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007823 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007824 return;
7825
7826 error:
7827
7828 /* If we are in HTTP mode, and we are not send any
7829 * data, return a 500 server error in best effort:
7830 * if there is no room available in the buffer,
7831 * just close the connection.
7832 */
7833 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02007834 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007835
7836 channel_erase(res);
7837 res->buf.data = b_data(err);
7838 memcpy(res->buf.area, b_head(err), b_data(err));
7839 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007840 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007841 }
7842 if (!(strm->flags & SF_ERR_MASK))
7843 strm->flags |= SF_ERR_RESOURCE;
7844 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7845 goto done;
7846}
7847
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007848static void hlua_applet_http_release(struct appctx *ctx)
7849{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007850 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007851 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007852 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007853 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007854}
7855
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007856/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007857 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007858 *
7859 * This function can fail with an abort() due to an Lua critical error.
7860 * We are in the configuration parsing process of HAProxy, this abort() is
7861 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007862 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007863static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7864 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007865{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007866 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007867 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007868
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007869 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007870 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007871 if (!rule->arg.hlua_rule) {
7872 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02007873 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007874 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007875
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007876 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02007877 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
7878 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007879 if (!rule->arg.hlua_rule->args) {
7880 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02007881 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007882 }
7883
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007884 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01007885 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007886
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007887 /* Expect some arguments */
7888 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007889 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007890 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02007891 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007892 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007893 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007894 if (!rule->arg.hlua_rule->args[i]) {
7895 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02007896 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007897 }
7898 (*cur_arg)++;
7899 }
7900 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007901
Thierry FOURNIER42148732015-09-02 17:17:33 +02007902 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007903 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007904 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02007905
7906 error:
7907 if (rule->arg.hlua_rule) {
7908 if (rule->arg.hlua_rule->args) {
7909 for (i = 0; i < fcn->nargs; i++)
7910 ha_free(&rule->arg.hlua_rule->args[i]);
7911 ha_free(&rule->arg.hlua_rule->args);
7912 }
7913 ha_free(&rule->arg.hlua_rule);
7914 }
7915 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007916}
7917
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007918static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7919 struct act_rule *rule, char **err)
7920{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007921 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007922
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007923 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007924 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007925 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007926 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007927 * the call of this analyzer.
7928 */
7929 if (rule->from != ACT_F_HTTP_REQ) {
7930 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7931 return ACT_RET_PRS_ERR;
7932 }
7933
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007934 /* Memory for the rule. */
7935 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7936 if (!rule->arg.hlua_rule) {
7937 memprintf(err, "out of memory error");
7938 return ACT_RET_PRS_ERR;
7939 }
7940
7941 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01007942 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007943
7944 /* TODO: later accept arguments. */
7945 rule->arg.hlua_rule->args = NULL;
7946
7947 /* Add applet pointer in the rule. */
7948 rule->applet.obj_type = OBJ_TYPE_APPLET;
7949 rule->applet.name = fcn->name;
7950 rule->applet.init = hlua_applet_http_init;
7951 rule->applet.fct = hlua_applet_http_fct;
7952 rule->applet.release = hlua_applet_http_release;
7953 rule->applet.timeout = hlua_timeout_applet;
7954
7955 return ACT_RET_PRS_OK;
7956}
7957
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007958/* This function is an LUA binding used for registering
7959 * "sample-conv" functions. It expects a converter name used
7960 * in the haproxy configuration file, and an LUA function.
7961 */
7962__LJMP static int hlua_register_action(lua_State *L)
7963{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02007964 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007965 const char *name;
7966 int ref;
7967 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02007968 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007969 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007970 struct buffer *trash;
7971 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007972
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007973 /* Initialise the number of expected arguments at 0. */
7974 nargs = 0;
7975
7976 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7977 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007978
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01007979 if (hlua_gethlua(L)) {
7980 /* runtime processing */
7981 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
7982 }
7983
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007984 /* First argument : converter name. */
7985 name = MAY_LJMP(luaL_checkstring(L, 1));
7986
7987 /* Second argument : environment. */
7988 if (lua_type(L, 2) != LUA_TTABLE)
7989 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7990
7991 /* Third argument : lua function. */
7992 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7993
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007994 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007995 if (lua_gettop(L) >= 4)
7996 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7997
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007998 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007999 lua_pushnil(L);
8000 while (lua_next(L, 2) != 0) {
8001 if (lua_type(L, -1) != LUA_TSTRING)
8002 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
8003
Thierry Fournierf67442e2020-11-28 20:41:07 +01008004 /* Check if action exists */
8005 trash = get_trash_chunk();
8006 chunk_printf(trash, "lua.%s", name);
8007 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
8008 akw = tcp_req_cont_action(trash->area);
8009 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
8010 akw = tcp_res_cont_action(trash->area);
8011 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
8012 akw = action_http_req_custom(trash->area);
8013 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
8014 akw = action_http_res_custom(trash->area);
8015 } else {
8016 akw = NULL;
8017 }
8018 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008019 fcn = akw->private;
8020 if (fcn->function_ref[hlua_state_id] != -1) {
8021 ha_warning("Trying to register action 'lua.%s' more than once. "
8022 "This will become a hard error in version 2.5.\n", name);
8023 }
8024 fcn->function_ref[hlua_state_id] = ref;
8025
8026 /* pop the environment string. */
8027 lua_pop(L, 1);
8028 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008029 }
8030
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008031 /* Check required environment. Only accepted "http" or "tcp". */
8032 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008033 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008034 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008035 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008036 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008037 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008038 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008039
8040 /* Fill fcn. */
8041 fcn->name = strdup(name);
8042 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008043 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01008044 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008045
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008046 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01008047 fcn->nargs = nargs;
8048
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008049 /* List head */
8050 akl->list.n = akl->list.p = NULL;
8051
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008052 /* action keyword. */
8053 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02008054 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008055 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008056 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008057
8058 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
8059
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02008060 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008061 akl->kw[0].private = fcn;
8062 akl->kw[0].parse = action_register_lua;
8063
8064 /* select the action registering point. */
8065 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
8066 tcp_req_cont_keywords_register(akl);
8067 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
8068 tcp_res_cont_keywords_register(akl);
8069 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
8070 http_req_keywords_register(akl);
8071 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
8072 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008073 else {
8074 release_hlua_function(fcn);
8075 if (akl)
8076 ha_free((char **)&(akl->kw[0].kw));
8077 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008078 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008079 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
8080 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008081 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008082
8083 /* pop the environment string. */
8084 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008085
8086 /* reset for next loop */
8087 akl = NULL;
8088 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008089 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008090 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008091
8092 alloc_error:
8093 release_hlua_function(fcn);
8094 ha_free(&akl);
8095 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8096 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008097}
8098
8099static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
8100 struct act_rule *rule, char **err)
8101{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008102 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008103
Christopher Faulet280f85b2019-07-15 15:02:04 +02008104 if (px->mode == PR_MODE_HTTP) {
8105 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01008106 return ACT_RET_PRS_ERR;
8107 }
8108
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008109 /* Memory for the rule. */
8110 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
8111 if (!rule->arg.hlua_rule) {
8112 memprintf(err, "out of memory error");
8113 return ACT_RET_PRS_ERR;
8114 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008115
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008116 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01008117 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008118
8119 /* TODO: later accept arguments. */
8120 rule->arg.hlua_rule->args = NULL;
8121
8122 /* Add applet pointer in the rule. */
8123 rule->applet.obj_type = OBJ_TYPE_APPLET;
8124 rule->applet.name = fcn->name;
8125 rule->applet.init = hlua_applet_tcp_init;
8126 rule->applet.fct = hlua_applet_tcp_fct;
8127 rule->applet.release = hlua_applet_tcp_release;
8128 rule->applet.timeout = hlua_timeout_applet;
8129
8130 return 0;
8131}
8132
8133/* This function is an LUA binding used for registering
8134 * "sample-conv" functions. It expects a converter name used
8135 * in the haproxy configuration file, and an LUA function.
8136 */
8137__LJMP static int hlua_register_service(lua_State *L)
8138{
8139 struct action_kw_list *akl;
8140 const char *name;
8141 const char *env;
8142 int ref;
8143 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02008144 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008145 struct buffer *trash;
8146 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008147
8148 MAY_LJMP(check_args(L, 3, "register_service"));
8149
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01008150 if (hlua_gethlua(L)) {
8151 /* runtime processing */
8152 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
8153 }
8154
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008155 /* First argument : converter name. */
8156 name = MAY_LJMP(luaL_checkstring(L, 1));
8157
8158 /* Second argument : environment. */
8159 env = MAY_LJMP(luaL_checkstring(L, 2));
8160
8161 /* Third argument : lua function. */
8162 ref = MAY_LJMP(hlua_checkfunction(L, 3));
8163
Thierry Fournierf67442e2020-11-28 20:41:07 +01008164 /* Check for service already registered */
8165 trash = get_trash_chunk();
8166 chunk_printf(trash, "lua.%s", name);
8167 akw = service_find(trash->area);
8168 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008169 fcn = akw->private;
8170 if (fcn->function_ref[hlua_state_id] != -1) {
8171 ha_warning("Trying to register service 'lua.%s' more than once. "
8172 "This will become a hard error in version 2.5.\n", name);
8173 }
8174 fcn->function_ref[hlua_state_id] = ref;
8175 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008176 }
8177
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008178 /* Allocate and fill the sample fetch keyword struct. */
8179 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
8180 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02008181 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008182 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008183 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02008184 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008185
8186 /* Fill fcn. */
8187 len = strlen("<lua.>") + strlen(name) + 1;
8188 fcn->name = calloc(1, len);
8189 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02008190 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008191 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01008192 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008193
8194 /* List head */
8195 akl->list.n = akl->list.p = NULL;
8196
8197 /* converter keyword. */
8198 len = strlen("lua.") + strlen(name) + 1;
8199 akl->kw[0].kw = calloc(1, len);
8200 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02008201 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008202
8203 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
8204
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01008205 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008206 if (strcmp(env, "tcp") == 0)
8207 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008208 else if (strcmp(env, "http") == 0)
8209 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02008210 else {
8211 release_hlua_function(fcn);
8212 if (akl)
8213 ha_free((char **)&(akl->kw[0].kw));
8214 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008215 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01008216 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02008217 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008218
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02008219 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008220 akl->kw[0].private = fcn;
8221
8222 /* End of array. */
8223 memset(&akl->kw[1], 0, sizeof(*akl->kw));
8224
8225 /* Register this new converter */
8226 service_keywords_register(akl);
8227
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008228 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02008229
8230 alloc_error:
8231 release_hlua_function(fcn);
8232 ha_free(&akl);
8233 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8234 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008235}
8236
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008237/* This function initialises Lua cli handler. It copies the
8238 * arguments in the Lua stack and create channel IO objects.
8239 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02008240static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008241{
8242 struct hlua *hlua;
8243 struct hlua_function *fcn;
8244 int i;
8245 const char *error;
8246
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008247 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008248 appctx->ctx.hlua_cli.fcn = private;
8249
Willy Tarreaubafbe012017-11-24 17:34:44 +01008250 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008251 if (!hlua) {
8252 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008253 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008254 }
8255 HLUA_INIT(hlua);
8256 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008257
8258 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05008259 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008260 * applet_http. It is absolutely compatible.
8261 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008262 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008263 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01008264 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008265 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008266 }
8267 appctx->ctx.hlua_cli.task->nice = 0;
8268 appctx->ctx.hlua_cli.task->context = appctx;
8269 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
8270
8271 /* Initialises the Lua context */
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01008272 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), appctx->ctx.hlua_cli.task)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008273 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008274 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008275 }
8276
8277 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008278 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01008279 hlua_lock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008280 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008281 error = hlua_tostring_safe(hlua->T, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008282 else
8283 error = "critical error";
8284 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01008285 hlua_unlock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008286 goto error;
8287 }
8288
8289 /* Check stack available size. */
8290 if (!lua_checkstack(hlua->T, 2)) {
8291 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
8292 goto error;
8293 }
8294
8295 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008296 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008297
8298 /* Once the arguments parsed, the CLI is like an AppletTCP,
8299 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008300 */
8301 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
8302 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
8303 goto error;
8304 }
8305 hlua->nargs = 1;
8306
8307 /* push keywords in the stack. */
8308 for (i = 0; *args[i]; i++) {
8309 /* Check stack available size. */
8310 if (!lua_checkstack(hlua->T, 1)) {
8311 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
8312 goto error;
8313 }
8314 lua_pushstring(hlua->T, args[i]);
8315 hlua->nargs++;
8316 }
8317
8318 /* We must initialize the execution timeouts. */
8319 hlua->max_time = hlua_timeout_session;
8320
8321 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008322 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008323
8324 /* It's ok */
8325 return 0;
8326
8327 /* It's not ok. */
8328error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008329 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008330 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008331 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008332 return 1;
8333}
8334
8335static int hlua_cli_io_handler_fct(struct appctx *appctx)
8336{
8337 struct hlua *hlua;
8338 struct stream_interface *si;
8339 struct hlua_function *fcn;
8340
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008341 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008342 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01008343 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008344
8345 /* If the stream is disconnect or closed, ldo nothing. */
8346 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8347 return 1;
8348
8349 /* Execute the function. */
8350 switch (hlua_ctx_resume(hlua, 1)) {
8351
8352 /* finished. */
8353 case HLUA_E_OK:
8354 return 1;
8355
8356 /* yield. */
8357 case HLUA_E_AGAIN:
8358 /* We want write. */
8359 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008360 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008361 /* Set the timeout. */
8362 if (hlua->wake_time != TICK_ETERNITY)
8363 task_schedule(hlua->task, hlua->wake_time);
8364 return 0;
8365
8366 /* finished with error. */
8367 case HLUA_E_ERRMSG:
8368 /* Display log. */
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01008369 hlua_lock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008370 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008371 fcn->name, hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008372 lua_pop(hlua->T, 1);
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01008373 hlua_unlock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008374 return 1;
8375
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008376 case HLUA_E_ETMOUT:
8377 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8378 fcn->name);
8379 return 1;
8380
8381 case HLUA_E_NOMEM:
8382 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8383 fcn->name);
8384 return 1;
8385
8386 case HLUA_E_YIELD: /* unexpected */
8387 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8388 fcn->name);
8389 return 1;
8390
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008391 case HLUA_E_ERR:
8392 /* Display log. */
8393 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8394 fcn->name);
8395 return 1;
8396
8397 default:
8398 return 1;
8399 }
8400
8401 return 1;
8402}
8403
8404static void hlua_cli_io_release_fct(struct appctx *appctx)
8405{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008406 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008407 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008408}
8409
8410/* This function is an LUA binding used for registering
8411 * new keywords in the cli. It expects a list of keywords
8412 * which are the "path". It is limited to 5 keywords. A
8413 * description of the command, a function to be executed
8414 * for the parsing and a function for io handlers.
8415 */
8416__LJMP static int hlua_register_cli(lua_State *L)
8417{
8418 struct cli_kw_list *cli_kws;
8419 const char *message;
8420 int ref_io;
8421 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008422 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008423 int index;
8424 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008425 struct buffer *trash;
8426 const char *kw[5];
8427 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008428 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008429
8430 MAY_LJMP(check_args(L, 3, "register_cli"));
8431
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01008432 if (hlua_gethlua(L)) {
8433 /* runtime processing */
8434 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
8435 }
8436
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008437 /* First argument : an array of maximum 5 keywords. */
8438 if (!lua_istable(L, 1))
8439 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8440
8441 /* Second argument : string with contextual message. */
8442 message = MAY_LJMP(luaL_checkstring(L, 2));
8443
8444 /* Third and fourth argument : lua function. */
8445 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8446
Thierry Fournierf67442e2020-11-28 20:41:07 +01008447 /* Check for CLI service already registered */
8448 trash = get_trash_chunk();
8449 index = 0;
8450 lua_pushnil(L);
8451 memset(kw, 0, sizeof(kw));
8452 while (lua_next(L, 1) != 0) {
8453 if (index >= CLI_PREFIX_KW_NB)
8454 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8455 if (lua_type(L, -1) != LUA_TSTRING)
8456 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8457 kw[index] = lua_tostring(L, -1);
8458 if (index == 0)
8459 chunk_printf(trash, "%s", kw[index]);
8460 else
8461 chunk_appendf(trash, " %s", kw[index]);
8462 index++;
8463 lua_pop(L, 1);
8464 }
8465 cli_kw = cli_find_kw_exact((char **)kw);
8466 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008467 fcn = cli_kw->private;
8468 if (fcn->function_ref[hlua_state_id] != -1) {
8469 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
8470 "This will become a hard error in version 2.5.\n", trash->area);
8471 }
8472 fcn->function_ref[hlua_state_id] = ref_io;
8473 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008474 }
8475
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008476 /* Allocate and fill the sample fetch keyword struct. */
8477 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008478 if (!cli_kws) {
8479 errmsg = "Lua out of memory error.";
8480 goto error;
8481 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008482 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008483 if (!fcn) {
8484 errmsg = "Lua out of memory error.";
8485 goto error;
8486 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008487
8488 /* Fill path. */
8489 index = 0;
8490 lua_pushnil(L);
8491 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008492 if (index >= 5) {
8493 errmsg = "1st argument must be a table with a maximum of 5 entries";
8494 goto error;
8495 }
8496 if (lua_type(L, -1) != LUA_TSTRING) {
8497 errmsg = "1st argument must be a table filled with strings";
8498 goto error;
8499 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008500 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008501 if (!cli_kws->kw[0].str_kw[index]) {
8502 errmsg = "Lua out of memory error.";
8503 goto error;
8504 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008505 index++;
8506 lua_pop(L, 1);
8507 }
8508
8509 /* Copy help message. */
8510 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008511 if (!cli_kws->kw[0].usage) {
8512 errmsg = "Lua out of memory error.";
8513 goto error;
8514 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008515
8516 /* Fill fcn io handler. */
8517 len = strlen("<lua.cli>") + 1;
8518 for (i = 0; i < index; i++)
8519 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8520 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008521 if (!fcn->name) {
8522 errmsg = "Lua out of memory error.";
8523 goto error;
8524 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008525 strncat((char *)fcn->name, "<lua.cli", len);
8526 for (i = 0; i < index; i++) {
8527 strncat((char *)fcn->name, ".", len);
8528 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8529 }
8530 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +01008531 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008532
8533 /* Fill last entries. */
8534 cli_kws->kw[0].private = fcn;
8535 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8536 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8537 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8538
8539 /* Register this new converter */
8540 cli_register_kw(cli_kws);
8541
8542 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008543
8544 error:
8545 release_hlua_function(fcn);
8546 if (cli_kws) {
8547 for (i = 0; i < index; i++)
8548 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
8549 ha_free((char **)&(cli_kws->kw[0].usage));
8550 }
8551 ha_free(&cli_kws);
8552 WILL_LJMP(luaL_error(L, errmsg));
8553 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008554}
8555
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008556static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008557 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008558 char **err, unsigned int *timeout)
8559{
8560 const char *error;
8561
8562 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02008563 if (error == PARSE_TIME_OVER) {
8564 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
8565 args[1], args[0]);
8566 return -1;
8567 }
8568 else if (error == PARSE_TIME_UNDER) {
8569 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
8570 args[1], args[0]);
8571 return -1;
8572 }
8573 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008574 memprintf(err, "%s: invalid timeout", args[0]);
8575 return -1;
8576 }
8577 return 0;
8578}
8579
8580static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008581 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008582 char **err)
8583{
8584 return hlua_read_timeout(args, section_type, curpx, defpx,
8585 file, line, err, &hlua_timeout_session);
8586}
8587
8588static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008589 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008590 char **err)
8591{
8592 return hlua_read_timeout(args, section_type, curpx, defpx,
8593 file, line, err, &hlua_timeout_task);
8594}
8595
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008596static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008597 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008598 char **err)
8599{
8600 return hlua_read_timeout(args, section_type, curpx, defpx,
8601 file, line, err, &hlua_timeout_applet);
8602}
8603
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008604static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008605 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008606 char **err)
8607{
8608 char *error;
8609
8610 hlua_nb_instruction = strtoll(args[1], &error, 10);
8611 if (*error != '\0') {
8612 memprintf(err, "%s: invalid number", args[0]);
8613 return -1;
8614 }
8615 return 0;
8616}
8617
Willy Tarreau32f61e22015-03-18 17:54:59 +01008618static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008619 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +01008620 char **err)
8621{
8622 char *error;
8623
8624 if (*(args[1]) == 0) {
8625 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8626 return -1;
8627 }
8628 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8629 if (*error != '\0') {
8630 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8631 return -1;
8632 }
8633 return 0;
8634}
8635
8636
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008637/* This function is called by the main configuration key "lua-load". It loads and
8638 * execute an lua file during the parsing of the HAProxy configuration file. It is
8639 * the main lua entry point.
8640 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008641 * This function runs with the HAProxy keywords API. It returns -1 if an error
8642 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008643 *
8644 * In some error case, LUA set an error message in top of the stack. This function
8645 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008646 *
8647 * This function can fail with an abort() due to an Lua critical error.
8648 * We are in the configuration parsing process of HAProxy, this abort() is
8649 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008650 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008651static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008652{
8653 int error;
8654
8655 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008656 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008657 if (error) {
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008658 memprintf(err, "error in Lua file '%s': %s", filename, hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008659 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008660 return -1;
8661 }
8662
8663 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008664 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008665 switch (error) {
8666 case LUA_OK:
8667 break;
8668 case LUA_ERRRUN:
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008669 memprintf(err, "Lua runtime error: %s\n", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008670 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008671 return -1;
8672 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +01008673 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008674 return -1;
8675 case LUA_ERRERR:
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008676 memprintf(err, "Lua message handler error: %s\n", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008677 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008678 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +02008679#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008680 case LUA_ERRGCMM:
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008681 memprintf(err, "Lua garbage collector error: %s\n", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008682 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008683 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +02008684#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008685 default:
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008686 memprintf(err, "Lua unknown error: %s\n", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008687 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008688 return -1;
8689 }
8690
8691 return 0;
8692}
8693
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008694static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008695 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008696 char **err)
8697{
8698 if (*(args[1]) == 0) {
8699 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
8700 return -1;
8701 }
8702
Thierry Fournier59f11be2020-11-29 00:37:41 +01008703 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +01008704 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008705 ha_set_tid(0);
Thierry Fournierafc63e22020-11-28 17:06:51 +01008706 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008707}
8708
Thierry Fournier59f11be2020-11-29 00:37:41 +01008709static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008710 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +01008711 char **err)
8712{
8713 int len;
8714
8715 if (*(args[1]) == 0) {
8716 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
8717 return -1;
8718 }
8719
8720 if (per_thread_load == NULL) {
8721 /* allocate the first entry large enough to store the final NULL */
8722 per_thread_load = calloc(1, sizeof(*per_thread_load));
8723 if (per_thread_load == NULL) {
8724 memprintf(err, "out of memory error");
8725 return -1;
8726 }
8727 }
8728
8729 /* count used entries */
8730 for (len = 0; per_thread_load[len] != NULL; len++)
8731 ;
8732
8733 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
8734 if (per_thread_load == NULL) {
8735 memprintf(err, "out of memory error");
8736 return -1;
8737 }
8738
8739 per_thread_load[len] = strdup(args[1]);
8740 per_thread_load[len + 1] = NULL;
8741
8742 if (per_thread_load[len] == NULL) {
8743 memprintf(err, "out of memory error");
8744 return -1;
8745 }
8746
8747 /* loading for thread 1 only */
8748 hlua_state_id = 1;
8749 ha_set_tid(0);
8750 return hlua_load_state(args[1], hlua_states[1], err);
8751}
8752
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008753/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
8754 * in the given <ctx>.
8755 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +01008756static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008757{
Thierry Fournier3fb9e512020-11-28 10:13:12 +01008758 lua_getglobal(L, "package"); /* push package variable */
8759 lua_pushstring(L, path); /* push given path */
8760 lua_pushstring(L, ";"); /* push semicolon */
8761 lua_getfield(L, -3, type); /* push old path */
8762 lua_concat(L, 3); /* concatenate to new path */
8763 lua_setfield(L, -2, type); /* store new path */
8764 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008765
8766 return 0;
8767}
8768
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008769static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008770 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008771 char **err)
8772{
8773 char *path;
8774 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008775 struct prepend_path *p = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008776
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008777 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008778 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008779 }
8780
8781 if (!(*args[1])) {
8782 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008783 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008784 }
8785 path = args[1];
8786
8787 if (*args[2]) {
8788 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
8789 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008790 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008791 }
8792 type = args[2];
8793 }
8794
Thierry Fournier59f11be2020-11-29 00:37:41 +01008795 p = calloc(1, sizeof(*p));
8796 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +01008797 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008798 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008799 }
8800 p->path = strdup(path);
8801 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +01008802 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008803 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008804 }
8805 p->type = strdup(type);
8806 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +01008807 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008808 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008809 }
Willy Tarreau2b718102021-04-21 07:32:39 +02008810 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +01008811
8812 hlua_prepend_path(hlua_states[0], type, path);
8813 hlua_prepend_path(hlua_states[1], type, path);
8814 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008815
8816err2:
8817 free(p->type);
8818 free(p->path);
8819err:
8820 free(p);
8821 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008822}
8823
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008824/* configuration keywords declaration */
8825static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008826 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008827 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +01008828 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008829 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8830 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008831 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008832 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008833 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008834 { 0, NULL, NULL },
8835}};
8836
Willy Tarreau0108d902018-11-25 19:14:37 +01008837INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8838
Christopher Fauletafd8f102018-11-08 11:34:21 +01008839
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008840/* This function can fail with an abort() due to an Lua critical error.
8841 * We are in the initialisation process of HAProxy, this abort() is
8842 * tolerated.
8843 */
Thierry Fournierb8cef172020-11-28 15:37:17 +01008844int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008845{
8846 struct hlua_init_function *init;
8847 const char *msg;
8848 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008849 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +01008850 const char *kind;
8851 const char *trace;
8852 int return_status = 1;
8853#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
8854 int nres;
8855#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008856
Willy Tarreaucdb53462020-12-02 12:12:00 +01008857 /* disable memory limit checks if limit is not set */
8858 if (!hlua_global_allocator.limit)
8859 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
8860
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008861 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +01008862 if (setjmp(safe_ljmp_env) != 0) {
8863 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +01008864 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008865 error = hlua_tostring_safe(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008866 else
8867 error = "critical error";
8868 fprintf(stderr, "Lua post-init: %s.\n", error);
8869 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +01008870 } else {
8871 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008872 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008873
Thierry Fournierb8cef172020-11-28 15:37:17 +01008874 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008875
Thierry Fournierc7492592020-11-28 23:57:24 +01008876 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +01008877 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Aurelien DARRAGON93591b42023-03-20 16:29:55 +01008878 /* function ref should be released right away since it was pushed
8879 * on the stack and will not be used anymore
8880 */
8881 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +01008882
8883#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Aurelien DARRAGON2dec9502023-09-08 19:29:08 +02008884 ret = lua_resume(L, NULL, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +01008885#else
Aurelien DARRAGON2dec9502023-09-08 19:29:08 +02008886 ret = lua_resume(L, NULL, 0);
Thierry Fournier670db242020-11-28 10:49:59 +01008887#endif
8888 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008889 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +01008890
8891 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +01008892 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +01008893 break;
Thierry Fournier670db242020-11-28 10:49:59 +01008894
8895 case LUA_ERRERR:
8896 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008897 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +01008898 case LUA_ERRRUN:
8899 if (!kind)
8900 kind = "runtime error";
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008901 msg = hlua_tostring_safe(L, -1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01008902 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +01008903 if (msg)
8904 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
8905 else
8906 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
Aurelien DARRAGONadac9322024-03-01 19:54:16 +01008907
8908 lua_settop(L, 0); /* Empty the stack. */
Thierry Fournier670db242020-11-28 10:49:59 +01008909 return_status = 0;
8910 break;
8911
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008912 default:
Thierry Fournier670db242020-11-28 10:49:59 +01008913 /* Unknown error */
8914 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008915 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +01008916 case LUA_YIELD:
8917 /* yield is not configured at this step, this state doesn't happen */
8918 if (!kind)
8919 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008920 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +01008921 case LUA_ERRMEM:
8922 if (!kind)
8923 kind = "out of memory error";
Aurelien DARRAGON93f5d8d2023-08-09 10:11:49 +02008924 lua_settop(L, 0); /* Empty the stack. */
Christopher Fauletd09cc512021-03-24 14:48:45 +01008925 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +01008926 ha_alert("Lua init: %s: %s\n", kind, trace);
8927 return_status = 0;
8928 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008929 }
Thierry Fournier670db242020-11-28 10:49:59 +01008930 if (!return_status)
8931 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008932 }
Thierry Fournier3c539322020-11-28 16:05:05 +01008933
8934 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +01008935 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008936}
8937
Thierry Fournierb8cef172020-11-28 15:37:17 +01008938int hlua_post_init()
8939{
Thierry Fournier59f11be2020-11-29 00:37:41 +01008940 int ret;
8941 int i;
8942 int errors;
8943 char *err = NULL;
8944 struct hlua_function *fcn;
8945
Willy Tarreau42afc592021-08-30 09:35:18 +02008946#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +01008947 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01008948 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +01008949 int saved_used_backed = global.ssl_used_backend;
8950 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01008951 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +01008952 global.ssl_used_backend = saved_used_backed;
8953 }
8954#endif
8955
Thierry Fournierc7492592020-11-28 23:57:24 +01008956 /* Perform post init of common thread */
8957 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008958 ha_set_tid(0);
8959 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
8960 if (ret == 0)
8961 return 0;
8962
8963 /* init remaining lua states and load files */
8964 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
8965
8966 /* set thread context */
8967 ha_set_tid(hlua_state_id - 1);
8968
8969 /* Init lua state */
8970 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
8971
8972 /* Load lua files */
8973 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
8974 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
8975 if (ret != 0) {
8976 ha_alert("Lua init: %s\n", err);
8977 return 0;
8978 }
8979 }
8980 }
8981
8982 /* Reset thread context */
8983 ha_set_tid(0);
8984
8985 /* Execute post init for all states */
8986 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
8987
8988 /* set thread context */
8989 ha_set_tid(hlua_state_id - 1);
8990
8991 /* run post init */
8992 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
8993 if (ret == 0)
8994 return 0;
8995 }
8996
8997 /* Reset thread context */
8998 ha_set_tid(0);
8999
9000 /* control functions registering. Each function must have:
9001 * - only the function_ref[0] set positive and all other to -1
9002 * - only the function_ref[0] set to -1 and all other positive
9003 * This ensure a same reference is not used both in shared
9004 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05009005 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +01009006 * complicated to found for the end user.
9007 */
9008 errors = 0;
9009 list_for_each_entry(fcn, &referenced_functions, l) {
9010 ret = 0;
9011 for (i = 1; i < global.nbthread + 1; i++) {
9012 if (fcn->function_ref[i] == -1)
9013 ret--;
9014 else
9015 ret++;
9016 }
9017 if (abs(ret) != global.nbthread) {
9018 ha_alert("Lua function '%s' is not referenced in all thread. "
9019 "Expect function in all thread or in none thread.\n", fcn->name);
9020 errors++;
9021 continue;
9022 }
9023
9024 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05009025 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
9026 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +01009027 "exclusive.\n", fcn->name);
9028 errors++;
9029 }
9030 }
9031
9032 if (errors > 0)
9033 return 0;
9034
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05009035 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +01009036 * -1 in order to have probably a segfault if someone use it
9037 */
9038 hlua_state_id = -1;
9039
9040 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +01009041}
9042
Willy Tarreau32f61e22015-03-18 17:54:59 +01009043/* The memory allocator used by the Lua stack. <ud> is a pointer to the
9044 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
9045 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +01009046 * allocation. <nsize> is the requested new size. A new allocation is
9047 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +01009048 * zero. This one verifies that the limits are respected but is optimized
9049 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaue00ad052021-10-22 16:00:02 +02009050 *
9051 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
9052 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
9053 * that and will simply allocate zero as if it were the result of malloc(0),
9054 * so mapping this onto realloc() will lead to memory leaks on non-glibc
9055 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +01009056 */
9057static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
9058{
9059 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +01009060 size_t limit, old, new;
9061
Tim Duesterhus22586522021-01-08 10:35:33 +01009062 if (unlikely(!ptr && !nsize))
9063 return NULL;
9064
Willy Tarreaucdb53462020-12-02 12:12:00 +01009065 /* a limit of ~0 means unlimited and boot complete, so there's no need
9066 * for accounting anymore.
9067 */
Willy Tarreaue00ad052021-10-22 16:00:02 +02009068 if (likely(~zone->limit == 0)) {
9069 if (!nsize)
9070 ha_free(&ptr);
9071 else
9072 ptr = realloc(ptr, nsize);
9073 return ptr;
9074 }
Willy Tarreau32f61e22015-03-18 17:54:59 +01009075
Willy Tarreaud36c7fa2020-12-02 12:26:29 +01009076 if (!ptr)
9077 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +01009078
Willy Tarreaucdb53462020-12-02 12:12:00 +01009079 /* enforce strict limits across all threads */
9080 limit = zone->limit;
9081 old = _HA_ATOMIC_LOAD(&zone->allocated);
9082 do {
9083 new = old + nsize - osize;
9084 if (unlikely(nsize && limit && new > limit))
9085 return NULL;
9086 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +01009087
Willy Tarreaue00ad052021-10-22 16:00:02 +02009088 if (!nsize)
9089 ha_free(&ptr);
9090 else
9091 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +01009092
9093 if (unlikely(!ptr && nsize)) // failed
9094 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
9095
9096 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +01009097 return ptr;
9098}
9099
Thierry Fournierecb83c22020-11-28 15:49:44 +01009100/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009101 * We are in the initialisation process of HAProxy, this abort() is
9102 * tolerated.
9103 */
Thierry Fournierecb83c22020-11-28 15:49:44 +01009104lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01009105{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009106 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009107 int idx;
9108 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009109 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009110 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009111 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009112 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009113 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +01009114 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009115
Thierry FOURNIER380d0932015-01-23 14:27:52 +01009116 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009117 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01009118
firexinghebdd336c2023-07-13 11:03:34 +08009119 if (!L) {
9120 fprintf(stderr,
9121 "Lua init: critical error: lua_newstate() returned NULL."
9122 " This may possibly be caused by a memory allocation error.\n");
9123 exit(1);
9124 }
9125
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009126 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009127 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009128 *context = NULL;
9129
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009130 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009131 * the Lua function can fail with an abort. We are in the initialisation
9132 * process of HAProxy, this abort() is tolerated.
9133 */
9134
Thierry Fournier3c539322020-11-28 16:05:05 +01009135 /* Call post initialisation function in safe environment. */
9136 if (setjmp(safe_ljmp_env) != 0) {
9137 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009138 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01009139 error_msg = hlua_tostring_safe(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +01009140 else
9141 error_msg = "critical error";
9142 fprintf(stderr, "Lua init: %s.\n", error_msg);
9143 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +01009144 } else {
9145 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +01009146 }
9147
Thierry FOURNIER380d0932015-01-23 14:27:52 +01009148 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009149 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01009150#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
9151#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
9152#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009153 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01009154#endif
9155#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009156 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01009157#endif
9158#undef HLUA_PREPEND_PATH_TOSTRING
9159#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009160
Thierry Fournier59f11be2020-11-29 00:37:41 +01009161 /* Apply configured prepend path */
9162 list_for_each_entry(pp, &prepend_path_list, l)
9163 hlua_prepend_path(L, pp->type, pp->path);
9164
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009165 /*
9166 *
9167 * Create "core" object.
9168 *
9169 */
9170
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01009171 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009172 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009173
Thierry Fournierecb83c22020-11-28 15:49:44 +01009174 /* set the thread id */
9175 hlua_class_const_int(L, "thread", thread_num);
9176
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009177 /* Push the loglevel constants. */
Christopher Faulet8263e942024-02-29 15:41:17 +01009178 hlua_class_const_int(L, "silent", -1);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01009179 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009180 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009181
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009182 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009183 hlua_class_function(L, "register_init", hlua_register_init);
9184 hlua_class_function(L, "register_task", hlua_register_task);
9185 hlua_class_function(L, "register_fetches", hlua_register_fetches);
9186 hlua_class_function(L, "register_converters", hlua_register_converters);
9187 hlua_class_function(L, "register_action", hlua_register_action);
9188 hlua_class_function(L, "register_service", hlua_register_service);
9189 hlua_class_function(L, "register_cli", hlua_register_cli);
9190 hlua_class_function(L, "yield", hlua_yield);
9191 hlua_class_function(L, "set_nice", hlua_set_nice);
9192 hlua_class_function(L, "sleep", hlua_sleep);
9193 hlua_class_function(L, "msleep", hlua_msleep);
9194 hlua_class_function(L, "add_acl", hlua_add_acl);
9195 hlua_class_function(L, "del_acl", hlua_del_acl);
9196 hlua_class_function(L, "set_map", hlua_set_map);
9197 hlua_class_function(L, "del_map", hlua_del_map);
9198 hlua_class_function(L, "tcp", hlua_socket_new);
9199 hlua_class_function(L, "log", hlua_log);
9200 hlua_class_function(L, "Debug", hlua_log_debug);
9201 hlua_class_function(L, "Info", hlua_log_info);
9202 hlua_class_function(L, "Warning", hlua_log_warning);
9203 hlua_class_function(L, "Alert", hlua_log_alert);
9204 hlua_class_function(L, "done", hlua_done);
9205 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009206
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009207 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009208
9209 /*
9210 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +01009211 * Create "act" object.
9212 *
9213 */
9214
9215 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009216 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +01009217
9218 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009219 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
9220 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
9221 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
9222 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
9223 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
9224 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
9225 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
9226 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +01009227
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009228 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009229
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009230 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +01009231
9232 /*
9233 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009234 * Register class Map
9235 *
9236 */
9237
9238 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009239 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009240
9241 /* register pattern types. */
9242 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009243 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01009244 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02009245 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009246 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01009247 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009248
9249 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009250 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009251
9252 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009253 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009254
Ilya Shipitsind4259502020-04-08 01:07:56 +05009255 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009256 lua_pushstring(L, "__index");
9257 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009258
9259 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009260 hlua_class_function(L, "lookup", hlua_map_lookup);
9261 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009262
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009263 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009264
Thierry Fournier45e78d72016-02-19 18:34:46 +01009265 /* Register previous table in the registry with reference and named entry.
9266 * The function hlua_register_metatable() pops the stack, so we
9267 * previously create a copy of the table.
9268 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009269 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
9270 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009271
9272 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009273 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009274
9275 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009276 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009277
9278 /*
9279 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009280 * Register class Channel
9281 *
9282 */
9283
9284 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009285 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009286
Ilya Shipitsind4259502020-04-08 01:07:56 +05009287 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009288 lua_pushstring(L, "__index");
9289 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009290
9291 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009292 hlua_class_function(L, "get", hlua_channel_get);
9293 hlua_class_function(L, "dup", hlua_channel_dup);
9294 hlua_class_function(L, "getline", hlua_channel_getline);
9295 hlua_class_function(L, "set", hlua_channel_set);
9296 hlua_class_function(L, "append", hlua_channel_append);
9297 hlua_class_function(L, "send", hlua_channel_send);
9298 hlua_class_function(L, "forward", hlua_channel_forward);
9299 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
9300 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
9301 hlua_class_function(L, "is_full", hlua_channel_is_full);
9302 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009303
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009304 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009305
9306 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009307 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009308
9309 /*
9310 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009311 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009312 *
9313 */
9314
9315 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009316 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009317
Ilya Shipitsind4259502020-04-08 01:07:56 +05009318 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009319 lua_pushstring(L, "__index");
9320 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009321
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009322 /* Browse existing fetches and create the associated
9323 * object method.
9324 */
9325 sf = NULL;
9326 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009327 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
9328 * by an underscore.
9329 */
Willy Tarreaufa92f362021-08-26 16:48:53 +02009330 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02009331 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009332 if (*p == '.' || *p == '-' || *p == '+')
9333 *p = '_';
9334
9335 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009336 lua_pushstring(L, trash.area);
9337 lua_pushlightuserdata(L, sf);
9338 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
9339 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009340 }
9341
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009342 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009343
9344 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009345 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009346
9347 /*
9348 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009349 * Register class Converters
9350 *
9351 */
9352
9353 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009354 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009355
9356 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009357 lua_pushstring(L, "__index");
9358 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009359
9360 /* Browse existing converters and create the associated
9361 * object method.
9362 */
9363 sc = NULL;
9364 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009365 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
9366 * by an underscore.
9367 */
Willy Tarreaufa92f362021-08-26 16:48:53 +02009368 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02009369 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009370 if (*p == '.' || *p == '-' || *p == '+')
9371 *p = '_';
9372
9373 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009374 lua_pushstring(L, trash.area);
9375 lua_pushlightuserdata(L, sc);
9376 lua_pushcclosure(L, hlua_run_sample_conv, 1);
9377 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009378 }
9379
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009380 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009381
9382 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009383 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009384
9385 /*
9386 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009387 * Register class HTTP
9388 *
9389 */
9390
9391 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009392 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009393
Ilya Shipitsind4259502020-04-08 01:07:56 +05009394 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009395 lua_pushstring(L, "__index");
9396 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009397
9398 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009399 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
9400 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
9401 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
9402 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
9403 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
9404 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
9405 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
9406 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
9407 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
9408 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009409
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009410 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
9411 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
9412 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
9413 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
9414 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
9415 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
9416 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009417
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009418 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009419
9420 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009421 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009422
9423 /*
9424 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009425 * Register class AppletTCP
9426 *
9427 */
9428
9429 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009430 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009431
Ilya Shipitsind4259502020-04-08 01:07:56 +05009432 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009433 lua_pushstring(L, "__index");
9434 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009435
9436 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009437 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
9438 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
9439 hlua_class_function(L, "send", hlua_applet_tcp_send);
9440 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
9441 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
9442 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
9443 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
9444 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009445
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009446 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009447
9448 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009449 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009450
9451 /*
9452 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009453 * Register class AppletHTTP
9454 *
9455 */
9456
9457 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009458 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009459
Ilya Shipitsind4259502020-04-08 01:07:56 +05009460 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009461 lua_pushstring(L, "__index");
9462 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009463
9464 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009465 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
9466 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
9467 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
9468 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
9469 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
9470 hlua_class_function(L, "getline", hlua_applet_http_getline);
9471 hlua_class_function(L, "receive", hlua_applet_http_recv);
9472 hlua_class_function(L, "send", hlua_applet_http_send);
9473 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
9474 hlua_class_function(L, "set_status", hlua_applet_http_status);
9475 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009476
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009477 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009478
9479 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009480 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009481
9482 /*
9483 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009484 * Register class TXN
9485 *
9486 */
9487
9488 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009489 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009490
Ilya Shipitsind4259502020-04-08 01:07:56 +05009491 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009492 lua_pushstring(L, "__index");
9493 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009494
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01009495 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009496 hlua_class_function(L, "set_priv", hlua_set_priv);
9497 hlua_class_function(L, "get_priv", hlua_get_priv);
9498 hlua_class_function(L, "set_var", hlua_set_var);
9499 hlua_class_function(L, "unset_var", hlua_unset_var);
9500 hlua_class_function(L, "get_var", hlua_get_var);
9501 hlua_class_function(L, "done", hlua_txn_done);
9502 hlua_class_function(L, "reply", hlua_txn_reply_new);
9503 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
9504 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
9505 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
9506 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
9507 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
9508 hlua_class_function(L, "deflog", hlua_txn_deflog);
9509 hlua_class_function(L, "log", hlua_txn_log);
9510 hlua_class_function(L, "Debug", hlua_txn_log_debug);
9511 hlua_class_function(L, "Info", hlua_txn_log_info);
9512 hlua_class_function(L, "Warning", hlua_txn_log_warning);
9513 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01009514
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009515 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009516
9517 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009518 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009519
9520 /*
9521 *
Christopher Faulet700d9e82020-01-31 12:21:52 +01009522 * Register class reply
9523 *
9524 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009525 lua_newtable(L);
9526 lua_pushstring(L, "__index");
9527 lua_newtable(L);
9528 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
9529 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
9530 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
9531 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
9532 lua_settable(L, -3); /* Sets the __index entry. */
9533 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +01009534
9535
9536 /*
9537 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009538 * Register class Socket
9539 *
9540 */
9541
9542 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009543 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009544
Ilya Shipitsind4259502020-04-08 01:07:56 +05009545 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009546 lua_pushstring(L, "__index");
9547 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009548
Baptiste Assmann84bb4932015-03-02 21:40:06 +01009549#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009550 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01009551#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009552 hlua_class_function(L, "connect", hlua_socket_connect);
9553 hlua_class_function(L, "send", hlua_socket_send);
9554 hlua_class_function(L, "receive", hlua_socket_receive);
9555 hlua_class_function(L, "close", hlua_socket_close);
9556 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
9557 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
9558 hlua_class_function(L, "setoption", hlua_socket_setoption);
9559 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009560
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009561 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009562
9563 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009564 lua_pushstring(L, "__gc");
9565 lua_pushcclosure(L, hlua_socket_gc, 0);
9566 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009567
9568 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009569 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009570
Thierry Fournieraafc7772020-12-04 11:47:47 +01009571 lua_atpanic(L, hlua_panic_safe);
9572
9573 return L;
9574}
9575
9576void hlua_init(void) {
9577 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01009578 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +01009579#ifdef USE_OPENSSL
9580 struct srv_kw *kw;
9581 int tmp_error;
9582 char *error;
9583 char *args[] = { /* SSL client configuration. */
9584 "ssl",
9585 "verify",
9586 "none",
9587 NULL
9588 };
9589#endif
9590
9591 /* Init post init function list head */
9592 for (i = 0; i < MAX_THREADS + 1; i++)
9593 LIST_INIT(&hlua_init_functions[i]);
9594
9595 /* Init state for common/shared lua parts */
9596 hlua_state_id = 0;
9597 ha_set_tid(0);
9598 hlua_states[0] = hlua_init_state(0);
9599
9600 /* Init state 1 for thread 0. We have at least one thread. */
9601 hlua_state_id = 1;
9602 ha_set_tid(0);
9603 hlua_states[1] = hlua_init_state(1);
9604
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009605 /* Proxy and server configuration initialisation. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01009606 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_LUA, &errmsg);
9607 if (!socket_proxy) {
9608 fprintf(stderr, "Lua init: %s\n", errmsg);
9609 exit(1);
9610 }
9611 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009612
9613 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009614 socket_tcp = new_server(socket_proxy);
9615 if (!socket_tcp) {
9616 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
9617 exit(1);
9618 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009619
9620#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009621 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009622 socket_ssl = new_server(socket_proxy);
9623 if (!socket_ssl) {
9624 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
9625 exit(1);
9626 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009627
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009628 socket_ssl->use_ssl = 1;
9629 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009630
Bertrand Jacquin80839ff2021-01-21 19:14:46 +00009631 for (i = 0; args[i] != NULL; i++) {
9632 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009633 /*
9634 *
9635 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009636 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009637 * features like client certificates and ssl_verify.
9638 *
9639 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009640 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009641 if (tmp_error != 0) {
9642 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
9643 abort(); /* This must be never arrives because the command line
9644 not editable by the user. */
9645 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +00009646 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009647 }
9648 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009649#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01009650
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01009651}
Willy Tarreaubb57d942016-12-21 19:04:56 +01009652
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +02009653static void hlua_deinit()
9654{
Willy Tarreau186f3762020-12-04 11:48:12 +01009655 int thr;
9656
9657 for (thr = 0; thr < MAX_THREADS+1; thr++) {
9658 if (hlua_states[thr])
9659 lua_close(hlua_states[thr]);
9660 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +01009661
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009662 free_server(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +01009663
Willy Tarreau0f143af2021-03-05 10:41:48 +01009664#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009665 free_server(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +01009666#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01009667
9668 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +02009669}
9670
9671REGISTER_POST_DEINIT(hlua_deinit);
9672
Willy Tarreau80713382018-11-26 10:19:54 +01009673static void hlua_register_build_options(void)
9674{
Willy Tarreaubb57d942016-12-21 19:04:56 +01009675 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01009676
Willy Tarreaubb57d942016-12-21 19:04:56 +01009677 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
9678 hap_register_build_opts(ptr, 1);
9679}
Willy Tarreau80713382018-11-26 10:19:54 +01009680
9681INITCALL0(STG_REGISTER, hlua_register_build_options);