blob: d8b2203359f0ab2a23305fd6935a549ce4a48635 [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
Christopher Fauletd09cc512021-03-24 14:48:45 +0100565__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200566{
567 lua_Debug ar;
568 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200569 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200570
571 while (lua_getstack(L, level++, &ar)) {
572
573 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100574 if (b_data(msg))
575 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200576
577 /* Fill fields:
578 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
579 * 'l': fills in the field currentline;
580 * 'n': fills in the field name and namewhat;
581 * 't': fills in the field istailcall;
582 */
583 lua_getinfo(L, "Slnt", &ar);
584
585 /* Append code localisation */
586 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100587 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200588 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100589 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200590
591 /*
592 * Get function name
593 *
594 * if namewhat is no empty, name is defined.
595 * what contains "Lua" for Lua function, "C" for C function,
596 * or "main" for main code.
597 */
598 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100599 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200600
601 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100602 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200603
604 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100605 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200606
607 else /* nothing left... */
608 chunk_appendf(msg, "?");
609
610
611 /* Display tailed call */
612 if (ar.istailcall)
613 chunk_appendf(msg, " ...");
614 }
615
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200616 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200617}
618
619
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100620/* This function check the number of arguments available in the
621 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500622 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100623 */
624__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
625{
626 if (lua_gettop(L) == nb)
627 return;
628 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
629}
630
Mark Lakes22154b42018-01-29 14:38:40 -0800631/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100632 * and the line number where the error is encountered.
633 */
634static int hlua_pusherror(lua_State *L, const char *fmt, ...)
635{
636 va_list argp;
637 va_start(argp, fmt);
638 luaL_where(L, 1);
639 lua_pushvfstring(L, fmt, argp);
640 va_end(argp);
641 lua_concat(L, 2);
642 return 1;
643}
644
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100645/* This functions is used with sample fetch and converters. It
646 * converts the HAProxy configuration argument in a lua stack
647 * values.
648 *
649 * It takes an array of "arg", and each entry of the array is
650 * converted and pushed in the LUA stack.
651 */
652static int hlua_arg2lua(lua_State *L, const struct arg *arg)
653{
654 switch (arg->type) {
655 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100656 case ARGT_TIME:
657 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100658 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100659 break;
660
661 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200662 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100663 break;
664
665 case ARGT_IPV4:
666 case ARGT_IPV6:
667 case ARGT_MSK4:
668 case ARGT_MSK6:
669 case ARGT_FE:
670 case ARGT_BE:
671 case ARGT_TAB:
672 case ARGT_SRV:
673 case ARGT_USR:
674 case ARGT_MAP:
675 default:
676 lua_pushnil(L);
677 break;
678 }
679 return 1;
680}
681
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500682/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100683 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500684 * with sample fetch wrappers. The input arguments are given to the
685 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100686 */
687static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
688{
689 switch (lua_type(L, ud)) {
690
691 case LUA_TNUMBER:
692 case LUA_TBOOLEAN:
693 arg->type = ARGT_SINT;
694 arg->data.sint = lua_tointeger(L, ud);
695 break;
696
697 case LUA_TSTRING:
698 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200699 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200700 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200701 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200702 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100703 break;
704
705 case LUA_TUSERDATA:
706 case LUA_TNIL:
707 case LUA_TTABLE:
708 case LUA_TFUNCTION:
709 case LUA_TTHREAD:
710 case LUA_TLIGHTUSERDATA:
711 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200712 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100713 break;
714 }
715 return 1;
716}
717
718/* the following functions are used to convert a struct sample
719 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500720 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100721 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100722static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100723{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200724 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100725 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100726 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200727 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100728 break;
729
730 case SMP_T_BIN:
731 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200732 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100733 break;
734
735 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200736 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100737 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
738 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
739 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
740 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
741 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
742 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
743 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
744 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
745 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200746 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100747 break;
748 default:
749 lua_pushnil(L);
750 break;
751 }
752 break;
753
754 case SMP_T_IPV4:
755 case SMP_T_IPV6:
756 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200757 if (sample_casts[smp->data.type][SMP_T_STR] &&
758 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200759 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100760 else
761 lua_pushnil(L);
762 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100763 default:
764 lua_pushnil(L);
765 break;
766 }
767 return 1;
768}
769
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100770/* the following functions are used to convert a struct sample
771 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500772 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100773 */
774static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
775{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200776 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100777
778 case SMP_T_BIN:
779 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200780 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100781 break;
782
783 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200784 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100785 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
786 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
787 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
788 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
789 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
790 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
791 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
792 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
793 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200794 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100795 break;
796 default:
797 lua_pushstring(L, "");
798 break;
799 }
800 break;
801
802 case SMP_T_SINT:
803 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100804 case SMP_T_IPV4:
805 case SMP_T_IPV6:
806 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200807 if (sample_casts[smp->data.type][SMP_T_STR] &&
808 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200809 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100810 else
811 lua_pushstring(L, "");
812 break;
813 default:
814 lua_pushstring(L, "");
815 break;
816 }
817 return 1;
818}
819
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100820/* the following functions are used to convert an Lua type in a
821 * struct sample. This is useful to provide data from a converter
822 * to the LUA code.
823 */
824static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
825{
826 switch (lua_type(L, ud)) {
827
828 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200829 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200830 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100831 break;
832
833
834 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200835 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200836 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100837 break;
838
839 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200840 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100841 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200842 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200843 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200844 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200845 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100846 break;
847
848 case LUA_TUSERDATA:
849 case LUA_TNIL:
850 case LUA_TTABLE:
851 case LUA_TFUNCTION:
852 case LUA_TTHREAD:
853 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200854 case LUA_TNONE:
855 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200856 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200857 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100858 break;
859 }
860 return 1;
861}
862
Ilya Shipitsind4259502020-04-08 01:07:56 +0500863/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800864 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100865 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100866 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500867 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100868 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100869 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100870__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100871 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100872{
873 int min_arg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200874 int i, idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100875 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200876 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200877 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200878 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200879 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100880
881 idx = 0;
882 min_arg = ARGM(mask);
883 mask >>= ARGM_BITS;
884
885 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200886 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100887
888 /* Check oversize. */
889 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200890 msg = "Malformed argument mask";
891 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100892 }
893
894 /* Check for mandatory arguments. */
895 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100896 if (idx < min_arg) {
897
898 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200899 if (idx > 0) {
900 msg = "Mandatory argument expected";
901 goto error;
902 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100903
904 /* If first argument have a certain type, some default values
905 * may be used. See the function smp_resolve_args().
906 */
907 switch (mask & ARGT_MASK) {
908
909 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200910 if (!(p->cap & PR_CAP_FE)) {
911 msg = "Mandatory argument expected";
912 goto error;
913 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100914 argp[idx].data.prx = p;
915 argp[idx].type = ARGT_FE;
916 argp[idx+1].type = ARGT_STOP;
917 break;
918
919 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200920 if (!(p->cap & PR_CAP_BE)) {
921 msg = "Mandatory argument expected";
922 goto error;
923 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100924 argp[idx].data.prx = p;
925 argp[idx].type = ARGT_BE;
926 argp[idx+1].type = ARGT_STOP;
927 break;
928
929 case ARGT_TAB:
Olivier Houcharda2658272022-09-13 00:35:53 +0200930 if (!p->table) {
931 msg = "Mandatory argument expected";
932 goto error;
933 }
934 argp[idx].data.t = p->table;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100935 argp[idx].type = ARGT_TAB;
936 argp[idx+1].type = ARGT_STOP;
937 break;
938
939 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200940 msg = "Mandatory argument expected";
941 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100942 break;
943 }
944 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200945 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100946 }
947
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500948 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100949 if ((mask & ARGT_MASK) == ARGT_STOP &&
950 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200951 msg = "Last argument expected";
952 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100953 }
954
955 if ((mask & ARGT_MASK) == ARGT_STOP &&
956 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200957 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100958 }
959
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200960 /* Convert some argument types. All string in argp[] are for not
961 * duplicated yet.
962 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100963 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100964 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200965 if (argp[idx].type != ARGT_SINT) {
966 msg = "integer expected";
967 goto error;
968 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100969 argp[idx].type = ARGT_SINT;
970 break;
971
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100972 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200973 if (argp[idx].type != ARGT_SINT) {
974 msg = "integer expected";
975 goto error;
976 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200977 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100978 break;
979
980 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200981 if (argp[idx].type != ARGT_SINT) {
982 msg = "integer expected";
983 goto error;
984 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200985 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100986 break;
987
988 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200989 if (argp[idx].type != ARGT_STR) {
990 msg = "string expected";
991 goto error;
992 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200993 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200994 if (!argp[idx].data.prx) {
995 msg = "frontend doesn't exist";
996 goto error;
997 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100998 argp[idx].type = ARGT_FE;
999 break;
1000
1001 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001002 if (argp[idx].type != ARGT_STR) {
1003 msg = "string expected";
1004 goto error;
1005 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001006 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001007 if (!argp[idx].data.prx) {
1008 msg = "backend doesn't exist";
1009 goto error;
1010 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001011 argp[idx].type = ARGT_BE;
1012 break;
1013
1014 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001015 if (argp[idx].type != ARGT_STR) {
1016 msg = "string expected";
1017 goto error;
1018 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001019 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001020 if (!argp[idx].data.t) {
1021 msg = "table doesn't exist";
1022 goto error;
1023 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001024 argp[idx].type = ARGT_TAB;
1025 break;
1026
1027 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001028 if (argp[idx].type != ARGT_STR) {
1029 msg = "string expected";
1030 goto error;
1031 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001032 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001033 if (sname) {
1034 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001035 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +02001036 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001037 if (!px) {
1038 msg = "backend doesn't exist";
1039 goto error;
1040 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001041 }
1042 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +02001043 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001044 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001045 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001046 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001047 if (!argp[idx].data.srv) {
1048 msg = "server doesn't exist";
1049 goto error;
1050 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001051 argp[idx].type = ARGT_SRV;
1052 break;
1053
1054 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001055 if (argp[idx].type != ARGT_STR) {
1056 msg = "string expected";
1057 goto error;
1058 }
1059 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1060 msg = "invalid IPv4 address";
1061 goto error;
1062 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001063 argp[idx].type = ARGT_IPV4;
1064 break;
1065
1066 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001067 if (argp[idx].type == ARGT_SINT)
1068 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
1069 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001070 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
1071 msg = "invalid IPv4 mask";
1072 goto error;
1073 }
1074 }
1075 else {
1076 msg = "integer or string expected";
1077 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001078 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001079 argp[idx].type = ARGT_MSK4;
1080 break;
1081
1082 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001083 if (argp[idx].type != ARGT_STR) {
1084 msg = "string expected";
1085 goto error;
1086 }
1087 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1088 msg = "invalid IPv6 address";
1089 goto error;
1090 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001091 argp[idx].type = ARGT_IPV6;
1092 break;
1093
1094 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +02001095 if (argp[idx].type == ARGT_SINT)
1096 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
1097 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001098 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
1099 msg = "invalid IPv6 mask";
1100 goto error;
1101 }
1102 }
1103 else {
1104 msg = "integer or string expected";
1105 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +02001106 }
Tim Duesterhusb814da62018-01-25 16:24:50 +01001107 argp[idx].type = ARGT_MSK6;
1108 break;
1109
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001110 case ARGT_REG:
1111 if (argp[idx].type != ARGT_STR) {
1112 msg = "string expected";
1113 goto error;
1114 }
1115 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
1116 if (!reg) {
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001117 msg = hlua_pushfstring_safe(L, "error compiling regex '%s' : '%s'",
1118 argp[idx].data.str.area, err);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001119 free(err);
1120 goto error;
1121 }
1122 argp[idx].type = ARGT_REG;
1123 argp[idx].data.reg = reg;
1124 break;
1125
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +01001126 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001127 if (argp[idx].type != ARGT_STR) {
1128 msg = "string expected";
1129 goto error;
1130 }
1131 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +01001132 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +02001133 ul = p->uri_auth->userlist;
1134 else
1135 ul = auth_find_userlist(argp[idx].data.str.area);
1136
1137 if (!ul) {
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001138 msg = hlua_pushfstring_safe(L, "unable to find userlist '%s'",
1139 argp[idx].data.str.area);
Christopher Fauletd25d9262020-08-06 11:04:46 +02001140 goto error;
1141 }
1142 argp[idx].type = ARGT_USR;
1143 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001144 break;
1145
1146 case ARGT_STR:
1147 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
1148 msg = "unable to duplicate string arg";
1149 goto error;
1150 }
1151 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001152 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001153
Christopher Fauletd25d9262020-08-06 11:04:46 +02001154 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +02001155 msg = "type not yet supported";
1156 goto error;
1157 break;
1158
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001159 }
1160
1161 /* Check for type of argument. */
1162 if ((mask & ARGT_MASK) != argp[idx].type) {
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001163 msg = hlua_pushfstring_safe(L, "'%s' expected, got '%s'",
1164 arg_type_names[(mask & ARGT_MASK)],
1165 arg_type_names[argp[idx].type & ARGT_MASK]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001166 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001167 }
1168
1169 /* Next argument. */
1170 mask >>= ARGT_BITS;
1171 idx++;
1172 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001173 return 0;
1174
1175 error:
Olivier Houchardda25dac2022-09-13 00:31:17 +02001176 argp[idx].type = ARGT_STOP;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001177 for (i = 0; i < idx; i++) {
1178 if (argp[i].type == ARGT_STR)
1179 chunk_destroy(&argp[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02001180 else if (argp[i].type == ARGT_REG)
1181 regex_free(argp[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02001182 }
1183 WILL_LJMP(luaL_argerror(L, first + idx, msg));
1184 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +01001185}
1186
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001187/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001188 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001189 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001190 *
1191 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001192 * - hlua_sethlua : create the association between hlua context and lua_state.
1193 */
1194static inline struct hlua *hlua_gethlua(lua_State *L)
1195{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001196 struct hlua **hlua = lua_getextraspace(L);
1197 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001198}
1199static inline void hlua_sethlua(struct hlua *hlua)
1200{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +01001201 struct hlua **hlua_store = lua_getextraspace(hlua->T);
1202 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001203}
1204
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001205/* This function is used to send logs. It try to send on screen (stderr)
1206 * and on the default syslog server.
1207 */
1208static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1209{
1210 struct tm tm;
1211 char *p;
1212
1213 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001214 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001215 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001216 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001217 /* Break the message if exceed the buffer size. */
1218 *(p-4) = ' ';
1219 *(p-3) = '.';
1220 *(p-2) = '.';
1221 *(p-1) = '.';
1222 break;
1223 }
Willy Tarreau90807112020-02-25 08:16:33 +01001224 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001225 *p = *msg;
1226 else
1227 *p = '.';
1228 }
1229 *p = '\0';
1230
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001231 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001232 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001233 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1234 return;
1235
Willy Tarreaua678b432015-08-28 10:14:59 +02001236 get_localtime(date.tv_sec, &tm);
1237 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001238 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001239 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001240 fflush(stderr);
1241 }
1242}
1243
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001244/* This function just ensure that the yield will be always
1245 * returned with a timeout and permit to set some flags
1246 */
Aurelien DARRAGONf5d3b312023-07-13 10:18:04 +02001247__LJMP void hlua_yieldk(lua_State *L, int nresults, lua_KContext ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001248 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001249{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001250 struct hlua *hlua;
1251
1252 /* Get hlua struct, or NULL if we execute from main lua state */
1253 hlua = hlua_gethlua(L);
1254 if (!hlua) {
1255 return;
1256 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001257
1258 /* Set the wake timeout. If timeout is required, we set
1259 * the expiration time.
1260 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001261 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001262
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001263 hlua->flags |= flags;
1264
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001265 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001266 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001267}
1268
Willy Tarreau87b09662015-04-03 00:22:06 +02001269/* This function initialises the Lua environment stored in the stream.
1270 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001271 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001272 *
1273 * This function is particular. it initialises a new Lua thread. If the
1274 * initialisation fails (example: out of memory error), the lua function
1275 * throws an error (longjmp).
1276 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001277 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001278 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001279 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001280 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001281 */
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01001282int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001283{
1284 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001285 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001286 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001287 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001288 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001289 LIST_INIT(&lua->com);
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01001290 if (!SET_SAFE_LJMP_PARENT(lua)) {
1291 lua->Tref = LUA_REFNIL;
1292 return 0;
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001293 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001294 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001295 if (!lua->T) {
1296 lua->Tref = LUA_REFNIL;
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01001297 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001298 return 0;
1299 }
1300 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001301 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001302 lua->task = task;
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01001303 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001304 return 1;
1305}
1306
Willy Tarreau87b09662015-04-03 00:22:06 +02001307/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001308 * is destroyed. The destroy also the memory context. The struct "lua"
Aurelien DARRAGONd5c8a102023-03-01 16:45:50 +01001309 * will be freed.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001310 */
1311void hlua_ctx_destroy(struct hlua *lua)
1312{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001313 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001314 return;
1315
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001316 if (!lua->T)
1317 goto end;
1318
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001319 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001320 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001321
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001322 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001323 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001324 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001325 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001326
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001327 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001328 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001329 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001330 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001331 /* Forces a garbage collecting process. If the Lua program is finished
1332 * without error, we run the GC on the thread pointer. Its freed all
1333 * the unused memory.
1334 * If the thread is finnish with an error or is currently yielded,
1335 * it seems that the GC applied on the thread doesn't clean anything,
1336 * so e run the GC on the main thread.
1337 * NOTE: maybe this action locks all the Lua threads untiml the en of
1338 * the garbage collection.
1339 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001340 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001341 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001342 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001343 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001344 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001345 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001346
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001347 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001348
1349end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001350 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001351}
1352
1353/* This function is used to restore the Lua context when a coroutine
1354 * fails. This function copy the common memory between old coroutine
1355 * and the new coroutine. The old coroutine is destroyed, and its
1356 * replaced by the new coroutine.
1357 * If the flag "keep_msg" is set, the last entry of the old is assumed
1358 * as string error message and it is copied in the new stack.
1359 */
1360static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1361{
1362 lua_State *T;
1363 int new_ref;
1364
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001365 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001366 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001367 if (!T)
1368 return 0;
1369
1370 /* Copy last error message. */
1371 if (keep_msg)
1372 lua_xmove(lua->T, T, 1);
1373
1374 /* Copy data between the coroutines. */
1375 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1376 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001377 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001378
1379 /* Destroy old data. */
1380 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1381
1382 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001383 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001384
1385 /* Fill the struct with the new coroutine values. */
1386 lua->Mref = new_ref;
1387 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001388 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001389
1390 /* Set context. */
1391 hlua_sethlua(lua);
1392
1393 return 1;
1394}
1395
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001396/* Helper function to get the lua ctx for a given stream and state_id */
1397static inline struct hlua *hlua_stream_ctx_get(struct stream *s, int state_id)
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001398{
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001399 /* state_id == 0 -> global runtime ctx
1400 * state_id != 0 -> per-thread runtime ctx
1401 */
1402 return s->hlua[!!state_id];
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001403}
1404
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001405/* Helper function to prepare the lua ctx for a given stream and state id
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001406 *
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001407 * It uses the global or per-thread ctx depending on the expected
1408 * <state_id>.
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001409 *
1410 * Returns hlua ctx on success and NULL on failure
1411 */
1412static struct hlua *hlua_stream_ctx_prepare(struct stream *s, int state_id)
1413{
1414 /* In the execution wrappers linked with a stream, the
1415 * Lua context can be not initialized. This behavior
1416 * permits to save performances because a systematic
1417 * Lua initialization cause 5% performances loss.
1418 */
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001419 if (!s->hlua[!!state_id]) {
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001420 struct hlua *hlua;
1421
1422 hlua = pool_alloc(pool_head_hlua);
1423 if (!hlua)
1424 return NULL;
1425 HLUA_INIT(hlua);
1426 if (!hlua_ctx_init(hlua, state_id, s->task)) {
1427 pool_free(pool_head_hlua, hlua);
1428 return NULL;
1429 }
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001430 s->hlua[!!state_id] = hlua;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001431 }
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01001432 return s->hlua[!!state_id];
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01001433}
1434
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001435void hlua_hook(lua_State *L, lua_Debug *ar)
1436{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001437 struct hlua *hlua;
1438
1439 /* Get hlua struct, or NULL if we execute from main lua state */
1440 hlua = hlua_gethlua(L);
1441 if (!hlua)
1442 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001443
1444 /* Lua cannot yield when its returning from a function,
1445 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001446 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001447 */
1448 if (lua_gethookmask(L) & LUA_MASKRET) {
1449 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1450 return;
1451 }
1452
1453 /* restore the interrupt condition. */
1454 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1455
1456 /* If we interrupt the Lua processing in yieldable state, we yield.
1457 * If the state is not yieldable, trying yield causes an error.
1458 */
1459 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001460 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001461
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001462 /* If we cannot yield, update the clock and check the timeout. */
1463 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001464 hlua->run_time += now_ms - hlua->start_time;
1465 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001466 lua_pushfstring(L, "execution timeout");
1467 WILL_LJMP(lua_error(L));
1468 }
1469
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001470 /* Update the start time. */
1471 hlua->start_time = now_ms;
1472
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001473 /* Try to interrupt the process at the end of the current
1474 * unyieldable function.
1475 */
1476 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001477}
1478
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001479/* This function start or resumes the Lua stack execution. If the flag
1480 * "yield_allowed" if no set and the LUA stack execution returns a yield
1481 * The function return an error.
1482 *
1483 * The function can returns 4 values:
1484 * - HLUA_E_OK : The execution is terminated without any errors.
1485 * - HLUA_E_AGAIN : The execution must continue at the next associated
1486 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001487 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001488 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001489 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001490 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001491 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001492 * LUA code.
1493 */
1494static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1495{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001496#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1497 int nres;
1498#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001499 int ret;
1500 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001501 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001502
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001503 /* Initialise run time counter. */
1504 if (!HLUA_IS_RUNNING(lua))
1505 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001506
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001507 /* Lock the whole Lua execution. This lock must be before the
1508 * label "resume_execution".
1509 */
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +01001510 hlua_lock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001511
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001512resume_execution:
1513
1514 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1515 * instructions. it is used for preventing infinite loops.
1516 */
1517 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1518
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001519 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001520 HLUA_SET_RUN(lua);
1521 HLUA_CLR_CTRLYIELD(lua);
1522 HLUA_CLR_WAKERESWR(lua);
1523 HLUA_CLR_WAKEREQWR(lua);
Christopher Fauleta6e792f2021-08-04 17:58:21 +02001524 HLUA_CLR_NOYIELD(lua);
1525 if (!yield_allowed)
1526 HLUA_SET_NOYIELD(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001527
Christopher Fauletbc275a92020-02-26 14:55:16 +01001528 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001529 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001530 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001531
Aurelien DARRAGON5d351962024-03-12 00:22:44 +01001532 HLUA_SET_BUSY(lua);
1533
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001534 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001535#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001536 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001537#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001538 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001539#endif
Aurelien DARRAGONfff27962023-09-08 14:00:27 +02001540
Aurelien DARRAGON5d351962024-03-12 00:22:44 +01001541 HLUA_CLR_BUSY(lua);
1542
Aurelien DARRAGONfff27962023-09-08 14:00:27 +02001543 /* reset nargs because those possibly passed to the lua_resume() call
1544 * were already consumed, and since we may call lua_resume() again
1545 * after a successful yield, we don't want to pass stale nargs hint
1546 * to the Lua API. As such, nargs should be set explicitly before each
1547 * lua_resume() (or hlua_ctx_resume()) invocation if needed.
1548 */
1549 lua->nargs = 0;
1550
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001551 switch (ret) {
1552
1553 case LUA_OK:
1554 ret = HLUA_E_OK;
1555 break;
1556
1557 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001558 /* Check if the execution timeout is expired. It it is the case, we
1559 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001560 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001561 tv_update_date(0, 1);
1562 lua->run_time += now_ms - lua->start_time;
1563 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001564 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001565 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001566 break;
1567 }
1568 /* Process the forced yield. if the general yield is not allowed or
1569 * if no task were associated this the current Lua execution
1570 * coroutine, we resume the execution. Else we want to return in the
1571 * scheduler and we want to be waked up again, to continue the
1572 * current Lua execution. So we schedule our own task.
1573 */
1574 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001575 if (!yield_allowed || !lua->task)
1576 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001577 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001578 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001579 if (!yield_allowed) {
1580 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001581 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001582 break;
1583 }
1584 ret = HLUA_E_AGAIN;
1585 break;
1586
1587 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001588
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001589 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001590 * because the errors ares the only one mean to return immediately
1591 * from and lua execution.
1592 */
1593 if (lua->flags & HLUA_EXIT) {
1594 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001595 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001596 break;
1597 }
1598
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001599 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001600 if (!lua_checkstack(lua->T, 1)) {
1601 ret = HLUA_E_ERR;
1602 break;
1603 }
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01001604 msg = hlua_tostring_safe(lua->T, -1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001605 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001606 if (msg)
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001607 hlua_pushfstring_safe(lua->T, "[state-id %d] runtime error: %s from %s",
1608 lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001609 else
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001610 hlua_pushfstring_safe(lua->T, "[state-id %d] unknown runtime error from %s",
1611 lua->state_id, trace);
Aurelien DARRAGONadac9322024-03-01 19:54:16 +01001612
1613 /* Move the error msg at the top and then empty the stack except last msg */
1614 lua_insert(lua->T, -lua_gettop(lua->T));
1615 lua_settop(lua->T, 1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001616 ret = HLUA_E_ERRMSG;
1617 break;
1618
1619 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001620 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001621 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001622 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001623 break;
1624
1625 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001626 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001627 if (!lua_checkstack(lua->T, 1)) {
1628 ret = HLUA_E_ERR;
1629 break;
1630 }
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01001631 msg = hlua_tostring_safe(lua->T, -1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001632 if (msg)
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001633 hlua_pushfstring_safe(lua->T, "[state-id %d] message handler error: %s",
1634 lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001635 else
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02001636 hlua_pushfstring_safe(lua->T, "[state-id %d] message handler error",
1637 lua->state_id);
Aurelien DARRAGONadac9322024-03-01 19:54:16 +01001638
1639 /* Move the error msg at the top and then empty the stack except last msg */
1640 lua_insert(lua->T, -lua_gettop(lua->T));
1641 lua_settop(lua->T, 1);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001642 ret = HLUA_E_ERRMSG;
1643 break;
1644
1645 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001646 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001647 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001648 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001649 break;
1650 }
1651
1652 switch (ret) {
1653 case HLUA_E_AGAIN:
1654 break;
1655
1656 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001657 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001658 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001659 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001660 break;
1661
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001662 case HLUA_E_ETMOUT:
1663 case HLUA_E_NOMEM:
1664 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001665 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001666 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001667 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001668 hlua_ctx_renew(lua, 0);
1669 break;
1670
1671 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001672 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001673 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001674 break;
1675 }
1676
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001677 /* This is the main exit point, remove the Lua lock. */
Aurelien DARRAGONe00bf5d2023-03-21 13:22:33 +01001678 hlua_unlock(lua);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001679
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001680 return ret;
1681}
1682
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001683/* This function exit the current code. */
1684__LJMP static int hlua_done(lua_State *L)
1685{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001686 struct hlua *hlua;
1687
1688 /* Get hlua struct, or NULL if we execute from main lua state */
1689 hlua = hlua_gethlua(L);
1690 if (!hlua)
1691 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001692
1693 hlua->flags |= HLUA_EXIT;
1694 WILL_LJMP(lua_error(L));
1695
1696 return 0;
1697}
1698
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001699/* This function is an LUA binding. It provides a function
1700 * for deleting ACL from a referenced ACL file.
1701 */
1702__LJMP static int hlua_del_acl(lua_State *L)
1703{
1704 const char *name;
1705 const char *key;
1706 struct pat_ref *ref;
1707
1708 MAY_LJMP(check_args(L, 2, "del_acl"));
1709
1710 name = MAY_LJMP(luaL_checkstring(L, 1));
1711 key = MAY_LJMP(luaL_checkstring(L, 2));
1712
1713 ref = pat_ref_lookup(name);
1714 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001715 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001716
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001717 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001718 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001719 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001720 return 0;
1721}
1722
1723/* This function is an LUA binding. It provides a function
1724 * for deleting map entry from a referenced map file.
1725 */
1726static int hlua_del_map(lua_State *L)
1727{
1728 const char *name;
1729 const char *key;
1730 struct pat_ref *ref;
1731
1732 MAY_LJMP(check_args(L, 2, "del_map"));
1733
1734 name = MAY_LJMP(luaL_checkstring(L, 1));
1735 key = MAY_LJMP(luaL_checkstring(L, 2));
1736
1737 ref = pat_ref_lookup(name);
1738 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001739 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001740
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001741 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001742 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001743 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001744 return 0;
1745}
1746
1747/* This function is an LUA binding. It provides a function
1748 * for adding ACL pattern from a referenced ACL file.
1749 */
1750static int hlua_add_acl(lua_State *L)
1751{
1752 const char *name;
1753 const char *key;
1754 struct pat_ref *ref;
1755
1756 MAY_LJMP(check_args(L, 2, "add_acl"));
1757
1758 name = MAY_LJMP(luaL_checkstring(L, 1));
1759 key = MAY_LJMP(luaL_checkstring(L, 2));
1760
1761 ref = pat_ref_lookup(name);
1762 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001763 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001764
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001765 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001766 if (pat_ref_find_elt(ref, key) == NULL)
1767 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001768 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001769 return 0;
1770}
1771
1772/* This function is an LUA binding. It provides a function
1773 * for setting map pattern and sample from a referenced map
1774 * file.
1775 */
1776static int hlua_set_map(lua_State *L)
1777{
1778 const char *name;
1779 const char *key;
1780 const char *value;
1781 struct pat_ref *ref;
1782
1783 MAY_LJMP(check_args(L, 3, "set_map"));
1784
1785 name = MAY_LJMP(luaL_checkstring(L, 1));
1786 key = MAY_LJMP(luaL_checkstring(L, 2));
1787 value = MAY_LJMP(luaL_checkstring(L, 3));
1788
1789 ref = pat_ref_lookup(name);
1790 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001791 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001792
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001793 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001794 if (pat_ref_find_elt(ref, key) != NULL)
1795 pat_ref_set(ref, key, value, NULL);
1796 else
1797 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001798 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001799 return 0;
1800}
1801
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001802/* A class is a lot of memory that contain data. This data can be a table,
1803 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001804 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001805 * the name of the object (_G[<name>] = <metable> ).
1806 *
1807 * A metable is a table that modify the standard behavior of a standard
1808 * access to the associated data. The entries of this new metatable are
1809 * defined as is:
1810 *
1811 * http://lua-users.org/wiki/MetatableEvents
1812 *
1813 * __index
1814 *
1815 * we access an absent field in a table, the result is nil. This is
1816 * true, but it is not the whole truth. Actually, such access triggers
1817 * the interpreter to look for an __index metamethod: If there is no
1818 * such method, as usually happens, then the access results in nil;
1819 * otherwise, the metamethod will provide the result.
1820 *
1821 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1822 * the key does not appear in the table, but the metatable has an __index
1823 * property:
1824 *
1825 * - if the value is a function, the function is called, passing in the
1826 * table and the key; the return value of that function is returned as
1827 * the result.
1828 *
1829 * - if the value is another table, the value of the key in that table is
1830 * asked for and returned (and if it doesn't exist in that table, but that
1831 * table's metatable has an __index property, then it continues on up)
1832 *
1833 * - Use "rawget(myTable,key)" to skip this metamethod.
1834 *
1835 * http://www.lua.org/pil/13.4.1.html
1836 *
1837 * __newindex
1838 *
1839 * Like __index, but control property assignment.
1840 *
1841 * __mode - Control weak references. A string value with one or both
1842 * of the characters 'k' and 'v' which specifies that the the
1843 * keys and/or values in the table are weak references.
1844 *
1845 * __call - Treat a table like a function. When a table is followed by
1846 * parenthesis such as "myTable( 'foo' )" and the metatable has
1847 * a __call key pointing to a function, that function is invoked
1848 * (passing any specified arguments) and the return value is
1849 * returned.
1850 *
1851 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1852 * called, if the metatable for myTable has a __metatable
1853 * key, the value of that key is returned instead of the
1854 * actual metatable.
1855 *
1856 * __tostring - Control string representation. When the builtin
1857 * "tostring( myTable )" function is called, if the metatable
1858 * for myTable has a __tostring property set to a function,
1859 * that function is invoked (passing myTable to it) and the
1860 * return value is used as the string representation.
1861 *
1862 * __len - Control table length. When the table length is requested using
1863 * the length operator ( '#' ), if the metatable for myTable has
1864 * a __len key pointing to a function, that function is invoked
1865 * (passing myTable to it) and the return value used as the value
1866 * of "#myTable".
1867 *
1868 * __gc - Userdata finalizer code. When userdata is set to be garbage
1869 * collected, if the metatable has a __gc field pointing to a
1870 * function, that function is first invoked, passing the userdata
1871 * to it. The __gc metamethod is not called for tables.
1872 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1873 *
1874 * Special metamethods for redefining standard operators:
1875 * http://www.lua.org/pil/13.1.html
1876 *
1877 * __add "+"
1878 * __sub "-"
1879 * __mul "*"
1880 * __div "/"
1881 * __unm "!"
1882 * __pow "^"
1883 * __concat ".."
1884 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001885 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001886 * http://www.lua.org/pil/13.2.html
1887 *
1888 * __eq "=="
1889 * __lt "<"
1890 * __le "<="
1891 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001892
1893/*
1894 *
1895 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001896 * Class Map
1897 *
1898 *
1899 */
1900
1901/* Returns a struct hlua_map if the stack entry "ud" is
1902 * a class session, otherwise it throws an error.
1903 */
1904__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1905{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001906 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001907}
1908
1909/* This function is the map constructor. It don't need
1910 * the class Map object. It creates and return a new Map
1911 * object. It must be called only during "body" or "init"
1912 * context because it process some filesystem accesses.
1913 */
1914__LJMP static int hlua_map_new(struct lua_State *L)
1915{
1916 const char *fn;
1917 int match = PAT_MATCH_STR;
1918 struct sample_conv conv;
1919 const char *file = "";
1920 int line = 0;
1921 lua_Debug ar;
1922 char *err = NULL;
1923 struct arg args[2];
1924
1925 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1926 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1927
1928 fn = MAY_LJMP(luaL_checkstring(L, 1));
1929
1930 if (lua_gettop(L) >= 2) {
1931 match = MAY_LJMP(luaL_checkinteger(L, 2));
1932 if (match < 0 || match >= PAT_MATCH_NUM)
1933 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1934 }
1935
1936 /* Get Lua filename and line number. */
1937 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1938 lua_getinfo(L, "Sl", &ar); /* get info about it */
1939 if (ar.currentline > 0) { /* is there info? */
1940 file = ar.short_src;
1941 line = ar.currentline;
1942 }
1943 }
1944
1945 /* fill fake sample_conv struct. */
1946 conv.kw = ""; /* unused. */
1947 conv.process = NULL; /* unused. */
1948 conv.arg_mask = 0; /* unused. */
1949 conv.val_args = NULL; /* unused. */
1950 conv.out_type = SMP_T_STR;
1951 conv.private = (void *)(long)match;
1952 switch (match) {
1953 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1954 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1955 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1956 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1957 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1958 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1959 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001960 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001961 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1962 default:
1963 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1964 }
1965
1966 /* fill fake args. */
1967 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001968 args[0].data.str.area = strdup(fn);
1969 args[0].data.str.data = strlen(fn);
1970 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001971 args[1].type = ARGT_STOP;
1972
1973 /* load the map. */
1974 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001975 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001976 * free the err variable.
1977 */
Aurelien DARRAGONca0cdfe2024-06-04 12:48:45 +02001978 hlua_pusherror(L, "'new': %s.", err);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001979 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001980 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001981 WILL_LJMP(lua_error(L));
1982 }
1983
1984 /* create the lua object. */
1985 lua_newtable(L);
1986 lua_pushlightuserdata(L, args[0].data.map);
1987 lua_rawseti(L, -2, 0);
1988
1989 /* Pop a class Map metatable and affect it to the userdata. */
1990 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1991 lua_setmetatable(L, -2);
1992
1993
1994 return 1;
1995}
1996
1997__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1998{
1999 struct map_descriptor *desc;
2000 struct pattern *pat;
2001 struct sample smp;
2002
2003 MAY_LJMP(check_args(L, 2, "lookup"));
2004 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02002005 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002006 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02002007 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002008 }
2009 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002010 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002011 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002012 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 +01002013 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002014 }
2015
2016 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02002017 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002018 if (str)
2019 lua_pushstring(L, "");
2020 else
2021 lua_pushnil(L);
2022 return 1;
2023 }
2024
2025 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002026 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02002027 return 1;
2028}
2029
2030__LJMP static int hlua_map_lookup(struct lua_State *L)
2031{
2032 return _hlua_map_lookup(L, 0);
2033}
2034
2035__LJMP static int hlua_map_slookup(struct lua_State *L)
2036{
2037 return _hlua_map_lookup(L, 1);
2038}
2039
2040/*
2041 *
2042 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043 * Class Socket
2044 *
2045 *
2046 */
2047
2048__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
2049{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002050 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051}
2052
2053/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002054 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002055 * received.
2056 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002057static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002058{
Willy Tarreau00a37f02015-04-13 12:05:19 +02002059 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002060
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002061 if (appctx->ctx.hlua_cosocket.die) {
2062 si_shutw(si);
2063 si_shutr(si);
2064 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002065 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
2066 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002067 stream_shutdown(si_strm(si), SF_ERR_KILLED);
2068 }
2069
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002070 /* If we can't write, wakeup the pending write signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002071 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002072 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002073
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05002074 /* If we can't read, wakeup the pending read signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002075 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002076 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02002077
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002078 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002079 * to be notified whenever the connection completes.
2080 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002081 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002082 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01002083 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01002084 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02002085 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02002086 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087
2088 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002089 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002091 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02002092 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002093 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002094
2095 /* Wake the tasks which wants to read if the buffer contains data. */
Christopher Faulet174144c2024-02-16 15:33:44 +01002096 if (!channel_is_empty(si_oc(si))) {
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002097 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Christopher Faulet174144c2024-02-16 15:33:44 +01002098 si_cant_get(si);
2099 }
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002100
2101 /* Some data were injected in the buffer, notify the stream
2102 * interface.
2103 */
2104 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01002105 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002106
2107 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01002108 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002109 */
2110 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01002111 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112}
2113
Willy Tarreau87b09662015-04-03 00:22:06 +02002114/* This function is called when the "struct stream" is destroyed.
2115 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002116 * Wake all the pending signals.
2117 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02002118static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002119{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002120 struct xref *peer;
2121
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002122 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002123 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
2124 if (peer)
2125 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126
2127 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002128 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
2129 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002130}
2131
2132/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02002133 * uses this object. If the stream does not exists, just quit.
2134 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002135 * pending signal can rest in the read and write lists. destroy
2136 * it.
2137 */
2138__LJMP static int hlua_socket_gc(lua_State *L)
2139{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002140 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002142 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002143
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002144 MAY_LJMP(check_args(L, 1, "__gc"));
2145
2146 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002147 peer = xref_get_peer_and_lock(&socket->xref);
2148 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002150 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002152 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002153 appctx->ctx.hlua_cosocket.die = 1;
2154 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002155
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002156 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002157 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158 return 0;
2159}
2160
2161/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02002162 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002163 */
sada05ed3302018-05-11 11:48:18 -07002164__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002166 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002168 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002169 struct hlua *hlua;
2170
2171 /* Get hlua struct, or NULL if we execute from main lua state */
2172 hlua = hlua_gethlua(L);
2173 if (!hlua)
2174 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002176 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002177
2178 /* Check if we run on the same thread than the xreator thread.
2179 * We cannot access to the socket if the thread is different.
2180 */
2181 if (socket->tid != tid)
2182 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2183
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002184 peer = xref_get_peer_and_lock(&socket->xref);
2185 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01002187
2188 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002189 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002190
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002191 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002192 appctx->ctx.hlua_cosocket.die = 1;
2193 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002195 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002196 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197 return 0;
2198}
2199
sada05ed3302018-05-11 11:48:18 -07002200/* The close function calls close_helper.
2201 */
2202__LJMP static int hlua_socket_close(lua_State *L)
2203{
2204 MAY_LJMP(check_args(L, 1, "close"));
2205 return hlua_socket_close_helper(L);
2206}
2207
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208/* This Lua function assumes that the stack contain three parameters.
2209 * 1 - USERDATA containing a struct socket
2210 * 2 - INTEGER with values of the macro defined below
2211 * If the integer is -1, we must read at most one line.
2212 * If the integer is -2, we ust read all the data until the
2213 * end of the stream.
2214 * If the integer is positive value, we must read a number of
2215 * bytes corresponding to this value.
2216 */
2217#define HLSR_READ_LINE (-1)
2218#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002219__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220{
2221 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2222 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002223 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002225 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02002227 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002228 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02002229 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002230 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002231 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01002232 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002233 struct stream_interface *si;
2234 struct stream *s;
2235 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002236 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002238 /* Get hlua struct, or NULL if we execute from main lua state */
2239 hlua = hlua_gethlua(L);
2240
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002241 /* Check if this lua stack is schedulable. */
2242 if (!hlua || !hlua->task)
2243 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
2244 "'frontend', 'backend' or 'task'"));
2245
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002246 /* Check if we run on the same thread than the xreator thread.
2247 * We cannot access to the socket if the thread is different.
2248 */
2249 if (socket->tid != tid)
2250 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2251
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002252 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002253 peer = xref_get_peer_and_lock(&socket->xref);
2254 if (!peer)
2255 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002256 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2257 si = appctx->owner;
2258 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002259
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002260 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002263 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002264 if (nblk < 0) /* Connection close. */
2265 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002266 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002267 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002268
2269 /* remove final \r\n. */
2270 if (nblk == 1) {
2271 if (blk1[len1-1] == '\n') {
2272 len1--;
2273 skip_at_end++;
2274 if (blk1[len1-1] == '\r') {
2275 len1--;
2276 skip_at_end++;
2277 }
2278 }
2279 }
2280 else {
2281 if (blk2[len2-1] == '\n') {
2282 len2--;
2283 skip_at_end++;
2284 if (blk2[len2-1] == '\r') {
2285 len2--;
2286 skip_at_end++;
2287 }
2288 }
2289 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290 }
2291
2292 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002294 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295 if (nblk < 0) /* Connection close. */
2296 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002297 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298 goto connection_empty;
2299 }
2300
2301 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002303 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304 if (nblk < 0) /* Connection close. */
2305 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002306 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002307 goto connection_empty;
2308
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002309 missing_bytes = wanted - socket->b.n;
2310 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002312 len1 = missing_bytes;
2313 } if (nblk == 2 && len1 + len2 > missing_bytes)
2314 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 }
2316
2317 len = len1;
2318
2319 luaL_addlstring(&socket->b, blk1, len1);
2320 if (nblk == 2) {
2321 len += len2;
2322 luaL_addlstring(&socket->b, blk2, len2);
2323 }
2324
2325 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002326 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327
2328 /* Don't wait anything. */
Christopher Faulet174144c2024-02-16 15:33:44 +01002329 si_want_get(si);
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002330 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331
2332 /* If the pattern reclaim to read all the data
2333 * in the connection, got out.
2334 */
2335 if (wanted == HLSR_READ_ALL)
2336 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002337 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002338 goto connection_empty;
2339
2340 /* Return result. */
2341 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002342 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343 return 1;
2344
2345connection_closed:
2346
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002347 xref_unlock(&socket->xref, peer);
2348
2349no_peer:
2350
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351 /* If the buffer containds data. */
2352 if (socket->b.n > 0) {
2353 luaL_pushresult(&socket->b);
2354 return 1;
2355 }
2356 lua_pushnil(L);
2357 lua_pushstring(L, "connection closed.");
2358 return 2;
2359
2360connection_empty:
2361
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002362 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
2363 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002364 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002365 }
2366 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002367 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002368 return 0;
2369}
2370
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002371/* This Lua function gets two parameters. The first one can be string
2372 * or a number. If the string is "*l", the user requires one line. If
2373 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374 * If the value is a number, the user require a number of bytes equal
2375 * to the value. The default value is "*l" (a line).
2376 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002377 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378 * integer takes this values:
2379 * -1 : read a line
2380 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002381 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002382 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002383 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384 * concatenated with the read data.
2385 */
2386__LJMP static int hlua_socket_receive(struct lua_State *L)
2387{
2388 int wanted = HLSR_READ_LINE;
2389 const char *pattern;
Christopher Fauletc31b2002021-05-03 10:11:13 +02002390 int lastarg, type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002391 char *error;
2392 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002393 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394
2395 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2396 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2397
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002398 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002400 /* Check if we run on the same thread than the xreator thread.
2401 * We cannot access to the socket if the thread is different.
2402 */
2403 if (socket->tid != tid)
2404 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2405
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002406 /* check for pattern. */
2407 if (lua_gettop(L) >= 2) {
2408 type = lua_type(L, 2);
2409 if (type == LUA_TSTRING) {
2410 pattern = lua_tostring(L, 2);
2411 if (strcmp(pattern, "*a") == 0)
2412 wanted = HLSR_READ_ALL;
2413 else if (strcmp(pattern, "*l") == 0)
2414 wanted = HLSR_READ_LINE;
2415 else {
2416 wanted = strtoll(pattern, &error, 10);
2417 if (*error != '\0')
2418 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2419 }
2420 }
2421 else if (type == LUA_TNUMBER) {
2422 wanted = lua_tointeger(L, 2);
2423 if (wanted < 0)
2424 WILL_LJMP(luaL_error(L, "Unsupported size."));
2425 }
2426 }
2427
2428 /* Set pattern. */
2429 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002430
2431 /* Check if we would replace the top by itself. */
2432 if (lua_gettop(L) != 2)
2433 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002434
Christopher Fauletc31b2002021-05-03 10:11:13 +02002435 /* Save index of the top of the stack because since buffers are used, it
2436 * may change
2437 */
2438 lastarg = lua_gettop(L);
2439
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002440 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002441 luaL_buffinit(L, &socket->b);
2442
2443 /* Check prefix. */
Christopher Fauletc31b2002021-05-03 10:11:13 +02002444 if (lastarg >= 3) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002445 if (lua_type(L, 3) != LUA_TSTRING)
2446 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2447 pattern = lua_tolstring(L, 3, &len);
2448 luaL_addlstring(&socket->b, pattern, len);
2449 }
2450
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002451 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002452}
2453
2454/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002455 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002456 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002457static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002458{
2459 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002460 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002461 struct appctx *appctx;
2462 size_t buf_len;
2463 const char *buf;
2464 int len;
2465 int send_len;
2466 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002467 struct xref *peer;
2468 struct stream_interface *si;
2469 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002471 /* Get hlua struct, or NULL if we execute from main lua state */
2472 hlua = hlua_gethlua(L);
2473
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474 /* Check if this lua stack is schedulable. */
2475 if (!hlua || !hlua->task)
2476 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2477 "'frontend', 'backend' or 'task'"));
2478
2479 /* Get object */
2480 socket = MAY_LJMP(hlua_checksocket(L, 1));
2481 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002482 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002483
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002484 /* Check if we run on the same thread than the xreator thread.
2485 * We cannot access to the socket if the thread is different.
2486 */
2487 if (socket->tid != tid)
2488 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2489
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002490 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002491 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002492 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002493 lua_pushinteger(L, -1);
2494 return 1;
2495 }
2496 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2497 si = appctx->owner;
2498 s = si_strm(si);
2499
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002501 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002502 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002503 lua_pushinteger(L, -1);
2504 return 1;
2505 }
2506
2507 /* Update the input buffer data. */
2508 buf += sent;
2509 send_len = buf_len - sent;
2510
2511 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002512 if (sent >= buf_len) {
2513 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002514 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002515 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002516
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002517 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002518 * the request buffer if its not required.
2519 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002520 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002521 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002522 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002523 }
2524
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002525 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002526 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002527 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002528 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002529 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002530
2531 /* send data */
2532 if (len < send_len)
2533 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002534 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002535
2536 /* "Not enough space" (-1), "Buffer too little to contain
2537 * the data" (-2) are not expected because the available length
2538 * is tested.
2539 * Other unknown error are also not expected.
2540 */
2541 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002542 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002543 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002544
sada05ed3302018-05-11 11:48:18 -07002545 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002546 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002547 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002548 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002549 return 1;
2550 }
2551
2552 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002553 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002554
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002555 s->req.rex = TICK_ETERNITY;
2556 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002557
2558 /* Update length sent. */
2559 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002560 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002561
2562 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002563 if (sent + len >= buf_len) {
2564 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002565 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002566 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002567
2568hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002569 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2570 xref_unlock(&socket->xref, peer);
2571 WILL_LJMP(luaL_error(L, "out of memory"));
2572 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002573 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002574 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575 return 0;
2576}
2577
2578/* This function initiate the send of data. It just check the input
2579 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002580 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002581 * "hlua_socket_write_yield" that can yield.
2582 *
2583 * The Lua function gets between 3 and 4 parameters. The first one is
2584 * the associated object. The second is a string buffer. The third is
2585 * a facultative integer that represents where is the buffer position
2586 * of the start of the data that can send. The first byte is the
2587 * position "1". The default value is "1". The fourth argument is a
2588 * facultative integer that represents where is the buffer position
2589 * of the end of the data that can send. The default is the last byte.
2590 */
2591static int hlua_socket_send(struct lua_State *L)
2592{
2593 int i;
2594 int j;
2595 const char *buf;
2596 size_t buf_len;
2597
2598 /* Check number of arguments. */
2599 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2600 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2601
2602 /* Get the string. */
2603 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2604
2605 /* Get and check j. */
2606 if (lua_gettop(L) == 4) {
2607 j = MAY_LJMP(luaL_checkinteger(L, 4));
2608 if (j < 0)
2609 j = buf_len + j + 1;
2610 if (j > buf_len)
2611 j = buf_len + 1;
2612 lua_pop(L, 1);
2613 }
2614 else
2615 j = buf_len;
2616
2617 /* Get and check i. */
2618 if (lua_gettop(L) == 3) {
2619 i = MAY_LJMP(luaL_checkinteger(L, 3));
2620 if (i < 0)
2621 i = buf_len + i + 1;
2622 if (i > buf_len)
2623 i = buf_len + 1;
2624 lua_pop(L, 1);
2625 } else
2626 i = 1;
2627
2628 /* Check bth i and j. */
2629 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002630 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002631 return 1;
2632 }
2633 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002634 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002635 return 1;
2636 }
2637 if (i == 0)
2638 i = 1;
2639 if (j == 0)
2640 j = 1;
2641
2642 /* Pop the string. */
2643 lua_pop(L, 1);
2644
2645 /* Update the buffer length. */
2646 buf += i - 1;
2647 buf_len = j - i + 1;
2648 lua_pushlstring(L, buf, buf_len);
2649
2650 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002651 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002652
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002653 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002654}
2655
Willy Tarreau22b0a682015-06-17 19:43:49 +02002656#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002657__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2658{
2659 static char buffer[SOCKET_INFO_MAX_LEN];
2660 int ret;
2661 int len;
2662 char *p;
2663
2664 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2665 if (ret <= 0) {
2666 lua_pushnil(L);
2667 return 1;
2668 }
2669
2670 if (ret == AF_UNIX) {
2671 lua_pushstring(L, buffer+1);
2672 return 1;
2673 }
2674 else if (ret == AF_INET6) {
2675 buffer[0] = '[';
2676 len = strlen(buffer);
2677 buffer[len] = ']';
2678 len++;
2679 buffer[len] = ':';
2680 len++;
2681 p = buffer;
2682 }
2683 else if (ret == AF_INET) {
2684 p = buffer + 1;
2685 len = strlen(p);
2686 p[len] = ':';
2687 len++;
2688 }
2689 else {
2690 lua_pushnil(L);
2691 return 1;
2692 }
2693
2694 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2695 lua_pushnil(L);
2696 return 1;
2697 }
2698
2699 lua_pushstring(L, p);
2700 return 1;
2701}
2702
2703/* Returns information about the peer of the connection. */
2704__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2705{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002706 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002707 struct xref *peer;
2708 struct appctx *appctx;
2709 struct stream_interface *si;
2710 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002711 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002712
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002713 MAY_LJMP(check_args(L, 1, "getpeername"));
2714
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002715 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002716
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002717 /* Check if we run on the same thread than the xreator thread.
2718 * We cannot access to the socket if the thread is different.
2719 */
2720 if (socket->tid != tid)
2721 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2722
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002723 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002724 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002725 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002726 lua_pushnil(L);
2727 return 1;
2728 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002729 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2730 si = appctx->owner;
2731 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002732
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002733 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002734 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002735 lua_pushnil(L);
2736 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002737 }
2738
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002739 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002740 xref_unlock(&socket->xref, peer);
2741 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002742}
2743
2744/* Returns information about my connection side. */
2745static int hlua_socket_getsockname(struct lua_State *L)
2746{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002747 struct hlua_socket *socket;
2748 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002749 struct appctx *appctx;
2750 struct xref *peer;
2751 struct stream_interface *si;
2752 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002753 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002754
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002755 MAY_LJMP(check_args(L, 1, "getsockname"));
2756
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002757 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002758
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002759 /* Check if we run on the same thread than the xreator thread.
2760 * We cannot access to the socket if the thread is different.
2761 */
2762 if (socket->tid != tid)
2763 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2764
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002765 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002766 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002767 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002768 lua_pushnil(L);
2769 return 1;
2770 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002771 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2772 si = appctx->owner;
2773 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002774
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002775 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002776 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002777 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002778 lua_pushnil(L);
2779 return 1;
2780 }
2781
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002782 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002783 xref_unlock(&socket->xref, peer);
2784 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002785}
2786
2787/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002788static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002789 .obj_type = OBJ_TYPE_APPLET,
2790 .name = "<LUA_TCP>",
2791 .fct = hlua_socket_handler,
2792 .release = hlua_socket_release,
2793};
2794
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002795__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002796{
2797 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002798 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002799 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002800 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002801 struct stream_interface *si;
2802 struct stream *s;
2803
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002804 /* Get hlua struct, or NULL if we execute from main lua state */
2805 hlua = hlua_gethlua(L);
2806 if (!hlua)
2807 return 0;
2808
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002809 /* Check if we run on the same thread than the xreator thread.
2810 * We cannot access to the socket if the thread is different.
2811 */
2812 if (socket->tid != tid)
2813 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2814
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002815 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002816 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002817 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002818 lua_pushnil(L);
2819 lua_pushstring(L, "Can't connect");
2820 return 2;
2821 }
2822 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2823 si = appctx->owner;
2824 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002825
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002826 /* Check if we run on the same thread than the xreator thread.
2827 * We cannot access to the socket if the thread is different.
2828 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002829 if (socket->tid != tid) {
2830 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002831 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002832 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002833
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002834 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002835 if (!hlua || channel_output_closed(&s->req)) {
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 lua_pushstring(L, "Can't connect");
2839 return 2;
2840 }
2841
Willy Tarreaue09101e2018-10-16 17:37:12 +02002842 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002843
2844 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002845 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002846 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002847 lua_pushinteger(L, 1);
2848 return 1;
2849 }
2850
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002851 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2852 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002853 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002854 }
2855 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002856 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002857 return 0;
2858}
2859
2860/* This function fail or initite the connection. */
2861__LJMP static int hlua_socket_connect(struct lua_State *L)
2862{
2863 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002864 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002865 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002866 struct hlua *hlua;
2867 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002868 int low, high;
2869 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002870 struct xref *peer;
2871 struct stream_interface *si;
2872 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002873
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002874 if (lua_gettop(L) < 2)
2875 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002876
2877 /* Get args. */
2878 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002879
2880 /* Check if we run on the same thread than the xreator thread.
2881 * We cannot access to the socket if the thread is different.
2882 */
2883 if (socket->tid != tid)
2884 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2885
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002886 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002887 if (lua_gettop(L) >= 3) {
2888 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002889 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002890
Tim Duesterhus6edab862018-01-06 19:04:45 +01002891 /* Force the ip to end with a colon, to support IPv6 addresses
2892 * that are not enclosed within square brackets.
2893 */
2894 if (port > 0) {
2895 luaL_buffinit(L, &b);
2896 luaL_addstring(&b, ip);
2897 luaL_addchar(&b, ':');
2898 luaL_pushresult(&b);
2899 ip = lua_tolstring(L, lua_gettop(L), NULL);
2900 }
2901 }
2902
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002903 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002904 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002905 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002906 lua_pushnil(L);
2907 return 1;
2908 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002909
2910 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002911 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 +02002912 if (!addr) {
2913 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002914 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002915 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002916
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002917 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002918 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002919 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002920 if (port == -1) {
2921 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002922 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002923 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002924 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2925 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002926 if (port == -1) {
2927 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002928 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002929 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002930 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002931 }
2932 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002933
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002934 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2935 si = appctx->owner;
2936 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002937
Willy Tarreau9b7587a2020-10-15 07:32:10 +02002938 if (!sockaddr_alloc(&s->target_addr, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002939 xref_unlock(&socket->xref, peer);
2940 WILL_LJMP(luaL_error(L, "connect: internal error"));
2941 }
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002942 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002943
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002944 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002945 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002946 if (!hlua)
2947 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002948
2949 /* inform the stream that we want to be notified whenever the
2950 * connection completes.
2951 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002952 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002953 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002954 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002955
Willy Tarreauf31af932020-01-14 09:59:38 +01002956 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002957
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002958 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2959 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002960 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002961 }
2962 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002963
2964 task_wakeup(s->task, TASK_WOKEN_INIT);
2965 /* Return yield waiting for connection. */
2966
Willy Tarreau9635e032018-10-16 17:52:55 +02002967 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002968
2969 return 0;
2970}
2971
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002972#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002973__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2974{
2975 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002976 struct xref *peer;
2977 struct appctx *appctx;
2978 struct stream_interface *si;
2979 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002980
2981 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2982 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002983
2984 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002985 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002986 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002987 lua_pushnil(L);
2988 return 1;
2989 }
2990 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2991 si = appctx->owner;
2992 s = si_strm(si);
2993
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002994 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002995 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002996 return MAY_LJMP(hlua_socket_connect(L));
2997}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002998#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002999
3000__LJMP static int hlua_socket_setoption(struct lua_State *L)
3001{
3002 return 0;
3003}
3004
3005__LJMP static int hlua_socket_settimeout(struct lua_State *L)
3006{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003007 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003008 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02003009 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003010 struct xref *peer;
3011 struct appctx *appctx;
3012 struct stream_interface *si;
3013 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003014
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003015 MAY_LJMP(check_args(L, 2, "settimeout"));
3016
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003017 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02003018
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003019 /* convert the timeout to millis */
3020 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003021
Thierry Fournier17a921b2018-03-08 09:59:02 +01003022 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02003023 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01003024 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
3025
Mark Lakes56cc1252018-03-27 09:48:06 +02003026 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003027 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02003028
3029 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02003030 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003031 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02003032
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003033 /* Check if we run on the same thread than the xreator thread.
3034 * We cannot access to the socket if the thread is different.
3035 */
3036 if (socket->tid != tid)
3037 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
3038
Mark Lakes56cc1252018-03-27 09:48:06 +02003039 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003040 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003041 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003042 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
3043 WILL_LJMP(lua_error(L));
3044 return 0;
3045 }
3046 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
3047 si = appctx->owner;
3048 s = si_strm(si);
3049
Cyril Bonté7bb63452018-08-17 23:51:02 +02003050 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003051 s->req.rto = tmout;
3052 s->req.wto = tmout;
3053 s->res.rto = tmout;
3054 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02003055 s->req.rex = tick_add_ifset(now_ms, tmout);
3056 s->req.wex = tick_add_ifset(now_ms, tmout);
3057 s->res.rex = tick_add_ifset(now_ms, tmout);
3058 s->res.wex = tick_add_ifset(now_ms, tmout);
3059
3060 s->task->expire = tick_add_ifset(now_ms, tmout);
3061 task_queue(s->task);
3062
Thierry FOURNIER952939d2017-09-01 14:17:32 +02003063 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003064
Thierry Fourniere9636f12018-03-08 09:54:32 +01003065 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01003066 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003067}
3068
3069__LJMP static int hlua_socket_new(lua_State *L)
3070{
3071 struct hlua_socket *socket;
3072 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02003073 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003074 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003075
3076 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003077 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003078 hlua_pusherror(L, "socket: full stack");
3079 goto out_fail_conf;
3080 }
3081
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003082 /* Create the object: obj[0] = userdata. */
3083 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003084 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003085 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003086 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02003087 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003088
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003089 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01003090 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01003091 hlua_pusherror(L, "socket: uninitialized pools.");
3092 goto out_fail_conf;
3093 }
3094
Willy Tarreau87b09662015-04-03 00:22:06 +02003095 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003096 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
3097 lua_setmetatable(L, -2);
3098
Willy Tarreaud420a972015-04-06 00:39:18 +02003099 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01003100 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003101 if (!appctx) {
3102 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02003103 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003104 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003105
Thierry FOURNIER18d09902016-12-16 09:25:38 +01003106 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02003107 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01003108 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
3109 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02003110
Willy Tarreaud420a972015-04-06 00:39:18 +02003111 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01003112 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02003113 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003114 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02003115 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003116 }
3117
Christopher Faulet26256f82020-09-14 11:40:13 +02003118 strm = stream_new(sess, &appctx->obj_type, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003119 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003120 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02003121 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003122 }
3123
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02003124 /* Initialise cross reference between stream and Lua socket object. */
3125 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003126
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003127 /* Configure "right" stream interface. this "si" is used to connect
3128 * and retrieve data from the server. The connection is initialized
3129 * with the "struct server".
3130 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02003131 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003132
3133 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02003134 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01003135 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003136
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003137 return 1;
3138
Willy Tarreaud420a972015-04-06 00:39:18 +02003139 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02003140 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02003141 out_fail_sess:
3142 appctx_free(appctx);
3143 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003144 WILL_LJMP(lua_error(L));
3145 return 0;
3146}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003147
3148/*
3149 *
3150 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003151 * Class Channel
3152 *
3153 *
3154 */
3155
3156/* Returns the struct hlua_channel join to the class channel in the
3157 * stack entry "ud" or throws an argument error.
3158 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003159__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003160{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003161 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003162}
3163
Willy Tarreau47860ed2015-03-10 14:07:50 +01003164/* Pushes the channel onto the top of the stack. If the stask does not have a
3165 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003166 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01003167static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003168{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003169 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003170 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003171 return 0;
3172
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003173 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003174 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003175 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003176
3177 /* Pop a class sesison metatable and affect it to the userdata. */
3178 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
3179 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003180 return 1;
3181}
3182
3183/* Duplicate all the data present in the input channel and put it
3184 * in a string LUA variables. Returns -1 and push a nil value in
3185 * the stack if the channel is closed and all the data are consumed,
3186 * returns 0 if no data are available, otherwise it returns the length
Ilya Shipitsind4259502020-04-08 01:07:56 +05003187 * of the built string.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003188 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003189static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003190{
3191 char *blk1;
3192 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003193 size_t len1;
3194 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003195 int ret;
3196 luaL_Buffer b;
3197
Willy Tarreau06d80a92017-10-19 14:32:15 +02003198 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Christopher Faulet055310f2021-08-05 11:58:37 +02003199 if (unlikely(ret <= 0)) {
3200 if (ret < 0 || HLUA_CANT_YIELD(hlua_gethlua(L))) {
3201 lua_pushnil(L);
3202 return -1;
3203 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003204 return 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003205 }
3206
3207 luaL_buffinit(L, &b);
3208 luaL_addlstring(&b, blk1, len1);
3209 if (unlikely(ret == 2))
3210 luaL_addlstring(&b, blk2, len2);
3211 luaL_pushresult(&b);
3212
3213 if (unlikely(ret == 2))
3214 return len1 + len2;
3215 return len1;
3216}
3217
3218/* "_hlua_channel_dup" wrapper. If no data are available, it returns
3219 * a yield. This function keep the data in the buffer.
3220 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003221__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003222{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003223 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003224
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003225 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3226
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003227 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003228 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003229 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003230 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003231
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003232 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02003233 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003234 return 1;
3235}
3236
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003237/* Check arguments for the function "hlua_channel_dup_yield". */
3238__LJMP static int hlua_channel_dup(lua_State *L)
3239{
3240 MAY_LJMP(check_args(L, 1, "dup"));
3241 MAY_LJMP(hlua_checkchannel(L, 1));
3242 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
3243}
3244
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003245/* "_hlua_channel_dup" wrapper. If no data are available, it returns
3246 * a yield. This function consumes the data in the buffer. It returns
3247 * a string containing the data or a nil pointer if no data are available
3248 * and the channel is closed.
3249 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003250__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003251{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003252 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003253 int ret;
3254
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003255 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003256
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003257 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003258 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003259 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003260 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003261
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003262 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003263 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02003264 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003265
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003266 if (unlikely(ret == -1))
3267 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003268
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003269 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003270 return 1;
3271}
3272
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003273/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003274__LJMP static int hlua_channel_get(lua_State *L)
3275{
3276 MAY_LJMP(check_args(L, 1, "get"));
3277 MAY_LJMP(hlua_checkchannel(L, 1));
3278 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
3279}
3280
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003281/* This functions consumes and returns one line. If the channel is closed,
3282 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003283 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003284 * value.
3285 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003286__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003287{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003288 char *blk1;
3289 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003290 size_t len1;
3291 size_t len2;
3292 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01003293 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003294 int ret;
3295 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003296
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003297 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3298
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003299 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003300 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003301 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003302 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003303
Willy Tarreau06d80a92017-10-19 14:32:15 +02003304 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Christopher Faulet055310f2021-08-05 11:58:37 +02003305 if (ret == 0) {
3306 if (HLUA_CANT_YIELD(hlua_gethlua(L))) {
3307 _hlua_channel_dup(chn, L);
3308 return 1;
3309 }
Willy Tarreau9635e032018-10-16 17:52:55 +02003310 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet055310f2021-08-05 11:58:37 +02003311 }
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003312
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003313 if (ret == -1) {
3314 lua_pushnil(L);
3315 return 1;
3316 }
3317
3318 luaL_buffinit(L, &b);
3319 luaL_addlstring(&b, blk1, len1);
3320 len = len1;
3321 if (unlikely(ret == 2)) {
3322 luaL_addlstring(&b, blk2, len2);
3323 len += len2;
3324 }
3325 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003326 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003327 return 1;
3328}
3329
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003330/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003331__LJMP static int hlua_channel_getline(lua_State *L)
3332{
3333 MAY_LJMP(check_args(L, 1, "getline"));
3334 MAY_LJMP(hlua_checkchannel(L, 1));
3335 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3336}
3337
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003338/* This function takes a string as argument, and append it at the input side of
3339 * channel. If data cannot be copied, because there is not enough space to do so
3340 * or because the channel is closed, it returns -1. Otherwise, it returns the
3341 * amount of data written (the string length). This function does not yield.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003342 */
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003343__LJMP static int hlua_channel_append(lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003344{
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003345 struct channel *chn;
3346 const char *str;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003347 size_t len;
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003348
3349 MAY_LJMP(check_args(L, 2, "append"));
3350 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3351 str = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003352
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003353 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003354 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003355 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003356 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003357
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003358 if (len > c_room(chn) || ci_putblk(chn, str, len) < 0)
3359 lua_pushinteger(L, -1);
3360 else
3361 lua_pushinteger(L, len);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003362 return 1;
3363}
3364
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003365/* The function replaces input data from the channel by the string passed as
3366 * argument. Before clearing the buffer, we take care the copy will be
3367 * possible. It returns the amount of data written (the string length) on
3368 * success or -1 if the copy is not performed. This function does not yield.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003369 */
3370__LJMP static int hlua_channel_set(lua_State *L)
3371{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003372 struct channel *chn;
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003373 const char *str;
3374 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003375
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003376 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003377 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003378 str = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003379
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003380 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003381 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003382 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003383 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003384
Christopher Faulet3b7bc3e2021-08-06 09:59:49 +02003385 /* Be sure we can copied the string once input data will be removed. */
3386 if (len > ci_data(chn) || channel_input_closed(chn))
3387 lua_pushinteger(L, -1);
3388 else {
3389 b_set_data(&chn->buf, co_data(chn));
3390 if (ci_putblk(chn, str, len) < 0)
3391 lua_pushinteger(L, -1);
3392 else
3393 lua_pushinteger(L, len);
3394 }
3395 return -1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003396}
3397
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003398/* Append data in the output side of the buffer. This data is immediately
3399 * sent. The function returns the amount of data written. If the buffer
3400 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003401 * if the channel is closed.
3402 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003403__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003404{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003405 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003406 size_t len;
3407 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3408 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3409 int max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003410 struct hlua *hlua;
3411
3412 /* Get hlua struct, or NULL if we execute from main lua state */
3413 hlua = hlua_gethlua(L);
3414 if (!hlua) {
3415 lua_pushnil(L);
3416 return 1;
3417 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003418
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003419 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003420 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003421 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003422 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003423
Willy Tarreau47860ed2015-03-10 14:07:50 +01003424 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003425 lua_pushinteger(L, -1);
3426 return 1;
3427 }
3428
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003429 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003430 * the request buffer if its not required.
3431 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003432 if (chn->buf.size == 0) {
Christopher Faulet055310f2021-08-05 11:58:37 +02003433 if (HLUA_CANT_YIELD(hlua_gethlua(L)))
3434 return 1;
Willy Tarreau4b962a42018-11-15 11:03:21 +01003435 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003436 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003437 }
3438
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003439 /* The written data will be immediately sent, so we can check
3440 * the available space without taking in account the reserve.
3441 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003442 * data, because the buffer will be flushed.
3443 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003444 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003445
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003446 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003447 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003448 * we return the amount of copied data.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003449 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003450 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003451 return 1;
3452
3453 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003454 if (max > len - l)
3455 max = len - l;
3456
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003457 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003458 * detects a non contiguous buffer and realign it.
3459 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003460 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003461 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003462
3463 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003464 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003465
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003466 /* buffer replace considers that the input part is filled.
3467 * so, I must forward these new data in the output part.
3468 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003469 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003470
3471 l += max;
3472 lua_pop(L, 1);
3473 lua_pushinteger(L, l);
3474
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003475 if (l < len) {
Christopher Faulet055310f2021-08-05 11:58:37 +02003476 /* If there is no space available, and the output buffer is empty.
3477 * in this case, we cannot add more data, so we cannot yield,
3478 * we return the amount of copied data.
3479 */
3480 max = b_room(&chn->buf);
3481 if ((max == 0 && co_data(chn) == 0) || HLUA_CANT_YIELD(hlua_gethlua(L)))
3482 return 1;
3483
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003484 /* If we are waiting for space in the response buffer, we
3485 * must set the flag WAKERESWR. This flag required the task
3486 * wake up if any activity is detected on the response buffer.
3487 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003488 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003489 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003490 else
3491 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003492 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003493 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003494
3495 return 1;
3496}
3497
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003498/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003499 * yield the LUA process, and resume it without checking the
3500 * input arguments.
3501 */
3502__LJMP static int hlua_channel_send(lua_State *L)
3503{
3504 MAY_LJMP(check_args(L, 2, "send"));
3505 lua_pushinteger(L, 0);
3506
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003507 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003508}
3509
3510/* This function forward and amount of butes. The data pass from
3511 * the input side of the buffer to the output side, and can be
3512 * forwarded. This function never fails.
3513 *
3514 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003515 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003516 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003517__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003518{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003519 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003520 int len;
3521 int l;
3522 int max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003523 struct hlua *hlua;
3524
3525 /* Get hlua struct, or NULL if we execute from main lua state */
3526 hlua = hlua_gethlua(L);
3527 if (!hlua)
3528 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003529
3530 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003531
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003532 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003533 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003534 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003535 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003536
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003537 len = MAY_LJMP(luaL_checkinteger(L, 2));
3538 l = MAY_LJMP(luaL_checkinteger(L, -1));
3539
3540 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003541 if (max > ci_data(chn))
3542 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003543 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003544 l += max;
3545
3546 lua_pop(L, 1);
3547 lua_pushinteger(L, l);
3548
3549 /* Check if it miss bytes to forward. */
3550 if (l < len) {
3551 /* The the input channel or the output channel are closed, we
3552 * must return the amount of data forwarded.
3553 */
Christopher Faulet055310f2021-08-05 11:58:37 +02003554 if (channel_input_closed(chn) || channel_output_closed(chn) || HLUA_CANT_YIELD(hlua_gethlua(L)))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003555 return 1;
3556
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003557 /* If we are waiting for space data in the response buffer, we
3558 * must set the flag WAKERESWR. This flag required the task
3559 * wake up if any activity is detected on the response buffer.
3560 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003561 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003562 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003563 else
3564 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003565
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003566 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003567 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003568 }
3569
3570 return 1;
3571}
3572
3573/* Just check the input and prepare the stack for the previous
3574 * function "hlua_channel_forward_yield"
3575 */
3576__LJMP static int hlua_channel_forward(lua_State *L)
3577{
3578 MAY_LJMP(check_args(L, 2, "forward"));
3579 MAY_LJMP(hlua_checkchannel(L, 1));
3580 MAY_LJMP(luaL_checkinteger(L, 2));
3581
3582 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003583 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003584}
3585
3586/* Just returns the number of bytes available in the input
3587 * side of the buffer. This function never fails.
3588 */
3589__LJMP static int hlua_channel_get_in_len(lua_State *L)
3590{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003591 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003592
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003593 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003594 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003595 if (IS_HTX_STRM(chn_strm(chn))) {
3596 struct htx *htx = htxbuf(&chn->buf);
3597 lua_pushinteger(L, htx->data - co_data(chn));
3598 }
3599 else
3600 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003601 return 1;
3602}
3603
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003604/* Returns true if the channel is full. */
3605__LJMP static int hlua_channel_is_full(lua_State *L)
3606{
3607 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003608
3609 MAY_LJMP(check_args(L, 1, "is_full"));
3610 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003611 /* ignore the reserve, we are not on a producer side (ie in an
3612 * applet).
3613 */
3614 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003615 return 1;
3616}
3617
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003618/* Returns true if the channel is the response channel. */
3619__LJMP static int hlua_channel_is_resp(lua_State *L)
3620{
3621 struct channel *chn;
3622
3623 MAY_LJMP(check_args(L, 1, "is_resp"));
3624 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3625
3626 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3627 return 1;
3628}
3629
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003630/* Just returns the number of bytes available in the output
3631 * side of the buffer. This function never fails.
3632 */
3633__LJMP static int hlua_channel_get_out_len(lua_State *L)
3634{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003635 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003636
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003637 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003638 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003639 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003640 return 1;
3641}
3642
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003643/*
3644 *
3645 *
3646 * Class Fetches
3647 *
3648 *
3649 */
3650
3651/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003652 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003653 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003654__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003655{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003656 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003657}
3658
3659/* This function creates and push in the stack a fetch object according
3660 * with a current TXN.
3661 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003662static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003663{
Willy Tarreau7073c472015-04-06 11:15:40 +02003664 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003665
3666 /* Check stack size. */
3667 if (!lua_checkstack(L, 3))
3668 return 0;
3669
3670 /* Create the object: obj[0] = userdata.
3671 * Note that the base of the Fetches object is the
3672 * transaction object.
3673 */
3674 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003675 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003676 lua_rawseti(L, -2, 0);
3677
Willy Tarreau7073c472015-04-06 11:15:40 +02003678 hsmp->s = txn->s;
3679 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003680 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003681 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003682
3683 /* Pop a class sesison metatable and affect it to the userdata. */
3684 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3685 lua_setmetatable(L, -2);
3686
3687 return 1;
3688}
3689
3690/* This function is an LUA binding. It is called with each sample-fetch.
3691 * It uses closure argument to store the associated sample-fetch. It
3692 * returns only one argument or throws an error. An error is thrown
3693 * only if an error is encountered during the argument parsing. If
3694 * the "sample-fetch" function fails, nil is returned.
3695 */
3696__LJMP static int hlua_run_sample_fetch(lua_State *L)
3697{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003698 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003699 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003700 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003701 int i;
3702 struct sample smp;
3703
3704 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003705 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003706
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003707 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003708 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003709
Thierry FOURNIERca988662015-12-20 18:43:03 +01003710 /* Check execution authorization. */
3711 if (f->use & SMP_USE_HTTP_ANY &&
3712 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3713 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3714 "is not available in Lua services", f->kw);
3715 WILL_LJMP(lua_error(L));
3716 }
3717
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003718 /* Get extra arguments. */
3719 for (i = 0; i < lua_gettop(L) - 1; i++) {
3720 if (i >= ARGM_NBARGS)
3721 break;
3722 hlua_lua2arg(L, i + 2, &args[i]);
3723 }
3724 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003725 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003726
3727 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003728 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003729
3730 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003731 if (f->val_args && !f->val_args(args, NULL)) {
Aurelien DARRAGON159136c2024-06-03 23:18:24 +02003732 hlua_pushfstring_safe(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003733 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003734 }
3735
3736 /* Initialise the sample. */
3737 memset(&smp, 0, sizeof(smp));
3738
3739 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003740 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003741 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003742 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003743 lua_pushstring(L, "");
3744 else
3745 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003746 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003747 }
3748
3749 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003750 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003751 hlua_smp2lua_str(L, &smp);
3752 else
3753 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003754
3755 end:
3756 for (i = 0; args[i].type != ARGT_STOP; i++) {
3757 if (args[i].type == ARGT_STR)
3758 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003759 else if (args[i].type == ARGT_REG)
3760 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003761 }
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003762 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003763
3764 error:
3765 for (i = 0; args[i].type != ARGT_STOP; i++) {
3766 if (args[i].type == ARGT_STR)
3767 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003768 else if (args[i].type == ARGT_REG)
3769 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003770 }
3771 WILL_LJMP(lua_error(L));
3772 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003773}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003774
3775/*
3776 *
3777 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003778 * Class Converters
3779 *
3780 *
3781 */
3782
3783/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003784 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003785 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003786__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003787{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003788 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003789}
3790
3791/* This function creates and push in the stack a Converters object
3792 * according with a current TXN.
3793 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003794static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003795{
Willy Tarreau7073c472015-04-06 11:15:40 +02003796 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003797
3798 /* Check stack size. */
3799 if (!lua_checkstack(L, 3))
3800 return 0;
3801
3802 /* Create the object: obj[0] = userdata.
3803 * Note that the base of the Converters object is the
3804 * same than the TXN object.
3805 */
3806 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003807 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003808 lua_rawseti(L, -2, 0);
3809
Willy Tarreau7073c472015-04-06 11:15:40 +02003810 hsmp->s = txn->s;
3811 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003812 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003813 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003814
Willy Tarreau87b09662015-04-03 00:22:06 +02003815 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003816 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3817 lua_setmetatable(L, -2);
3818
3819 return 1;
3820}
3821
3822/* This function is an LUA binding. It is called with each converter.
3823 * It uses closure argument to store the associated converter. It
3824 * returns only one argument or throws an error. An error is thrown
3825 * only if an error is encountered during the argument parsing. If
3826 * the converter function function fails, nil is returned.
3827 */
3828__LJMP static int hlua_run_sample_conv(lua_State *L)
3829{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003830 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003831 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003832 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003833 int i;
3834 struct sample smp;
3835
3836 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003837 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003838
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003839 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003840 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003841
3842 /* Get extra arguments. */
3843 for (i = 0; i < lua_gettop(L) - 2; i++) {
3844 if (i >= ARGM_NBARGS)
3845 break;
3846 hlua_lua2arg(L, i + 3, &args[i]);
3847 }
3848 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003849 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003850
3851 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003852 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003853
3854 /* Run the special args checker. */
3855 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3856 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003857 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003858 }
3859
3860 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01003861 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003862 if (!hlua_lua2smp(L, 2, &smp)) {
3863 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003864 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003865 }
3866
Willy Tarreau1777ea62016-03-10 16:15:46 +01003867 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3868
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003869 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003870 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003871 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003872 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003873 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003874 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003875 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3876 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003877 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003878 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003879 }
3880
3881 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003882 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003883 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003884 lua_pushstring(L, "");
3885 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003886 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003887 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003888 }
3889
3890 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003891 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003892 hlua_smp2lua_str(L, &smp);
3893 else
3894 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003895 end:
3896 for (i = 0; args[i].type != ARGT_STOP; i++) {
3897 if (args[i].type == ARGT_STR)
3898 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003899 else if (args[i].type == ARGT_REG)
3900 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003901 }
Willy Tarreaua678b432015-08-28 10:14:59 +02003902 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003903
3904 error:
3905 for (i = 0; args[i].type != ARGT_STOP; i++) {
3906 if (args[i].type == ARGT_STR)
3907 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003908 else if (args[i].type == ARGT_REG)
3909 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003910 }
3911 WILL_LJMP(lua_error(L));
3912 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003913}
3914
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003915/*
3916 *
3917 *
3918 * Class AppletTCP
3919 *
3920 *
3921 */
3922
3923/* Returns a struct hlua_txn if the stack entry "ud" is
3924 * a class stream, otherwise it throws an error.
3925 */
3926__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3927{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003928 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003929}
3930
3931/* This function creates and push in the stack an Applet object
3932 * according with a current TXN.
3933 */
3934static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3935{
Willy Tarreau7e702d12021-04-28 17:59:21 +02003936 struct hlua_appctx *luactx;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003937 struct stream_interface *si = ctx->owner;
3938 struct stream *s = si_strm(si);
3939 struct proxy *p = s->be;
3940
3941 /* Check stack size. */
3942 if (!lua_checkstack(L, 3))
3943 return 0;
3944
3945 /* Create the object: obj[0] = userdata.
3946 * Note that the base of the Converters object is the
3947 * same than the TXN object.
3948 */
3949 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02003950 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003951 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02003952 luactx->appctx = ctx;
3953 luactx->htxn.s = s;
3954 luactx->htxn.p = p;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003955
3956 /* Create the "f" field that contains a list of fetches. */
3957 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02003958 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003959 return 0;
3960 lua_settable(L, -3);
3961
3962 /* Create the "sf" field that contains a list of stringsafe fetches. */
3963 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02003964 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003965 return 0;
3966 lua_settable(L, -3);
3967
3968 /* Create the "c" field that contains a list of converters. */
3969 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02003970 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003971 return 0;
3972 lua_settable(L, -3);
3973
3974 /* Create the "sc" field that contains a list of stringsafe converters. */
3975 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02003976 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003977 return 0;
3978 lua_settable(L, -3);
3979
3980 /* Pop a class stream metatable and affect it to the table. */
3981 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3982 lua_setmetatable(L, -2);
3983
3984 return 1;
3985}
3986
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003987__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3988{
Willy Tarreau7e702d12021-04-28 17:59:21 +02003989 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003990 struct stream *s;
3991 const char *name;
3992 size_t len;
3993 struct sample smp;
3994
Tim Duesterhus4e172c92020-05-19 13:49:42 +02003995 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
3996 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003997
3998 /* It is useles to retrieve the stream, but this function
3999 * runs only in a stream context.
4000 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004001 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004002 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004003 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004004
4005 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004006 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004007 hlua_lua2smp(L, 3, &smp);
4008
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02004009 /* Store the sample in a variable. We don't need to dup the smp, vars API
4010 * already takes care of duplicating dynamic var data.
4011 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004012 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004013
4014 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4015 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4016 else
4017 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4018
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004019 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004020}
4021
4022__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
4023{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004024 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004025 struct stream *s;
4026 const char *name;
4027 size_t len;
4028 struct sample smp;
4029
4030 MAY_LJMP(check_args(L, 2, "unset_var"));
4031
4032 /* It is useles to retrieve the stream, but this function
4033 * runs only in a stream context.
4034 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004035 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004036 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004037 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004038
4039 /* Unset the variable. */
4040 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004041 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4042 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004043}
4044
4045__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
4046{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004047 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004048 struct stream *s;
4049 const char *name;
4050 size_t len;
4051 struct sample smp;
4052
4053 MAY_LJMP(check_args(L, 2, "get_var"));
4054
4055 /* It is useles to retrieve the stream, but this function
4056 * runs only in a stream context.
4057 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004058 luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004059 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004060 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004061
4062 smp_set_owner(&smp, s->be, s->sess, s, 0);
4063 if (!vars_get_by_name(name, len, &smp)) {
4064 lua_pushnil(L);
4065 return 1;
4066 }
4067
4068 return hlua_smp2lua(L, &smp);
4069}
4070
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004071__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
4072{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004073 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4074 struct stream *s = luactx->htxn.s;
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01004075 struct hlua *hlua = hlua_stream_ctx_get(s, luactx->appctx->ctx.hlua_apptcp.hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004076
4077 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01004078 if (!hlua)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004079 return 0;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004080
4081 MAY_LJMP(check_args(L, 2, "set_priv"));
4082
4083 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004084 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004085
4086 /* Get and store new value. */
4087 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4088 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4089
4090 return 0;
4091}
4092
4093__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
4094{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004095 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4096 struct stream *s = luactx->htxn.s;
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01004097 struct hlua *hlua = hlua_stream_ctx_get(s, luactx->appctx->ctx.hlua_apptcp.hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004098
4099 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01004100 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004101 lua_pushnil(L);
4102 return 1;
4103 }
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004104
4105 /* Push configuration index in the stack. */
4106 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4107
4108 return 1;
4109}
4110
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004111/* If expected data not yet available, it returns a yield. This function
4112 * consumes the data in the buffer. It returns a string containing the
4113 * data. This string can be empty.
4114 */
4115__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
4116{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004117 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4118 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004119 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004120 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004121 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004122 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004123 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004124
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004125 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004126 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004127
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004128 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004129 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004130 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004131 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004132 }
4133
4134 /* End of data: commit the total strings and return. */
4135 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004136 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004137 return 1;
4138 }
4139
4140 /* Ensure that the block 2 length is usable. */
4141 if (ret == 1)
4142 len2 = 0;
4143
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004144 /* don't check the max length read and don't check. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004145 luaL_addlstring(&luactx->b, blk1, len1);
4146 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004147
4148 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004149 co_skip(si_oc(si), len1 + len2);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004150 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004151 return 1;
4152}
4153
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004154/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004155__LJMP static int hlua_applet_tcp_getline(lua_State *L)
4156{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004157 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004158
4159 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004160 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004161
4162 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
4163}
4164
4165/* If expected data not yet available, it returns a yield. This function
4166 * consumes the data in the buffer. It returns a string containing the
4167 * data. This string can be empty.
4168 */
4169__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
4170{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004171 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4172 struct stream_interface *si = luactx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004173 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004174 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004175 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004176 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004177 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004178 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004179
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004180 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004181 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004182
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004183 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004184 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004185 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004186 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004187 }
4188
4189 /* End of data: commit the total strings and return. */
4190 if (ret < 0) {
Willy Tarreau7e702d12021-04-28 17:59:21 +02004191 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004192 return 1;
4193 }
4194
4195 /* Ensure that the block 2 length is usable. */
4196 if (ret == 1)
4197 len2 = 0;
4198
4199 if (len == -1) {
4200
4201 /* If len == -1, catenate all the data avalaile and
4202 * yield because we want to get all the data until
4203 * the end of data stream.
4204 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004205 luaL_addlstring(&luactx->b, blk1, len1);
4206 luaL_addlstring(&luactx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02004207 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004208 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004209 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004210
4211 } else {
4212
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004213 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004214 if (len1 > len)
4215 len1 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004216 luaL_addlstring(&luactx->b, blk1, len1);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004217 len -= len1;
4218
4219 /* Copy the second block. */
4220 if (len2 > len)
4221 len2 = len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004222 luaL_addlstring(&luactx->b, blk2, len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004223 len -= len2;
4224
4225 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004226 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004227
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004228 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004229 if (len > 0) {
4230 lua_pushinteger(L, len);
4231 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004232 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004233 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004234 }
4235
4236 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004237 luaL_pushresult(&luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004238 return 1;
4239 }
4240
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004241 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004242 hlua_pusherror(L, "Lua: internal error");
4243 WILL_LJMP(lua_error(L));
4244 return 0;
4245}
4246
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004247/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004248__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4249{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004250 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004251 int len = -1;
4252
4253 if (lua_gettop(L) > 2)
4254 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4255 if (lua_gettop(L) >= 2) {
4256 len = MAY_LJMP(luaL_checkinteger(L, 2));
4257 lua_pop(L, 1);
4258 }
4259
4260 /* Confirm or set the required length */
4261 lua_pushinteger(L, len);
4262
4263 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004264 luaL_buffinit(L, &luactx->b);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004265
4266 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4267}
4268
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004269/* Append data in the output side of the buffer. This data is immediately
4270 * sent. The function returns the amount of data written. If the buffer
4271 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004272 * if the channel is closed.
4273 */
4274__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4275{
4276 size_t len;
Willy Tarreau7e702d12021-04-28 17:59:21 +02004277 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004278 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4279 int l = MAY_LJMP(luaL_checkinteger(L, 3));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004280 struct stream_interface *si = luactx->appctx->owner;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004281 struct channel *chn = si_ic(si);
4282 int max;
4283
4284 /* Get the max amount of data which can write as input in the channel. */
4285 max = channel_recv_max(chn);
4286 if (max > (len - l))
4287 max = len - l;
4288
4289 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004290 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004291
4292 /* update counters. */
4293 l += max;
4294 lua_pop(L, 1);
4295 lua_pushinteger(L, l);
4296
4297 /* If some data is not send, declares the situation to the
4298 * applet, and returns a yield.
4299 */
4300 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004301 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004302 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004303 }
4304
4305 return 1;
4306}
4307
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004308/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004309 * yield the LUA process, and resume it without checking the
4310 * input arguments.
4311 */
4312__LJMP static int hlua_applet_tcp_send(lua_State *L)
4313{
4314 MAY_LJMP(check_args(L, 2, "send"));
4315 lua_pushinteger(L, 0);
4316
4317 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4318}
4319
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004320/*
4321 *
4322 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004323 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004324 *
4325 *
4326 */
4327
4328/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004329 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004330 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004331__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004332{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004333 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004334}
4335
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004336/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004337 * according with a current TXN.
4338 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004339static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004340{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004341 struct hlua_appctx *luactx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004342 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004343 struct stream_interface *si = ctx->owner;
4344 struct stream *s = si_strm(si);
4345 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004346 struct htx *htx;
4347 struct htx_blk *blk;
4348 struct htx_sl *sl;
4349 struct ist path;
4350 unsigned long long len = 0;
4351 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004352
4353 /* Check stack size. */
4354 if (!lua_checkstack(L, 3))
4355 return 0;
4356
4357 /* Create the object: obj[0] = userdata.
4358 * Note that the base of the Converters object is the
4359 * same than the TXN object.
4360 */
4361 lua_newtable(L);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004362 luactx = lua_newuserdata(L, sizeof(*luactx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004363 lua_rawseti(L, -2, 0);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004364 luactx->appctx = ctx;
4365 luactx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
4366 luactx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
4367 luactx->htxn.s = s;
4368 luactx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004369
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004370 /* Create the "f" field that contains a list of fetches. */
4371 lua_pushstring(L, "f");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004372 if (!hlua_fetches_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004373 return 0;
4374 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004375
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004376 /* Create the "sf" field that contains a list of stringsafe fetches. */
4377 lua_pushstring(L, "sf");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004378 if (!hlua_fetches_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004379 return 0;
4380 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004381
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004382 /* Create the "c" field that contains a list of converters. */
4383 lua_pushstring(L, "c");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004384 if (!hlua_converters_new(L, &luactx->htxn, 0))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004385 return 0;
4386 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004387
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004388 /* Create the "sc" field that contains a list of stringsafe converters. */
4389 lua_pushstring(L, "sc");
Willy Tarreau7e702d12021-04-28 17:59:21 +02004390 if (!hlua_converters_new(L, &luactx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004391 return 0;
4392 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004393
Christopher Fauleta2097962019-07-15 16:25:33 +02004394 htx = htxbuf(&s->req.buf);
4395 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004396 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004397 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004398
Christopher Fauleta2097962019-07-15 16:25:33 +02004399 /* Stores the request method. */
4400 lua_pushstring(L, "method");
4401 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4402 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004403
Christopher Fauleta2097962019-07-15 16:25:33 +02004404 /* Stores the http version. */
4405 lua_pushstring(L, "version");
4406 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4407 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004408
Christopher Fauleta2097962019-07-15 16:25:33 +02004409 /* creates an array of headers. hlua_http_get_headers() crates and push
4410 * the array on the top of the stack.
4411 */
4412 lua_pushstring(L, "headers");
4413 htxn.s = s;
4414 htxn.p = px;
4415 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004416 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004417 return 0;
4418 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004419
Christopher Fauleta2097962019-07-15 16:25:33 +02004420 path = http_get_path(htx_sl_req_uri(sl));
Tim Duesterhused526372020-03-05 17:56:33 +01004421 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004422 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004423
Christopher Fauleta2097962019-07-15 16:25:33 +02004424 p = path.ptr;
4425 end = path.ptr + path.len;
4426 q = p;
4427 while (q < end && *q != '?')
4428 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004429
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004430 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004431 lua_pushstring(L, "path");
4432 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004433 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004434
Christopher Fauleta2097962019-07-15 16:25:33 +02004435 /* Stores the query string. */
4436 lua_pushstring(L, "qs");
4437 if (*q == '?')
4438 q++;
4439 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004440 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004441 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004442
Christopher Fauleta2097962019-07-15 16:25:33 +02004443 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4444 struct htx_blk *blk = htx_get_blk(htx, pos);
4445 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004446
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004447 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004448 break;
4449 if (type == HTX_BLK_DATA)
4450 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004451 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004452 if (htx->extra != ULLONG_MAX)
4453 len += htx->extra;
4454
4455 /* Stores the request path. */
4456 lua_pushstring(L, "length");
4457 lua_pushinteger(L, len);
4458 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004459
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004460 /* Create an empty array of HTTP request headers. */
4461 lua_pushstring(L, "response");
4462 lua_newtable(L);
4463 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004464
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004465 /* Pop a class stream metatable and affect it to the table. */
4466 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4467 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004468
4469 return 1;
4470}
4471
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004472__LJMP static int hlua_applet_http_set_var(lua_State *L)
4473{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004474 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004475 struct stream *s;
4476 const char *name;
4477 size_t len;
4478 struct sample smp;
4479
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004480 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4481 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004482
4483 /* It is useles to retrieve the stream, but this function
4484 * runs only in a stream context.
4485 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004486 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004487 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004488 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004489
4490 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004491 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004492 hlua_lua2smp(L, 3, &smp);
4493
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02004494 /* Store the sample in a variable. We don't need to dup the smp, vars API
4495 * already takes care of duplicating dynamic var data.
4496 */
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004497 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004498
4499 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4500 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4501 else
4502 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4503
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004504 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004505}
4506
4507__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4508{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004509 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004510 struct stream *s;
4511 const char *name;
4512 size_t len;
4513 struct sample smp;
4514
4515 MAY_LJMP(check_args(L, 2, "unset_var"));
4516
4517 /* It is useles to retrieve the stream, but this function
4518 * runs only in a stream context.
4519 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004520 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004521 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004522 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004523
4524 /* Unset the variable. */
4525 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004526 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4527 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004528}
4529
4530__LJMP static int hlua_applet_http_get_var(lua_State *L)
4531{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004532 struct hlua_appctx *luactx;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004533 struct stream *s;
4534 const char *name;
4535 size_t len;
4536 struct sample smp;
4537
4538 MAY_LJMP(check_args(L, 2, "get_var"));
4539
4540 /* It is useles to retrieve the stream, but this function
4541 * runs only in a stream context.
4542 */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004543 luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004544 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Willy Tarreau7e702d12021-04-28 17:59:21 +02004545 s = luactx->htxn.s;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004546
4547 smp_set_owner(&smp, s->be, s->sess, s, 0);
4548 if (!vars_get_by_name(name, len, &smp)) {
4549 lua_pushnil(L);
4550 return 1;
4551 }
4552
4553 return hlua_smp2lua(L, &smp);
4554}
4555
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004556__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4557{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004558 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4559 struct stream *s = luactx->htxn.s;
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01004560 struct hlua *hlua = hlua_stream_ctx_get(s, luactx->appctx->ctx.hlua_apphttp.hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004561
4562 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01004563 if (!hlua)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004564 return 0;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004565
4566 MAY_LJMP(check_args(L, 2, "set_priv"));
4567
4568 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004569 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004570
4571 /* Get and store new value. */
4572 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4573 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4574
4575 return 0;
4576}
4577
4578__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4579{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004580 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4581 struct stream *s = luactx->htxn.s;
Aurelien DARRAGONbe7b7ab2024-03-12 17:05:54 +01004582 struct hlua *hlua = hlua_stream_ctx_get(s, luactx->appctx->ctx.hlua_apphttp.hlua->state_id);
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004583
4584 /* Note that this hlua struct is from the session and not from the applet. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01004585 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004586 lua_pushnil(L);
4587 return 1;
4588 }
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004589
4590 /* Push configuration index in the stack. */
4591 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4592
4593 return 1;
4594}
4595
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004596/* If expected data not yet available, it returns a yield. This function
4597 * consumes the data in the buffer. It returns a string containing the
4598 * data. This string can be empty.
4599 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004600__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004601{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004602 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4603 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004604 struct channel *req = si_oc(si);
4605 struct htx *htx;
4606 struct htx_blk *blk;
4607 size_t count;
4608 int stop = 0;
4609
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004610 htx = htx_from_buf(&req->buf);
4611 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004612 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004613
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004614 while (count && !stop && blk) {
4615 enum htx_blk_type type = htx_get_blk_type(blk);
4616 uint32_t sz = htx_get_blksz(blk);
4617 struct ist v;
4618 uint32_t vlen;
4619 char *nl;
4620
4621 vlen = sz;
4622 if (vlen > count) {
4623 if (type != HTX_BLK_DATA)
4624 break;
4625 vlen = count;
4626 }
4627
4628 switch (type) {
4629 case HTX_BLK_UNUSED:
4630 break;
4631
4632 case HTX_BLK_DATA:
4633 v = htx_get_blk_value(htx, blk);
4634 v.len = vlen;
4635 nl = istchr(v, '\n');
4636 if (nl != NULL) {
4637 stop = 1;
4638 vlen = nl - v.ptr + 1;
4639 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004640 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004641 break;
4642
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004643 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004644 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004645 stop = 1;
4646 break;
4647
4648 default:
4649 break;
4650 }
4651
4652 co_set_data(req, co_data(req) - vlen);
4653 count -= vlen;
4654 if (sz == vlen)
4655 blk = htx_remove_blk(htx, blk);
4656 else {
4657 htx_cut_data_blk(htx, blk, vlen);
4658 break;
4659 }
4660 }
4661
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004662 /* The message was fully consumed and no more data are expected
4663 * (EOM flag set).
4664 */
Christopher Fauleta5a25b12022-08-29 15:37:16 +02004665 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004666 stop = 1;
4667
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004668 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004669 if (!stop) {
4670 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004671 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004672 }
4673
4674 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004675 luaL_pushresult(&luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004676 return 1;
4677}
4678
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004679
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004680/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004681__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004682{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004683 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004684
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004685 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004686 luaL_buffinit(L, &luactx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004687
Christopher Fauleta2097962019-07-15 16:25:33 +02004688 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004689}
4690
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004691/* If expected data not yet available, it returns a yield. This function
4692 * consumes the data in the buffer. It returns a string containing the
4693 * data. This string can be empty.
4694 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004695__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004696{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004697 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4698 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004699 struct channel *req = si_oc(si);
4700 struct htx *htx;
4701 struct htx_blk *blk;
4702 size_t count;
4703 int len;
4704
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004705 htx = htx_from_buf(&req->buf);
4706 len = MAY_LJMP(luaL_checkinteger(L, 2));
4707 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004708 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004709 while (count && len && blk) {
4710 enum htx_blk_type type = htx_get_blk_type(blk);
4711 uint32_t sz = htx_get_blksz(blk);
4712 struct ist v;
4713 uint32_t vlen;
4714
4715 vlen = sz;
4716 if (len > 0 && vlen > len)
4717 vlen = len;
4718 if (vlen > count) {
4719 if (type != HTX_BLK_DATA)
4720 break;
4721 vlen = count;
4722 }
4723
4724 switch (type) {
4725 case HTX_BLK_UNUSED:
4726 break;
4727
4728 case HTX_BLK_DATA:
4729 v = htx_get_blk_value(htx, blk);
Willy Tarreau7e702d12021-04-28 17:59:21 +02004730 luaL_addlstring(&luactx->b, v.ptr, vlen);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004731 break;
4732
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004733 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004734 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004735 len = 0;
4736 break;
4737
4738 default:
4739 break;
4740 }
4741
4742 co_set_data(req, co_data(req) - vlen);
4743 count -= vlen;
4744 if (len > 0)
4745 len -= vlen;
4746 if (sz == vlen)
4747 blk = htx_remove_blk(htx, blk);
4748 else {
4749 htx_cut_data_blk(htx, blk, vlen);
4750 break;
4751 }
4752 }
4753
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004754 /* The message was fully consumed and no more data are expected
4755 * (EOM flag set).
4756 */
Christopher Fauleta5a25b12022-08-29 15:37:16 +02004757 if (htx_is_empty(htx) && (req->flags & CF_EOI))
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004758 len = 0;
4759
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004760 htx_to_buf(htx, &req->buf);
4761
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004762 /* If we are no other data available, yield waiting for new data. */
4763 if (len) {
4764 if (len > 0) {
4765 lua_pushinteger(L, len);
4766 lua_replace(L, 2);
4767 }
4768 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004769 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004770 }
4771
4772 /* return the result. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004773 luaL_pushresult(&luactx->b);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004774 return 1;
4775}
4776
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004777/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004778__LJMP static int hlua_applet_http_recv(lua_State *L)
4779{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004780 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004781 int len = -1;
4782
4783 /* Check arguments. */
4784 if (lua_gettop(L) > 2)
4785 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4786 if (lua_gettop(L) >= 2) {
4787 len = MAY_LJMP(luaL_checkinteger(L, 2));
4788 lua_pop(L, 1);
4789 }
4790
Christopher Fauleta2097962019-07-15 16:25:33 +02004791 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004792
Christopher Fauleta2097962019-07-15 16:25:33 +02004793 /* Initialise the string catenation. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004794 luaL_buffinit(L, &luactx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004795
Christopher Fauleta2097962019-07-15 16:25:33 +02004796 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004797}
4798
4799/* Append data in the output side of the buffer. This data is immediately
4800 * sent. The function returns the amount of data written. If the buffer
4801 * cannot contain the data, the function yields. The function returns -1
4802 * if the channel is closed.
4803 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004804__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004805{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004806 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4807 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004808 struct channel *res = si_ic(si);
4809 struct htx *htx = htx_from_buf(&res->buf);
4810 const char *data;
4811 size_t len;
4812 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4813 int max;
4814
Christopher Faulet9060fc02019-07-03 11:39:30 +02004815 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004816 if (!max)
4817 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004818
4819 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4820
4821 /* Get the max amount of data which can write as input in the channel. */
4822 if (max > (len - l))
4823 max = len - l;
4824
4825 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004826 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004827 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004828
4829 /* update counters. */
4830 l += max;
4831 lua_pop(L, 1);
4832 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004833
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004834 /* If some data is not send, declares the situation to the
4835 * applet, and returns a yield.
4836 */
4837 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004838 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004839 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004840 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004841 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004842 }
4843
Christopher Fauleta2097962019-07-15 16:25:33 +02004844 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004845 return 1;
4846}
4847
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004848/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004849 * yield the LUA process, and resume it without checking the
4850 * input arguments.
4851 */
4852__LJMP static int hlua_applet_http_send(lua_State *L)
4853{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004854 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004855
4856 /* We want to send some data. Headers must be sent. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004857 if (!(luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004858 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4859 WILL_LJMP(lua_error(L));
4860 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004861
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004862 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004863 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004864
Christopher Fauleta2097962019-07-15 16:25:33 +02004865 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004866}
4867
4868__LJMP static int hlua_applet_http_addheader(lua_State *L)
4869{
4870 const char *name;
4871 int ret;
4872
4873 MAY_LJMP(hlua_checkapplet_http(L, 1));
4874 name = MAY_LJMP(luaL_checkstring(L, 2));
4875 MAY_LJMP(luaL_checkstring(L, 3));
4876
4877 /* Push in the stack the "response" entry. */
4878 ret = lua_getfield(L, 1, "response");
4879 if (ret != LUA_TTABLE) {
4880 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4881 "is expected as an array. %s found", lua_typename(L, ret));
4882 WILL_LJMP(lua_error(L));
4883 }
4884
4885 /* check if the header is already registered if it is not
4886 * the case, register it.
4887 */
4888 ret = lua_getfield(L, -1, name);
4889 if (ret == LUA_TNIL) {
4890
4891 /* Entry not found. */
4892 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4893
4894 /* Insert the new header name in the array in the top of the stack.
4895 * It left the new array in the top of the stack.
4896 */
4897 lua_newtable(L);
4898 lua_pushvalue(L, 2);
4899 lua_pushvalue(L, -2);
4900 lua_settable(L, -4);
4901
4902 } else if (ret != LUA_TTABLE) {
4903
4904 /* corruption error. */
4905 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4906 "is expected as an array. %s found", name, lua_typename(L, ret));
4907 WILL_LJMP(lua_error(L));
4908 }
4909
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004910 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004911 * the header value as new entry.
4912 */
4913 lua_pushvalue(L, 3);
4914 ret = lua_rawlen(L, -2);
4915 lua_rawseti(L, -2, ret + 1);
4916 lua_pushboolean(L, 1);
4917 return 1;
4918}
4919
4920__LJMP static int hlua_applet_http_status(lua_State *L)
4921{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004922 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004923 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004924 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004925
4926 if (status < 100 || status > 599) {
4927 lua_pushboolean(L, 0);
4928 return 1;
4929 }
4930
Willy Tarreau7e702d12021-04-28 17:59:21 +02004931 luactx->appctx->ctx.hlua_apphttp.status = status;
4932 luactx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004933 lua_pushboolean(L, 1);
4934 return 1;
4935}
4936
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004937
Christopher Fauleta2097962019-07-15 16:25:33 +02004938__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004939{
Willy Tarreau7e702d12021-04-28 17:59:21 +02004940 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4941 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004942 struct channel *res = si_ic(si);
4943 struct htx *htx;
4944 struct htx_sl *sl;
4945 struct h1m h1m;
4946 const char *status, *reason;
4947 const char *name, *value;
4948 size_t nlen, vlen;
4949 unsigned int flags;
4950
4951 /* Send the message at once. */
4952 htx = htx_from_buf(&res->buf);
4953 h1m_init_res(&h1m);
4954
4955 /* Use the same http version than the request. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02004956 status = ultoa_r(luactx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4957 reason = luactx->appctx->ctx.hlua_apphttp.reason;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004958 if (reason == NULL)
Willy Tarreau7e702d12021-04-28 17:59:21 +02004959 reason = http_get_reason(luactx->appctx->ctx.hlua_apphttp.status);
4960 if (luactx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004961 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4962 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4963 }
4964 else {
4965 flags = HTX_SL_F_IS_RESP;
4966 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4967 }
4968 if (!sl) {
4969 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02004970 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004971 WILL_LJMP(lua_error(L));
4972 }
Willy Tarreau7e702d12021-04-28 17:59:21 +02004973 sl->info.res.status = luactx->appctx->ctx.hlua_apphttp.status;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004974
4975 /* Get the array associated to the field "response" in the object AppletHTTP. */
4976 lua_pushvalue(L, 0);
4977 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4978 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02004979 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004980 WILL_LJMP(lua_error(L));
4981 }
4982
4983 /* Browse the list of headers. */
4984 lua_pushnil(L);
4985 while(lua_next(L, -2) != 0) {
4986 /* We expect a string as -2. */
4987 if (lua_type(L, -2) != LUA_TSTRING) {
4988 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02004989 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004990 lua_typename(L, lua_type(L, -2)));
4991 WILL_LJMP(lua_error(L));
4992 }
4993 name = lua_tolstring(L, -2, &nlen);
4994
4995 /* We expect an array as -1. */
4996 if (lua_type(L, -1) != LUA_TTABLE) {
4997 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 +02004998 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004999 name,
5000 lua_typename(L, lua_type(L, -1)));
5001 WILL_LJMP(lua_error(L));
5002 }
5003
5004 /* Browse the table who is on the top of the stack. */
5005 lua_pushnil(L);
5006 while(lua_next(L, -2) != 0) {
5007 int id;
5008
5009 /* We expect a number as -2. */
5010 if (lua_type(L, -2) != LUA_TNUMBER) {
5011 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 +02005012 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005013 name,
5014 lua_typename(L, lua_type(L, -2)));
5015 WILL_LJMP(lua_error(L));
5016 }
5017 id = lua_tointeger(L, -2);
5018
5019 /* We expect a string as -2. */
5020 if (lua_type(L, -1) != LUA_TSTRING) {
5021 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 +02005022 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005023 name, id,
5024 lua_typename(L, lua_type(L, -1)));
5025 WILL_LJMP(lua_error(L));
5026 }
5027 value = lua_tolstring(L, -1, &vlen);
5028
5029 /* Simple Protocol checks. */
5030 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01005031 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005032 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
5033 struct ist v = ist2(value, vlen);
5034 int ret;
5035
5036 ret = h1_parse_cont_len_header(&h1m, &v);
5037 if (ret < 0) {
5038 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005039 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005040 name);
5041 WILL_LJMP(lua_error(L));
5042 }
5043 else if (ret == 0)
5044 goto next; /* Skip it */
5045 }
5046
5047 /* Add a new header */
5048 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
5049 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005050 luactx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005051 name);
5052 WILL_LJMP(lua_error(L));
5053 }
5054 next:
5055 /* Remove the array from the stack, and get next element with a remaining string. */
5056 lua_pop(L, 1);
5057 }
5058
5059 /* Remove the array from the stack, and get next element with a remaining string. */
5060 lua_pop(L, 1);
5061 }
5062
5063 if (h1m.flags & H1_MF_CHNK)
5064 h1m.flags &= ~H1_MF_CLEN;
5065 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5066 h1m.flags |= H1_MF_XFER_LEN;
5067
5068 /* Uset HTX start-line flags */
5069 if (h1m.flags & H1_MF_XFER_ENC)
5070 flags |= HTX_SL_F_XFER_ENC;
5071 if (h1m.flags & H1_MF_XFER_LEN) {
5072 flags |= HTX_SL_F_XFER_LEN;
5073 if (h1m.flags & H1_MF_CHNK)
5074 flags |= HTX_SL_F_CHNK;
5075 else if (h1m.flags & H1_MF_CLEN)
5076 flags |= HTX_SL_F_CLEN;
5077 if (h1m.body_len == 0)
5078 flags |= HTX_SL_F_BODYLESS;
5079 }
5080 sl->flags |= flags;
5081
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07005082 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005083 * and the status code implies the presence of a message body, we must
5084 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005085 * for the keepalive compliance. If the applet announces a transfer-encoding
5086 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005087 */
5088 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
Willy Tarreau7e702d12021-04-28 17:59:21 +02005089 luactx->appctx->ctx.hlua_apphttp.status >= 200 &&
5090 luactx->appctx->ctx.hlua_apphttp.status != 204 &&
5091 luactx->appctx->ctx.hlua_apphttp.status != 304) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005092 /* Add a new header */
5093 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
5094 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
5095 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005096 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005097 WILL_LJMP(lua_error(L));
5098 }
5099 }
5100
5101 /* Finalize headers. */
5102 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
5103 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Willy Tarreau7e702d12021-04-28 17:59:21 +02005104 luactx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005105 WILL_LJMP(lua_error(L));
5106 }
5107
5108 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
5109 b_reset(&res->buf);
5110 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5111 WILL_LJMP(lua_error(L));
5112 }
5113
5114 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01005115 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005116
5117 /* Headers sent, set the flag. */
Willy Tarreau7e702d12021-04-28 17:59:21 +02005118 luactx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005119 return 0;
5120
5121}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005122/* We will build the status line and the headers of the HTTP response.
5123 * We will try send at once if its not possible, we give back the hand
5124 * waiting for more room.
5125 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005126__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005127{
Willy Tarreau7e702d12021-04-28 17:59:21 +02005128 struct hlua_appctx *luactx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5129 struct stream_interface *si = luactx->appctx->owner;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005130 struct channel *res = si_ic(si);
5131
5132 if (co_data(res)) {
5133 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02005134 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005135 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005136 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005137}
5138
5139
Christopher Fauleta2097962019-07-15 16:25:33 +02005140__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005141{
Christopher Fauleta2097962019-07-15 16:25:33 +02005142 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005143}
5144
Christopher Fauleta2097962019-07-15 16:25:33 +02005145/*
5146 *
5147 *
5148 * Class HTTP
5149 *
5150 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005151 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005152
5153/* Returns a struct hlua_txn if the stack entry "ud" is
5154 * a class stream, otherwise it throws an error.
5155 */
5156__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005157{
Christopher Fauleta2097962019-07-15 16:25:33 +02005158 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
5159}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005160
Christopher Fauleta2097962019-07-15 16:25:33 +02005161/* This function creates and push in the stack a HTTP object
5162 * according with a current TXN.
5163 */
5164static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5165{
5166 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005167
Christopher Fauleta2097962019-07-15 16:25:33 +02005168 /* Check stack size. */
5169 if (!lua_checkstack(L, 3))
5170 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005171
Christopher Fauleta2097962019-07-15 16:25:33 +02005172 /* Create the object: obj[0] = userdata.
5173 * Note that the base of the Converters object is the
5174 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005175 */
Christopher Fauleta2097962019-07-15 16:25:33 +02005176 lua_newtable(L);
5177 htxn = lua_newuserdata(L, sizeof(*htxn));
5178 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005179
5180 htxn->s = txn->s;
5181 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005182 htxn->dir = txn->dir;
5183 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005184
5185 /* Pop a class stream metatable and affect it to the table. */
5186 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5187 lua_setmetatable(L, -2);
5188
5189 return 1;
5190}
5191
5192/* This function creates ans returns an array of HTTP headers.
5193 * This function does not fails. It is used as wrapper with the
5194 * 2 following functions.
5195 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005196__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005197{
Christopher Fauleta2097962019-07-15 16:25:33 +02005198 struct htx *htx;
5199 int32_t pos;
5200
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005201 /* Create the table. */
5202 lua_newtable(L);
5203
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005204
Christopher Fauleta2097962019-07-15 16:25:33 +02005205 htx = htxbuf(&msg->chn->buf);
5206 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5207 struct htx_blk *blk = htx_get_blk(htx, pos);
5208 enum htx_blk_type type = htx_get_blk_type(blk);
5209 struct ist n, v;
5210 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005211
Christopher Fauleta2097962019-07-15 16:25:33 +02005212 if (type == HTX_BLK_HDR) {
5213 n = htx_get_blk_name(htx,blk);
5214 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005215 }
Christopher Fauleta2097962019-07-15 16:25:33 +02005216 else if (type == HTX_BLK_EOH)
5217 break;
5218 else
5219 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005220
Christopher Fauleta2097962019-07-15 16:25:33 +02005221 /* Check for existing entry:
5222 * assume that the table is on the top of the stack, and
5223 * push the key in the stack, the function lua_gettable()
5224 * perform the lookup.
5225 */
5226 lua_pushlstring(L, n.ptr, n.len);
5227 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01005228
Christopher Fauleta2097962019-07-15 16:25:33 +02005229 switch (lua_type(L, -1)) {
5230 case LUA_TNIL:
5231 /* Table not found, create it. */
5232 lua_pop(L, 1); /* remove the nil value. */
5233 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5234 lua_newtable(L); /* create and push empty table. */
5235 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5236 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5237 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005238 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005239
Christopher Fauleta2097962019-07-15 16:25:33 +02005240 case LUA_TTABLE:
5241 /* Entry found: push the value in the table. */
5242 len = lua_rawlen(L, -1);
5243 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5244 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5245 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5246 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005247
Christopher Fauleta2097962019-07-15 16:25:33 +02005248 default:
5249 /* Other cases are errors. */
5250 hlua_pusherror(L, "internal error during the parsing of headers.");
5251 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005252 }
5253 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005254 return 1;
5255}
5256
5257__LJMP static int hlua_http_req_get_headers(lua_State *L)
5258{
5259 struct hlua_txn *htxn;
5260
5261 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5262 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5263
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005264 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005265 WILL_LJMP(lua_error(L));
5266
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005267 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005268}
5269
5270__LJMP static int hlua_http_res_get_headers(lua_State *L)
5271{
5272 struct hlua_txn *htxn;
5273
5274 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5275 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5276
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005277 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005278 WILL_LJMP(lua_error(L));
5279
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005280 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005281}
5282
5283/* This function replace full header, or just a value in
5284 * the request or in the response. It is a wrapper fir the
5285 * 4 following functions.
5286 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005287__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005288{
5289 size_t name_len;
5290 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5291 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5292 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005293 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005294 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005295
Dragan Dosen26743032019-04-30 15:54:36 +02005296 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005297 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5298
Christopher Fauleta2097962019-07-15 16:25:33 +02005299 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005300 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005301 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005302 return 0;
5303}
5304
5305__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5306{
5307 struct hlua_txn *htxn;
5308
5309 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5310 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5311
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005312 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005313 WILL_LJMP(lua_error(L));
5314
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005315 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005316}
5317
5318__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5319{
5320 struct hlua_txn *htxn;
5321
5322 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5323 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5324
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005325 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005326 WILL_LJMP(lua_error(L));
5327
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005328 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005329}
5330
5331__LJMP static int hlua_http_req_rep_val(lua_State *L)
5332{
5333 struct hlua_txn *htxn;
5334
5335 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5336 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5337
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005338 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005339 WILL_LJMP(lua_error(L));
5340
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005341 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005342}
5343
5344__LJMP static int hlua_http_res_rep_val(lua_State *L)
5345{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005346 struct hlua_txn *htxn;
5347
5348 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5349 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5350
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005351 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005352 WILL_LJMP(lua_error(L));
5353
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005354 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005355}
5356
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005357/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005358 * It is a wrapper for the 2 following functions.
5359 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005360__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005361{
5362 size_t len;
5363 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005364 struct htx *htx = htxbuf(&msg->chn->buf);
5365 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005366
Christopher Fauleta2097962019-07-15 16:25:33 +02005367 ctx.blk = NULL;
5368 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5369 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005370 return 0;
5371}
5372
5373__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5374{
5375 struct hlua_txn *htxn;
5376
5377 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5378 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5379
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005380 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005381 WILL_LJMP(lua_error(L));
5382
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005383 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005384}
5385
5386__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5387{
5388 struct hlua_txn *htxn;
5389
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005390 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005391 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5392
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005393 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005394 WILL_LJMP(lua_error(L));
5395
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005396 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005397}
5398
5399/* This function adds an header. It is a wrapper used by
5400 * the 2 following functions.
5401 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005402__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005403{
5404 size_t name_len;
5405 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5406 size_t value_len;
5407 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005408 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005409
Christopher Fauleta2097962019-07-15 16:25:33 +02005410 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5411 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005412 return 0;
5413}
5414
5415__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5416{
5417 struct hlua_txn *htxn;
5418
5419 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5420 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5421
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005422 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005423 WILL_LJMP(lua_error(L));
5424
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005425 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005426}
5427
5428__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5429{
5430 struct hlua_txn *htxn;
5431
5432 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5433 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5434
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005435 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005436 WILL_LJMP(lua_error(L));
5437
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005438 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005439}
5440
5441static int hlua_http_req_set_hdr(lua_State *L)
5442{
5443 struct hlua_txn *htxn;
5444
5445 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5446 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5447
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005448 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005449 WILL_LJMP(lua_error(L));
5450
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005451 hlua_http_del_hdr(L, &htxn->s->txn->req);
5452 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005453}
5454
5455static int hlua_http_res_set_hdr(lua_State *L)
5456{
5457 struct hlua_txn *htxn;
5458
5459 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5460 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5461
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005462 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005463 WILL_LJMP(lua_error(L));
5464
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005465 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5466 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005467}
5468
5469/* This function set the method. */
5470static int hlua_http_req_set_meth(lua_State *L)
5471{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005472 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005473 size_t name_len;
5474 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005475
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005476 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005477 WILL_LJMP(lua_error(L));
5478
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005479 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005480 return 1;
5481}
5482
5483/* This function set the method. */
5484static int hlua_http_req_set_path(lua_State *L)
5485{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005486 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005487 size_t name_len;
5488 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005489
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005490 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005491 WILL_LJMP(lua_error(L));
5492
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005493 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005494 return 1;
5495}
5496
5497/* This function set the query-string. */
5498static int hlua_http_req_set_query(lua_State *L)
5499{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005500 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005501 size_t name_len;
5502 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005503
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005504 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005505 WILL_LJMP(lua_error(L));
5506
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005507 /* Check length. */
5508 if (name_len > trash.size - 1) {
5509 lua_pushboolean(L, 0);
5510 return 1;
5511 }
5512
5513 /* Add the mark question as prefix. */
5514 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005515 trash.area[trash.data++] = '?';
5516 memcpy(trash.area + trash.data, name, name_len);
5517 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005518
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005519 lua_pushboolean(L,
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005520 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005521 return 1;
5522}
5523
5524/* This function set the uri. */
5525static int hlua_http_req_set_uri(lua_State *L)
5526{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005527 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005528 size_t name_len;
5529 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005530
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005531 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005532 WILL_LJMP(lua_error(L));
5533
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005534 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005535 return 1;
5536}
5537
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005538/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005539static int hlua_http_res_set_status(lua_State *L)
5540{
5541 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5542 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Faulet96bff762019-12-17 13:46:18 +01005543 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5544 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005545
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005546 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005547 WILL_LJMP(lua_error(L));
5548
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005549 http_res_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005550 return 0;
5551}
5552
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005553/*
5554 *
5555 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005556 * Class TXN
5557 *
5558 *
5559 */
5560
5561/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005562 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005563 */
5564__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5565{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005566 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005567}
5568
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005569__LJMP static int hlua_set_var(lua_State *L)
5570{
5571 struct hlua_txn *htxn;
5572 const char *name;
5573 size_t len;
5574 struct sample smp;
5575
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005576 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5577 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005578
5579 /* It is useles to retrieve the stream, but this function
5580 * runs only in a stream context.
5581 */
5582 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5583 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5584
5585 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005586 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005587 hlua_lua2smp(L, 3, &smp);
5588
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02005589 /* Store the sample in a variable. We don't need to dup the smp, vars API
5590 * already takes care of duplicating dynamic var data.
5591 */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005592 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005593
5594 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5595 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5596 else
5597 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5598
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005599 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005600}
5601
Christopher Faulet85d79c92016-11-09 16:54:56 +01005602__LJMP static int hlua_unset_var(lua_State *L)
5603{
5604 struct hlua_txn *htxn;
5605 const char *name;
5606 size_t len;
5607 struct sample smp;
5608
5609 MAY_LJMP(check_args(L, 2, "unset_var"));
5610
5611 /* It is useles to retrieve the stream, but this function
5612 * runs only in a stream context.
5613 */
5614 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5615 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5616
5617 /* Unset the variable. */
5618 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005619 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5620 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01005621}
5622
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005623__LJMP static int hlua_get_var(lua_State *L)
5624{
5625 struct hlua_txn *htxn;
5626 const char *name;
5627 size_t len;
5628 struct sample smp;
5629
5630 MAY_LJMP(check_args(L, 2, "get_var"));
5631
5632 /* It is useles to retrieve the stream, but this function
5633 * runs only in a stream context.
5634 */
5635 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5636 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5637
Willy Tarreau7560dd42016-03-10 16:28:58 +01005638 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005639 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005640 lua_pushnil(L);
5641 return 1;
5642 }
5643
5644 return hlua_smp2lua(L, &smp);
5645}
5646
Willy Tarreau59551662015-03-10 14:23:13 +01005647__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005648{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005649 struct hlua *hlua;
5650
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005651 MAY_LJMP(check_args(L, 2, "set_priv"));
5652
Willy Tarreau87b09662015-04-03 00:22:06 +02005653 /* It is useles to retrieve the stream, but this function
5654 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005655 */
5656 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005657
5658 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005659 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005660 if (!hlua)
5661 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005662
5663 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005664 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005665
5666 /* Get and store new value. */
5667 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5668 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5669
5670 return 0;
5671}
5672
Willy Tarreau59551662015-03-10 14:23:13 +01005673__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005674{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005675 struct hlua *hlua;
5676
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005677 MAY_LJMP(check_args(L, 1, "get_priv"));
5678
Willy Tarreau87b09662015-04-03 00:22:06 +02005679 /* It is useles to retrieve the stream, but this function
5680 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005681 */
5682 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005683
5684 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005685 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005686 if (!hlua) {
5687 lua_pushnil(L);
5688 return 1;
5689 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005690
5691 /* Push configuration index in the stack. */
5692 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5693
5694 return 1;
5695}
5696
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005697/* Create stack entry containing a class TXN. This function
5698 * return 0 if the stack does not contains free slots,
5699 * otherwise it returns 1.
5700 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005701static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005702{
Willy Tarreaude491382015-04-06 11:04:28 +02005703 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005704
5705 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005706 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005707 return 0;
5708
5709 /* NOTE: The allocation never fails. The failure
5710 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005711 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005712 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005713 /* Create the object: obj[0] = userdata. */
5714 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005715 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005716 lua_rawseti(L, -2, 0);
5717
Willy Tarreaude491382015-04-06 11:04:28 +02005718 htxn->s = s;
5719 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005720 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005721 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005722
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005723 /* Create the "f" field that contains a list of fetches. */
5724 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005725 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005726 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005727 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005728
5729 /* Create the "sf" field that contains a list of stringsafe fetches. */
5730 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005731 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005732 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005733 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005734
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005735 /* Create the "c" field that contains a list of converters. */
5736 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005737 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005738 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005739 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005740
5741 /* Create the "sc" field that contains a list of stringsafe converters. */
5742 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005743 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005744 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005745 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005746
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005747 /* Create the "req" field that contains the request channel object. */
5748 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005749 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005750 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005751 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005752
5753 /* Create the "res" field that contains the response channel object. */
5754 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005755 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005756 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005757 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005758
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005759 /* Creates the HTTP object is the current proxy allows http. */
5760 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01005761 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02005762 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005763 return 0;
5764 }
5765 else
5766 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005767 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005768
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005769 /* Pop a class sesison metatable and affect it to the userdata. */
5770 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5771 lua_setmetatable(L, -2);
5772
5773 return 1;
5774}
5775
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005776__LJMP static int hlua_txn_deflog(lua_State *L)
5777{
5778 const char *msg;
5779 struct hlua_txn *htxn;
5780
5781 MAY_LJMP(check_args(L, 2, "deflog"));
5782 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5783 msg = MAY_LJMP(luaL_checkstring(L, 2));
5784
5785 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5786 return 0;
5787}
5788
5789__LJMP static int hlua_txn_log(lua_State *L)
5790{
5791 int level;
5792 const char *msg;
5793 struct hlua_txn *htxn;
5794
5795 MAY_LJMP(check_args(L, 3, "log"));
5796 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5797 level = MAY_LJMP(luaL_checkinteger(L, 2));
5798 msg = MAY_LJMP(luaL_checkstring(L, 3));
5799
5800 if (level < 0 || level >= NB_LOG_LEVELS)
5801 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5802
5803 hlua_sendlog(htxn->s->be, level, msg);
5804 return 0;
5805}
5806
5807__LJMP static int hlua_txn_log_debug(lua_State *L)
5808{
5809 const char *msg;
5810 struct hlua_txn *htxn;
5811
5812 MAY_LJMP(check_args(L, 2, "Debug"));
5813 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5814 msg = MAY_LJMP(luaL_checkstring(L, 2));
5815 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5816 return 0;
5817}
5818
5819__LJMP static int hlua_txn_log_info(lua_State *L)
5820{
5821 const char *msg;
5822 struct hlua_txn *htxn;
5823
5824 MAY_LJMP(check_args(L, 2, "Info"));
5825 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5826 msg = MAY_LJMP(luaL_checkstring(L, 2));
5827 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5828 return 0;
5829}
5830
5831__LJMP static int hlua_txn_log_warning(lua_State *L)
5832{
5833 const char *msg;
5834 struct hlua_txn *htxn;
5835
5836 MAY_LJMP(check_args(L, 2, "Warning"));
5837 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5838 msg = MAY_LJMP(luaL_checkstring(L, 2));
5839 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5840 return 0;
5841}
5842
5843__LJMP static int hlua_txn_log_alert(lua_State *L)
5844{
5845 const char *msg;
5846 struct hlua_txn *htxn;
5847
5848 MAY_LJMP(check_args(L, 2, "Alert"));
5849 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5850 msg = MAY_LJMP(luaL_checkstring(L, 2));
5851 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5852 return 0;
5853}
5854
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005855__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5856{
5857 struct hlua_txn *htxn;
5858 int ll;
5859
5860 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5861 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5862 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5863
Christopher Faulet8263e942024-02-29 15:41:17 +01005864 if (ll < -1 || ll > NB_LOG_LEVELS)
5865 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be one of the following value:"
5866 " core.silent(-1), core.emerg(0), core.alert(1), core.crit(2), core.error(3),"
5867 " core.warning(4), core.notice(5), core.info(6) or core.debug(7)"));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005868
Christopher Faulet8263e942024-02-29 15:41:17 +01005869 htxn->s->logs.level = (ll == -1) ? ll : ll + 1;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005870 return 0;
5871}
5872
5873__LJMP static int hlua_txn_set_tos(lua_State *L)
5874{
5875 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005876 int tos;
5877
5878 MAY_LJMP(check_args(L, 2, "set_tos"));
5879 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5880 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5881
Willy Tarreau1a18b542018-12-11 16:37:42 +01005882 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005883 return 0;
5884}
5885
5886__LJMP static int hlua_txn_set_mark(lua_State *L)
5887{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005888 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005889 int mark;
5890
5891 MAY_LJMP(check_args(L, 2, "set_mark"));
5892 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5893 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5894
Lukas Tribus579e3e32019-08-11 18:03:45 +02005895 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005896 return 0;
5897}
5898
Patrick Hemmer268a7072018-05-11 12:52:31 -04005899__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5900{
5901 struct hlua_txn *htxn;
5902
5903 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5904 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5905 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5906 return 0;
5907}
5908
5909__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5910{
5911 struct hlua_txn *htxn;
5912
5913 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5914 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5915 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5916 return 0;
5917}
5918
Christopher Faulet700d9e82020-01-31 12:21:52 +01005919/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005920 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01005921 * message and terminate the transaction. It returns 1 on success and 0 on
5922 * error. The Reply must be on top of the stack.
5923 */
5924__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
5925{
5926 struct htx *htx;
5927 struct htx_sl *sl;
5928 struct h1m h1m;
5929 const char *status, *reason, *body;
5930 size_t status_len, reason_len, body_len;
5931 int ret, code, flags;
5932
5933 code = 200;
5934 status = "200";
5935 status_len = 3;
5936 ret = lua_getfield(L, -1, "status");
5937 if (ret == LUA_TNUMBER) {
5938 code = lua_tointeger(L, -1);
5939 status = lua_tolstring(L, -1, &status_len);
5940 }
5941 lua_pop(L, 1);
5942
5943 reason = http_get_reason(code);
5944 reason_len = strlen(reason);
5945 ret = lua_getfield(L, -1, "reason");
5946 if (ret == LUA_TSTRING)
5947 reason = lua_tolstring(L, -1, &reason_len);
5948 lua_pop(L, 1);
5949
5950 body = NULL;
5951 body_len = 0;
5952 ret = lua_getfield(L, -1, "body");
5953 if (ret == LUA_TSTRING)
5954 body = lua_tolstring(L, -1, &body_len);
5955 lua_pop(L, 1);
5956
5957 /* Prepare the response before inserting the headers */
5958 h1m_init_res(&h1m);
5959 htx = htx_from_buf(&s->res.buf);
5960 channel_htx_truncate(&s->res, htx);
5961 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
5962 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5963 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
5964 ist2(status, status_len), ist2(reason, reason_len));
5965 }
5966 else {
5967 flags = HTX_SL_F_IS_RESP;
5968 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
5969 ist2(status, status_len), ist2(reason, reason_len));
5970 }
5971 if (!sl)
5972 goto fail;
5973 sl->info.res.status = code;
5974
5975 /* Push in the stack the "headers" entry. */
5976 ret = lua_getfield(L, -1, "headers");
5977 if (ret != LUA_TTABLE)
5978 goto skip_headers;
5979
5980 lua_pushnil(L);
5981 while (lua_next(L, -2) != 0) {
5982 struct ist name, value;
5983 const char *n, *v;
5984 size_t nlen, vlen;
5985
5986 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
5987 /* Skip element if the key is not a string or if the value is not a table */
5988 goto next_hdr;
5989 }
5990
5991 n = lua_tolstring(L, -2, &nlen);
5992 name = ist2(n, nlen);
5993 if (isteqi(name, ist("content-length"))) {
5994 /* Always skip content-length header. It will be added
5995 * later with the correct len
5996 */
5997 goto next_hdr;
5998 }
5999
6000 /* Loop on header's values */
6001 lua_pushnil(L);
6002 while (lua_next(L, -2)) {
6003 if (!lua_isstring(L, -1)) {
6004 /* Skip the value if it is not a string */
6005 goto next_value;
6006 }
6007
6008 v = lua_tolstring(L, -1, &vlen);
6009 value = ist2(v, vlen);
6010
6011 if (isteqi(name, ist("transfer-encoding")))
6012 h1_parse_xfer_enc_header(&h1m, value);
6013 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
6014 goto fail;
6015
6016 next_value:
6017 lua_pop(L, 1);
6018 }
6019
6020 next_hdr:
6021 lua_pop(L, 1);
6022 }
6023 skip_headers:
6024 lua_pop(L, 1);
6025
6026 /* Update h1m flags: CLEN is set if CHNK is not present */
6027 if (!(h1m.flags & H1_MF_CHNK)) {
6028 const char *clen = ultoa(body_len);
6029
6030 h1m.flags |= H1_MF_CLEN;
6031 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
6032 goto fail;
6033 }
6034 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
6035 h1m.flags |= H1_MF_XFER_LEN;
6036
6037 /* Update HTX start-line flags */
6038 if (h1m.flags & H1_MF_XFER_ENC)
6039 flags |= HTX_SL_F_XFER_ENC;
6040 if (h1m.flags & H1_MF_XFER_LEN) {
6041 flags |= HTX_SL_F_XFER_LEN;
6042 if (h1m.flags & H1_MF_CHNK)
6043 flags |= HTX_SL_F_CHNK;
6044 else if (h1m.flags & H1_MF_CLEN)
6045 flags |= HTX_SL_F_CLEN;
6046 if (h1m.body_len == 0)
6047 flags |= HTX_SL_F_BODYLESS;
6048 }
6049 sl->flags |= flags;
6050
6051
6052 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01006053 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01006054 goto fail;
6055
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01006056 htx->flags |= HTX_FL_EOM;
6057
Christopher Faulet700d9e82020-01-31 12:21:52 +01006058 /* Now, forward the response and terminate the transaction */
6059 s->txn->status = code;
6060 htx_to_buf(htx, &s->res.buf);
6061 if (!http_forward_proxy_resp(s, 1))
6062 goto fail;
6063
6064 return 1;
6065
6066 fail:
6067 channel_htx_truncate(&s->res, htx);
6068 return 0;
6069}
6070
6071/* Terminate a transaction if called from a lua action. For TCP streams,
6072 * processing is just aborted. Nothing is returned to the client and all
6073 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
6074 * is forwarded to the client before terminating the transaction. On success,
6075 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
6076 * with ACT_RET_ERR code. If this function is not called from a lua action, it
6077 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006078 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006079__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006080{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006081 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01006082 struct stream *s;
6083 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006084
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006085 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006086
Christopher Faulet700d9e82020-01-31 12:21:52 +01006087 /* If the flags NOTERM is set, we cannot terminate the session, so we
6088 * just end the execution of the current lua code. */
6089 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006090 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006091
Christopher Faulet700d9e82020-01-31 12:21:52 +01006092 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006093 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01006094 struct channel *req = &s->req;
6095 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006096
Christopher Faulet700d9e82020-01-31 12:21:52 +01006097 channel_auto_read(req);
6098 channel_abort(req);
6099 channel_auto_close(req);
6100 channel_erase(req);
6101
6102 res->wex = tick_add_ifset(now_ms, res->wto);
6103 channel_auto_read(res);
6104 channel_auto_close(res);
6105 channel_shutr_now(res);
6106
6107 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
6108 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02006109 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006110
Christopher Faulet700d9e82020-01-31 12:21:52 +01006111 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
6112 /* No reply or invalid reply */
6113 s->txn->status = 0;
6114 http_reply_and_close(s, 0, NULL);
6115 }
6116 else {
6117 /* Remove extra args to have the reply on top of the stack */
6118 if (lua_gettop(L) > 2)
6119 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006120
Christopher Faulet700d9e82020-01-31 12:21:52 +01006121 if (!hlua_txn_forward_reply(L, s)) {
6122 if (!(s->flags & SF_ERR_MASK))
6123 s->flags |= SF_ERR_PRXCOND;
6124 lua_pushinteger(L, ACT_RET_ERR);
6125 WILL_LJMP(hlua_done(L));
6126 return 0; /* Never reached */
6127 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02006128 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006129
Christopher Faulet700d9e82020-01-31 12:21:52 +01006130 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
6131 if (htxn->dir == SMP_OPT_DIR_REQ) {
6132 /* let's log the request time */
6133 s->logs.tv_request = now;
6134 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02006135 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01006136 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02006137
Christopher Faulet700d9e82020-01-31 12:21:52 +01006138 done:
6139 if (!(s->flags & SF_ERR_MASK))
6140 s->flags |= SF_ERR_LOCAL;
6141 if (!(s->flags & SF_FINST_MASK))
6142 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02006143
Christopher Faulet4ad73102020-03-05 11:07:31 +01006144 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006145 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006146 return 0;
6147}
6148
Christopher Faulet700d9e82020-01-31 12:21:52 +01006149/*
6150 *
6151 *
6152 * Class REPLY
6153 *
6154 *
6155 */
6156
6157/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
6158 * free slots, the function fails and returns 0;
6159 */
6160static int hlua_txn_reply_new(lua_State *L)
6161{
6162 struct hlua_txn *htxn;
6163 const char *reason, *body = NULL;
6164 int ret, status;
6165
6166 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006167 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01006168 hlua_pusherror(L, "txn object is not an HTTP transaction.");
6169 WILL_LJMP(lua_error(L));
6170 }
6171
6172 /* Default value */
6173 status = 200;
6174 reason = http_get_reason(status);
6175
6176 if (lua_istable(L, 2)) {
6177 /* load status and reason from the table argument at index 2 */
6178 ret = lua_getfield(L, 2, "status");
6179 if (ret == LUA_TNIL)
6180 goto reason;
6181 else if (ret != LUA_TNUMBER) {
6182 /* invalid status: ignore the reason */
6183 goto body;
6184 }
6185 status = lua_tointeger(L, -1);
6186
6187 reason:
6188 lua_pop(L, 1); /* restore the stack: remove status */
6189 ret = lua_getfield(L, 2, "reason");
6190 if (ret == LUA_TSTRING)
6191 reason = lua_tostring(L, -1);
6192
6193 body:
6194 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
6195 ret = lua_getfield(L, 2, "body");
6196 if (ret == LUA_TSTRING)
6197 body = lua_tostring(L, -1);
6198 lua_pop(L, 1); /* restore the stack: remove body */
6199 }
6200
6201 /* Create the Reply table */
6202 lua_newtable(L);
6203
6204 /* Add status element */
6205 lua_pushstring(L, "status");
6206 lua_pushinteger(L, status);
6207 lua_settable(L, -3);
6208
6209 /* Add reason element */
6210 reason = http_get_reason(status);
6211 lua_pushstring(L, "reason");
6212 lua_pushstring(L, reason);
6213 lua_settable(L, -3);
6214
6215 /* Add body element, nil if undefined */
6216 lua_pushstring(L, "body");
6217 if (body)
6218 lua_pushstring(L, body);
6219 else
6220 lua_pushnil(L);
6221 lua_settable(L, -3);
6222
6223 /* Add headers element */
6224 lua_pushstring(L, "headers");
6225 lua_newtable(L);
6226
6227 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
6228 if (lua_istable(L, 2)) {
6229 /* load headers from the table argument at index 2. If it is a table, copy it. */
6230 ret = lua_getfield(L, 2, "headers");
6231 if (ret == LUA_TTABLE) {
6232 /* stack: [ ... <headers:table>, <table> ] */
6233 lua_pushnil(L);
6234 while (lua_next(L, -2) != 0) {
6235 /* stack: [ ... <headers:table>, <table>, k, v] */
6236 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
6237 /* invalid value type, skip it */
6238 lua_pop(L, 1);
6239 continue;
6240 }
6241
6242
6243 /* Duplicate the key and swap it with the value. */
6244 lua_pushvalue(L, -2);
6245 lua_insert(L, -2);
6246 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
6247
6248 lua_newtable(L);
6249 lua_insert(L, -2);
6250 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
6251
6252 if (lua_isstring(L, -1)) {
6253 /* push the value in the inner table */
6254 lua_rawseti(L, -2, 1);
6255 }
6256 else { /* table */
6257 lua_pushnil(L);
6258 while (lua_next(L, -2) != 0) {
6259 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
6260 if (!lua_isstring(L, -1)) {
6261 /* invalid value type, skip it*/
6262 lua_pop(L, 1);
6263 continue;
6264 }
6265 /* push the value in the inner table */
6266 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
6267 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
6268 }
6269 lua_pop(L, 1);
6270 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
6271 }
6272
6273 /* push (k,v) on the stack in the headers table:
6274 * stack: [ ... <headers:table>, <table>, k, k, v ]
6275 */
6276 lua_settable(L, -5);
6277 /* stack: [ ... <headers:table>, <table>, k ] */
6278 }
6279 }
6280 lua_pop(L, 1);
6281 }
6282 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
6283 lua_settable(L, -3);
6284 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
6285
6286 /* Pop a class sesison metatable and affect it to the userdata. */
6287 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
6288 lua_setmetatable(L, -2);
6289 return 1;
6290}
6291
6292/* Set the reply status code, and optionally the reason. If no reason is
6293 * provided, the default one corresponding to the status code is used.
6294 */
6295__LJMP static int hlua_txn_reply_set_status(lua_State *L)
6296{
6297 int status = MAY_LJMP(luaL_checkinteger(L, 2));
6298 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6299
6300 /* First argument (self) must be a table */
6301 luaL_checktype(L, 1, LUA_TTABLE);
6302
6303 if (status < 100 || status > 599) {
6304 lua_pushboolean(L, 0);
6305 return 1;
6306 }
6307 if (!reason)
6308 reason = http_get_reason(status);
6309
6310 lua_pushinteger(L, status);
6311 lua_setfield(L, 1, "status");
6312
6313 lua_pushstring(L, reason);
6314 lua_setfield(L, 1, "reason");
6315
6316 lua_pushboolean(L, 1);
6317 return 1;
6318}
6319
6320/* Add a header into the reply object. Each header name is associated to an
6321 * array of values in the "headers" table. If the header name is not found, a
6322 * new entry is created.
6323 */
6324__LJMP static int hlua_txn_reply_add_header(lua_State *L)
6325{
6326 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
6327 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
6328 int ret;
6329
6330 /* First argument (self) must be a table */
6331 luaL_checktype(L, 1, LUA_TTABLE);
6332
6333 /* Push in the stack the "headers" entry. */
6334 ret = lua_getfield(L, 1, "headers");
6335 if (ret != LUA_TTABLE) {
6336 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
6337 WILL_LJMP(lua_error(L));
6338 }
6339
6340 /* check if the header is already registered. If not, register it. */
6341 ret = lua_getfield(L, -1, name);
6342 if (ret == LUA_TNIL) {
6343 /* Entry not found. */
6344 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
6345
6346 /* Insert the new header name in the array in the top of the stack.
6347 * It left the new array in the top of the stack.
6348 */
6349 lua_newtable(L);
6350 lua_pushstring(L, name);
6351 lua_pushvalue(L, -2);
6352 lua_settable(L, -4);
6353 }
6354 else if (ret != LUA_TTABLE) {
6355 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
6356 WILL_LJMP(lua_error(L));
6357 }
6358
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07006359 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01006360 * the header value as new entry.
6361 */
6362 lua_pushstring(L, value);
6363 ret = lua_rawlen(L, -2);
6364 lua_rawseti(L, -2, ret + 1);
6365
6366 lua_pushboolean(L, 1);
6367 return 1;
6368}
6369
6370/* Remove all occurrences of a given header name. */
6371__LJMP static int hlua_txn_reply_del_header(lua_State *L)
6372{
6373 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
6374 int ret;
6375
6376 /* First argument (self) must be a table */
6377 luaL_checktype(L, 1, LUA_TTABLE);
6378
6379 /* Push in the stack the "headers" entry. */
6380 ret = lua_getfield(L, 1, "headers");
6381 if (ret != LUA_TTABLE) {
6382 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
6383 WILL_LJMP(lua_error(L));
6384 }
6385
6386 lua_pushstring(L, name);
6387 lua_pushnil(L);
6388 lua_settable(L, -3);
6389
6390 lua_pushboolean(L, 1);
6391 return 1;
6392}
6393
6394/* Set the reply's body. Overwrite any existing entry. */
6395__LJMP static int hlua_txn_reply_set_body(lua_State *L)
6396{
6397 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
6398
6399 /* First argument (self) must be a table */
6400 luaL_checktype(L, 1, LUA_TTABLE);
6401
6402 lua_pushstring(L, payload);
6403 lua_setfield(L, 1, "body");
6404
6405 lua_pushboolean(L, 1);
6406 return 1;
6407}
6408
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006409__LJMP static int hlua_log(lua_State *L)
6410{
6411 int level;
6412 const char *msg;
6413
6414 MAY_LJMP(check_args(L, 2, "log"));
6415 level = MAY_LJMP(luaL_checkinteger(L, 1));
6416 msg = MAY_LJMP(luaL_checkstring(L, 2));
6417
6418 if (level < 0 || level >= NB_LOG_LEVELS)
6419 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6420
6421 hlua_sendlog(NULL, level, msg);
6422 return 0;
6423}
6424
6425__LJMP static int hlua_log_debug(lua_State *L)
6426{
6427 const char *msg;
6428
6429 MAY_LJMP(check_args(L, 1, "debug"));
6430 msg = MAY_LJMP(luaL_checkstring(L, 1));
6431 hlua_sendlog(NULL, LOG_DEBUG, msg);
6432 return 0;
6433}
6434
6435__LJMP static int hlua_log_info(lua_State *L)
6436{
6437 const char *msg;
6438
6439 MAY_LJMP(check_args(L, 1, "info"));
6440 msg = MAY_LJMP(luaL_checkstring(L, 1));
6441 hlua_sendlog(NULL, LOG_INFO, msg);
6442 return 0;
6443}
6444
6445__LJMP static int hlua_log_warning(lua_State *L)
6446{
6447 const char *msg;
6448
6449 MAY_LJMP(check_args(L, 1, "warning"));
6450 msg = MAY_LJMP(luaL_checkstring(L, 1));
6451 hlua_sendlog(NULL, LOG_WARNING, msg);
6452 return 0;
6453}
6454
6455__LJMP static int hlua_log_alert(lua_State *L)
6456{
6457 const char *msg;
6458
6459 MAY_LJMP(check_args(L, 1, "alert"));
6460 msg = MAY_LJMP(luaL_checkstring(L, 1));
6461 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006462 return 0;
6463}
6464
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006465__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006466{
6467 int wakeup_ms = lua_tointeger(L, -1);
Willy Tarreau9cc2e4c2021-09-30 16:12:31 +02006468 if (!tick_is_expired(wakeup_ms, now_ms))
Willy Tarreau9635e032018-10-16 17:52:55 +02006469 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006470 return 0;
6471}
6472
6473__LJMP static int hlua_sleep(lua_State *L)
6474{
6475 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006476 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006477
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006478 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006479
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006480 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006481 wakeup_ms = tick_add(now_ms, delay);
6482 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006483
Willy Tarreau9635e032018-10-16 17:52:55 +02006484 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006485 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006486}
6487
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006488__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006489{
6490 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006491 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006492
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006493 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006494
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006495 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006496 wakeup_ms = tick_add(now_ms, delay);
6497 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006498
Willy Tarreau9635e032018-10-16 17:52:55 +02006499 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006500 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006501}
6502
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006503/* This functionis an LUA binding. it permits to give back
6504 * the hand at the HAProxy scheduler. It is used when the
6505 * LUA processing consumes a lot of time.
6506 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006507__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006508{
6509 return 0;
6510}
6511
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006512__LJMP static int hlua_yield(lua_State *L)
6513{
Willy Tarreau9635e032018-10-16 17:52:55 +02006514 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006515 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006516}
6517
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006518/* This function change the nice of the currently executed
6519 * task. It is used set low or high priority at the current
6520 * task.
6521 */
Willy Tarreau59551662015-03-10 14:23:13 +01006522__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006523{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006524 struct hlua *hlua;
6525 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006526
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006527 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006528 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006529
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006530 /* Get hlua struct, or NULL if we execute from main lua state */
6531 hlua = hlua_gethlua(L);
6532
6533 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006534 if (!hlua || !hlua->task)
6535 return 0;
6536
6537 if (nice < -1024)
6538 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006539 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006540 nice = 1024;
6541
6542 hlua->task->nice = nice;
6543 return 0;
6544}
6545
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006546/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006547 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6548 * return an E_AGAIN signal, the emmiter of this signal must set a
6549 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006550 *
6551 * Task wrapper are longjmp safe because the only one Lua code
6552 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006553 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01006554struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006555{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006556 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006557 enum hlua_exec status;
6558
Christopher Faulet5bc99722018-04-25 10:34:45 +02006559 if (task->thread_mask == MAX_THREADS_MASK)
6560 task_set_affinity(task, tid_bit);
6561
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006562 /* If it is the first call to the task, we must initialize the
6563 * execution timeouts.
6564 */
6565 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006566 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006567
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006568 /* Execute the Lua code. */
6569 status = hlua_ctx_resume(hlua, 1);
6570
6571 switch (status) {
6572 /* finished or yield */
6573 case HLUA_E_OK:
6574 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006575 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006576 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006577 break;
6578
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006579 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006580 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006581 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006582 break;
6583
6584 /* finished with error. */
6585 case HLUA_E_ERRMSG:
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01006586 hlua_lock(hlua);
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01006587 SEND_ERR(NULL, "Lua task: %s.\n", hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006588 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006589 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006590 task = NULL;
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01006591 hlua_unlock(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006592 break;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006593 case HLUA_E_ERR:
6594 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006595 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006596 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006597 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006598 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006599 break;
6600 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006601 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006602}
6603
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006604/* This function is an LUA binding that register LUA function to be
6605 * executed after the HAProxy configuration parsing and before the
6606 * HAProxy scheduler starts. This function expect only one LUA
6607 * argument that is a function. This function returns nothing, but
6608 * throws if an error is encountered.
6609 */
6610__LJMP static int hlua_register_init(lua_State *L)
6611{
6612 struct hlua_init_function *init;
6613 int ref;
6614
6615 MAY_LJMP(check_args(L, 1, "register_init"));
6616
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01006617 if (hlua_gethlua(L)) {
6618 /* runtime processing */
6619 WILL_LJMP(luaL_error(L, "register_init: not available outside of body context"));
6620 }
6621
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006622 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6623
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006624 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006625 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006626 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006627
6628 init->function_ref = ref;
Willy Tarreau2b718102021-04-21 07:32:39 +02006629 LIST_APPEND(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006630 return 0;
6631}
6632
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006633/* This functio is an LUA binding. It permits to register a task
6634 * executed in parallel of the main HAroxy activity. The task is
6635 * created and it is set in the HAProxy scheduler. It can be called
6636 * from the "init" section, "post init" or during the runtime.
6637 *
6638 * Lua prototype:
6639 *
6640 * <none> core.register_task(<function>)
6641 */
6642static int hlua_register_task(lua_State *L)
6643{
Christopher Faulet5294ec02021-04-12 12:24:47 +02006644 struct hlua *hlua = NULL;
6645 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006646 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01006647 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006648
6649 MAY_LJMP(check_args(L, 1, "register_task"));
6650
6651 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6652
Thierry Fournier75fc0292020-11-28 13:18:56 +01006653 /* Get the reference state. If the reference is NULL, L is the master
6654 * state, otherwise hlua->T is.
6655 */
6656 hlua = hlua_gethlua(L);
6657 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01006658 /* we are in runtime processing */
6659 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01006660 else
Thierry Fournier021d9862020-11-28 23:42:03 +01006661 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01006662 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01006663
Willy Tarreaubafbe012017-11-24 17:34:44 +01006664 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006665 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02006666 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01006667 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006668
Thierry Fournier59f11be2020-11-29 00:37:41 +01006669 /* We are in the common lua state, execute the task anywhere,
6670 * otherwise, inherit the current thread identifier
6671 */
6672 if (state_id == 0)
6673 task = task_new(MAX_THREADS_MASK);
6674 else
6675 task = task_new(tid_bit);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006676 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02006677 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02006678
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006679 task->context = hlua;
6680 task->process = hlua_process_task;
6681
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01006682 if (!hlua_ctx_init(hlua, state_id, task))
Christopher Faulet5294ec02021-04-12 12:24:47 +02006683 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006684
6685 /* Restore the function in the stack. */
6686 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
Aurelien DARRAGONb6aade32023-03-13 14:09:21 +01006687 /* function ref not needed anymore since it was pushed to the substack */
6688 hlua_unref(L, ref);
6689
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006690 hlua->nargs = 0;
6691
6692 /* Schedule task. */
Willy Tarreau790810f2021-09-30 16:17:37 +02006693 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006694
6695 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02006696
6697 alloc_error:
6698 task_destroy(task);
6699 hlua_ctx_destroy(hlua);
6700 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6701 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006702}
6703
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006704/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6705 * doesn't allow "yield" functions because the HAProxy engine cannot
6706 * resume converters.
6707 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006708static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006709{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006710 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006711 struct stream *stream = smp->strm;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006712 struct hlua *hlua = NULL;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006713 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006714
Willy Tarreaube508f12016-03-10 11:47:01 +01006715 if (!stream)
6716 return 0;
6717
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006718 if (!(hlua = hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn)))) {
Aurelien DARRAGON4a7a5d82023-08-09 14:56:19 +02006719 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6720 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006721 }
6722
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006723 /* If it is the first run, initialize the data for the call. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006724 if (!HLUA_IS_RUNNING(hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006725
6726 /* The following Lua calls can fail. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006727 if (!SET_SAFE_LJMP(hlua)) {
6728 hlua_lock(hlua);
6729 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6730 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006731 else
6732 error = "critical error";
6733 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006734 hlua_unlock(hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006735 return 0;
6736 }
6737
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006738 /* Check stack available size. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006739 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006740 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006741 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006742 return 0;
6743 }
6744
6745 /* Restore the function in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006746 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006747
6748 /* convert input sample and pust-it in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006749 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006750 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006751 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006752 return 0;
6753 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006754 hlua_smp2lua(hlua->T, smp);
6755 hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006756
6757 /* push keywords in the stack. */
6758 if (arg_p) {
6759 for (; arg_p->type != ARGT_STOP; arg_p++) {
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006760 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006761 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006762 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006763 return 0;
6764 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006765 hlua_arg2lua(hlua->T, arg_p);
6766 hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006767 }
6768 }
6769
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006770 /* We must initialize the execution timeouts. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006771 hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006772
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006773 /* At this point the execution is safe. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006774 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006775 }
6776
6777 /* Execute the function. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006778 switch (hlua_ctx_resume(hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006779 /* finished. */
6780 case HLUA_E_OK:
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006781 hlua_lock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006782 /* If the stack is empty, the function fails. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006783 if (lua_gettop(hlua->T) <= 0) {
6784 hlua_unlock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006785 return 0;
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01006786 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006787
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006788 /* Convert the returned value in sample. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006789 hlua_lua2smp(hlua->T, -1, smp);
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02006790 /* dup the smp before popping the related lua value and
6791 * returning it to haproxy
6792 */
6793 smp_dup(smp);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006794 lua_pop(hlua->T, 1);
6795 hlua_unlock(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006796 return 1;
6797
6798 /* yield. */
6799 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006800 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006801 return 0;
6802
6803 /* finished with error. */
6804 case HLUA_E_ERRMSG:
6805 /* Display log. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006806 hlua_lock(hlua);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006807 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006808 fcn->name, hlua_tostring_safe(hlua->T, -1));
6809 lua_pop(hlua->T, 1);
6810 hlua_unlock(hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006811 return 0;
6812
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006813 case HLUA_E_ETMOUT:
6814 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6815 return 0;
6816
6817 case HLUA_E_NOMEM:
6818 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6819 return 0;
6820
6821 case HLUA_E_YIELD:
6822 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6823 return 0;
6824
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006825 case HLUA_E_ERR:
6826 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006827 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02006828 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006829
6830 default:
6831 return 0;
6832 }
6833}
6834
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006835/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6836 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006837 * resume sample-fetches. This function will be called by the sample
6838 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006839 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006840static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6841 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006842{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006843 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006844 struct stream *stream = smp->strm;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006845 struct hlua *hlua = NULL;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006846 const char *error;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006847 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006848
Willy Tarreaube508f12016-03-10 11:47:01 +01006849 if (!stream)
6850 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006851
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006852 if (!(hlua = hlua_stream_ctx_prepare(stream, fcn_ref_to_stack_id(fcn)))) {
Aurelien DARRAGON4a7a5d82023-08-09 14:56:19 +02006853 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6854 return 0;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006855 }
6856
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006857 /* If it is the first run, initialize the data for the call. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006858 if (!HLUA_IS_RUNNING(hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006859
6860 /* The following Lua calls can fail. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006861 if (!SET_SAFE_LJMP(hlua)) {
6862 hlua_lock(hlua);
6863 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6864 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006865 else
6866 error = "critical error";
6867 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006868 hlua_unlock(hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006869 return 0;
6870 }
6871
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006872 /* Check stack available size. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006873 if (!lua_checkstack(hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006874 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006875 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006876 return 0;
6877 }
6878
6879 /* Restore the function in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006880 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006881
6882 /* push arguments in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006883 if (!hlua_txn_new(hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006884 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006885 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006886 return 0;
6887 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006888 hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006889
6890 /* push keywords in the stack. */
6891 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6892 /* Check stack available size. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006893 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006894 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006895 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006896 return 0;
6897 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006898 hlua_arg2lua(hlua->T, arg_p);
6899 hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006900 }
6901
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006902 /* We must initialize the execution timeouts. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006903 hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006904
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006905 /* At this point the execution is safe. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006906 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006907 }
6908
6909 /* Execute the function. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006910 switch (hlua_ctx_resume(hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006911 /* finished. */
6912 case HLUA_E_OK:
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006913 hlua_lock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006914 /* If the stack is empty, the function fails. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006915 if (lua_gettop(hlua->T) <= 0) {
6916 hlua_unlock(hlua);
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006917 return 0;
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01006918 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006919
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006920 /* Convert the returned value in sample. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006921 hlua_lua2smp(hlua->T, -1, smp);
Aurelien DARRAGONd39fb742023-05-17 16:06:11 +02006922 /* dup the smp before popping the related lua value and
6923 * returning it to haproxy
6924 */
6925 smp_dup(smp);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006926 lua_pop(hlua->T, 1);
6927 hlua_unlock(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006928
6929 /* Set the end of execution flag. */
6930 smp->flags &= ~SMP_F_MAY_CHANGE;
6931 return 1;
6932
6933 /* yield. */
6934 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006935 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006936 return 0;
6937
6938 /* finished with error. */
6939 case HLUA_E_ERRMSG:
6940 /* Display log. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006941 hlua_lock(hlua);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006942 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01006943 fcn->name, hlua_tostring_safe(hlua->T, -1));
6944 lua_pop(hlua->T, 1);
6945 hlua_unlock(hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006946 return 0;
6947
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006948 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006949 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6950 return 0;
6951
6952 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006953 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6954 return 0;
6955
6956 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006957 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6958 return 0;
6959
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006960 case HLUA_E_ERR:
6961 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006962 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02006963 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006964
6965 default:
6966 return 0;
6967 }
6968}
6969
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006970/* This function is an LUA binding used for registering
6971 * "sample-conv" functions. It expects a converter name used
6972 * in the haproxy configuration file, and an LUA function.
6973 */
6974__LJMP static int hlua_register_converters(lua_State *L)
6975{
6976 struct sample_conv_kw_list *sck;
6977 const char *name;
6978 int ref;
6979 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02006980 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01006981 struct sample_conv *sc;
6982 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006983
6984 MAY_LJMP(check_args(L, 2, "register_converters"));
6985
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01006986 if (hlua_gethlua(L)) {
6987 /* runtime processing */
6988 WILL_LJMP(luaL_error(L, "register_converters: not available outside of body context"));
6989 }
6990
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006991 /* First argument : converter name. */
6992 name = MAY_LJMP(luaL_checkstring(L, 1));
6993
6994 /* Second argument : lua function. */
6995 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6996
Thierry Fournierf67442e2020-11-28 20:41:07 +01006997 /* Check if the converter is already registered */
6998 trash = get_trash_chunk();
6999 chunk_printf(trash, "lua.%s", name);
7000 sc = find_sample_conv(trash->area, trash->data);
7001 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01007002 fcn = sc->private;
7003 if (fcn->function_ref[hlua_state_id] != -1) {
7004 ha_warning("Trying to register converter 'lua.%s' more than once. "
7005 "This will become a hard error in version 2.5.\n", name);
7006 }
7007 fcn->function_ref[hlua_state_id] = ref;
7008 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007009 }
7010
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007011 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007012 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007013 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02007014 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01007015 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007016 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02007017 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007018
7019 /* Fill fcn. */
7020 fcn->name = strdup(name);
7021 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02007022 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01007023 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007024
7025 /* List head */
7026 sck->list.n = sck->list.p = NULL;
7027
7028 /* converter keyword. */
7029 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007030 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007031 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02007032 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007033
7034 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
7035 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01007036 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 +01007037 sck->kw[0].val_args = NULL;
7038 sck->kw[0].in_type = SMP_T_STR;
7039 sck->kw[0].out_type = SMP_T_STR;
7040 sck->kw[0].private = fcn;
7041
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007042 /* Register this new converter */
7043 sample_register_convs(sck);
7044
7045 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02007046
7047 alloc_error:
7048 release_hlua_function(fcn);
7049 ha_free(&sck);
7050 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
7051 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007052}
7053
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007054/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007055 * "sample-fetch" functions. It expects a converter name used
7056 * in the haproxy configuration file, and an LUA function.
7057 */
7058__LJMP static int hlua_register_fetches(lua_State *L)
7059{
7060 const char *name;
7061 int ref;
7062 int len;
7063 struct sample_fetch_kw_list *sfk;
Christopher Faulet2567f182021-04-12 14:11:50 +02007064 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007065 struct sample_fetch *sf;
7066 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007067
7068 MAY_LJMP(check_args(L, 2, "register_fetches"));
7069
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01007070 if (hlua_gethlua(L)) {
7071 /* runtime processing */
7072 WILL_LJMP(luaL_error(L, "register_fetches: not available outside of body context"));
7073 }
7074
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007075 /* First argument : sample-fetch name. */
7076 name = MAY_LJMP(luaL_checkstring(L, 1));
7077
7078 /* Second argument : lua function. */
7079 ref = MAY_LJMP(hlua_checkfunction(L, 2));
7080
Thierry Fournierf67442e2020-11-28 20:41:07 +01007081 /* Check if the sample-fetch is already registered */
7082 trash = get_trash_chunk();
7083 chunk_printf(trash, "lua.%s", name);
7084 sf = find_sample_fetch(trash->area, trash->data);
7085 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01007086 fcn = sf->private;
7087 if (fcn->function_ref[hlua_state_id] != -1) {
7088 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
7089 "This will become a hard error in version 2.5.\n", name);
7090 }
7091 fcn->function_ref[hlua_state_id] = ref;
7092 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007093 }
7094
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007095 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007096 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007097 if (!sfk)
Christopher Faulet2567f182021-04-12 14:11:50 +02007098 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01007099 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007100 if (!fcn)
Christopher Faulet2567f182021-04-12 14:11:50 +02007101 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007102
7103 /* Fill fcn. */
7104 fcn->name = strdup(name);
7105 if (!fcn->name)
Christopher Faulet2567f182021-04-12 14:11:50 +02007106 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01007107 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007108
7109 /* List head */
7110 sfk->list.n = sfk->list.p = NULL;
7111
7112 /* sample-fetch keyword. */
7113 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007114 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007115 if (!sfk->kw[0].kw)
Christopher Faulet2567f182021-04-12 14:11:50 +02007116 goto alloc_error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007117
7118 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
7119 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01007120 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 +01007121 sfk->kw[0].val_args = NULL;
7122 sfk->kw[0].out_type = SMP_T_STR;
7123 sfk->kw[0].use = SMP_USE_HTTP_ANY;
7124 sfk->kw[0].val = 0;
7125 sfk->kw[0].private = fcn;
7126
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007127 /* Register this new fetch. */
7128 sample_register_fetches(sfk);
7129
7130 return 0;
Christopher Faulet2567f182021-04-12 14:11:50 +02007131
7132 alloc_error:
7133 release_hlua_function(fcn);
7134 ha_free(&sfk);
7135 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
7136 return 0; /* Never reached */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007137}
7138
Christopher Faulet501465d2020-02-26 14:54:16 +01007139/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007140 */
Christopher Faulet501465d2020-02-26 14:54:16 +01007141__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007142{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007143 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007144 unsigned int delay;
7145 unsigned int wakeup_ms;
7146
Thierry Fournier4234dbd2020-11-28 13:18:23 +01007147 /* Get hlua struct, or NULL if we execute from main lua state */
7148 hlua = hlua_gethlua(L);
7149 if (!hlua) {
7150 return 0;
7151 }
7152
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007153 MAY_LJMP(check_args(L, 1, "wake_time"));
7154
7155 delay = MAY_LJMP(luaL_checkinteger(L, 1));
7156 wakeup_ms = tick_add(now_ms, delay);
7157 hlua->wake_time = wakeup_ms;
7158 return 0;
7159}
7160
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007161/* This function is a wrapper to execute each LUA function declared as an action
7162 * wrapper during the initialisation period. This function may return any
7163 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
7164 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
7165 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007166 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007167static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02007168 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007169{
7170 char **arg;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02007171 unsigned int hflags = 0;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007172 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007173 const char *error;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007174 struct hlua *hlua = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007175
7176 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01007177 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
7178 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
7179 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
7180 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007181 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007182 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007183 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007184 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007185
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007186 if (!(hlua = hlua_stream_ctx_prepare(s, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn)))) {
Aurelien DARRAGON4a7a5d82023-08-09 14:56:19 +02007187 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
7188 rule->arg.hlua_rule->fcn->name);
7189 goto end;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01007190 }
7191
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007192 /* If it is the first run, initialize the data for the call. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007193 if (!HLUA_IS_RUNNING(hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007194
7195 /* The following Lua calls can fail. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007196 if (!SET_SAFE_LJMP(hlua)) {
7197 hlua_lock(hlua);
7198 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7199 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007200 else
7201 error = "critical error";
7202 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007203 rule->arg.hlua_rule->fcn->name, error);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007204 hlua_unlock(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007205 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007206 }
7207
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007208 /* Check stack available size. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007209 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007210 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007211 rule->arg.hlua_rule->fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007212 RESET_SAFE_LJMP(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007213 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007214 }
7215
7216 /* Restore the function in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007217 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007218
Willy Tarreau87b09662015-04-03 00:22:06 +02007219 /* Create and and push object stream in the stack. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007220 if (!hlua_txn_new(hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007221 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007222 rule->arg.hlua_rule->fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007223 RESET_SAFE_LJMP(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007224 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007225 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007226 hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007227
7228 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007229 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007230 if (!lua_checkstack(hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007231 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007232 rule->arg.hlua_rule->fcn->name);
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007233 RESET_SAFE_LJMP(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007234 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007235 }
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007236 lua_pushstring(hlua->T, *arg);
7237 hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007238 }
7239
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007240 /* Now the execution is safe. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007241 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007242
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007243 /* We must initialize the execution timeouts. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007244 hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007245 }
7246
7247 /* Execute the function. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007248 switch (hlua_ctx_resume(hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007249 /* finished. */
7250 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007251 /* Catch the return value */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007252 hlua_lock(hlua);
7253 if (lua_gettop(hlua->T) > 0)
7254 act_ret = lua_tointeger(hlua->T, -1);
7255 hlua_unlock(hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007256
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007257 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02007258 if (act_ret == ACT_RET_YIELD) {
7259 if (flags & ACT_OPT_FINAL)
7260 goto err_yield;
7261
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007262 if (dir == SMP_OPT_DIR_REQ)
7263 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 +01007264 hlua->wake_time);
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007265 else
7266 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 +01007267 hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007268 }
7269 goto end;
7270
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007271 /* yield. */
7272 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01007273 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007274 if (dir == SMP_OPT_DIR_REQ)
7275 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 +01007276 hlua->wake_time);
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007277 else
7278 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 +01007279 hlua->wake_time);
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007280
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007281 /* Some actions can be wake up when a "write" event
7282 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007283 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007284 */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007285 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01007286 s->res.flags |= CF_WAKE_WRITE;
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007287 if (HLUA_IS_WAKEREQWR(hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01007288 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007289 act_ret = ACT_RET_YIELD;
7290 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007291
7292 /* finished with error. */
7293 case HLUA_E_ERRMSG:
7294 /* Display log. */
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007295 hlua_lock(hlua);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007296 SEND_ERR(px, "Lua function '%s': %s.\n",
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007297 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
7298 lua_pop(hlua->T, 1);
7299 hlua_unlock(hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007300 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007301
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007302 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01007303 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007304 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007305
7306 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01007307 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007308 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007309
7310 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02007311 err_yield:
7312 act_ret = ACT_RET_CONT;
Aurelien DARRAGON602c4af2023-08-31 21:45:21 +02007313 SEND_ERR(px, "Lua function '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007314 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007315 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007316
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007317 case HLUA_E_ERR:
7318 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007319 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007320 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007321
7322 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007323 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007324 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007325
7326 end:
Aurelien DARRAGONd5911352024-03-12 17:00:25 +01007327 if (act_ret != ACT_RET_YIELD && hlua)
7328 hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007329 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007330}
7331
Willy Tarreau144f84a2021-03-02 16:09:26 +01007332struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007333{
Olivier Houchard9f6af332018-05-25 14:04:04 +02007334 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007335
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007336 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02007337 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02007338 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007339}
7340
7341static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7342{
7343 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007344 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007345 struct task *task;
7346 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007347 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007348
Willy Tarreaubafbe012017-11-24 17:34:44 +01007349 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007350 if (!hlua) {
7351 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007352 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007353 return 0;
7354 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007355 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007356 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007357 ctx->ctx.hlua_apptcp.flags = 0;
7358
7359 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007360 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007361 if (!task) {
7362 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007363 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007364 return 0;
7365 }
7366 task->nice = 0;
7367 task->context = ctx;
7368 task->process = hlua_applet_wakeup;
7369 ctx->ctx.hlua_apptcp.task = task;
7370
7371 /* In the execution wrappers linked with a stream, the
7372 * Lua context can be not initialized. This behavior
7373 * permits to save performances because a systematic
7374 * Lua initialization cause 5% performances loss.
7375 */
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01007376 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007377 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007378 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007379 return 0;
7380 }
7381
7382 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007383 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007384
7385 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007386 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01007387 hlua_lock(hlua);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007388 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01007389 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007390 else
7391 error = "critical error";
7392 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007393 ctx->rule->arg.hlua_rule->fcn->name, error);
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01007394 hlua_unlock(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007395 return 0;
7396 }
7397
7398 /* Check stack available size. */
7399 if (!lua_checkstack(hlua->T, 1)) {
7400 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007401 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007402 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007403 return 0;
7404 }
7405
7406 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01007407 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007408
7409 /* Create and and push object stream in the stack. */
7410 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7411 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007412 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007413 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007414 return 0;
7415 }
7416 hlua->nargs = 1;
7417
7418 /* push keywords in the stack. */
7419 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7420 if (!lua_checkstack(hlua->T, 1)) {
7421 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007422 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007423 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007424 return 0;
7425 }
7426 lua_pushstring(hlua->T, *arg);
7427 hlua->nargs++;
7428 }
7429
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007430 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007431
7432 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007433 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007434 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007435
7436 return 1;
7437}
7438
Willy Tarreau60409db2019-08-21 14:14:50 +02007439void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007440{
7441 struct stream_interface *si = ctx->owner;
7442 struct stream *strm = si_strm(si);
7443 struct channel *res = si_ic(si);
7444 struct act_rule *rule = ctx->rule;
7445 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007446 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007447
7448 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007449 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7450 /* eat the whole request */
7451 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007452 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007453 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007454
7455 /* If the stream is disconnect or closed, ldo nothing. */
7456 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7457 return;
7458
7459 /* Execute the function. */
7460 switch (hlua_ctx_resume(hlua, 1)) {
7461 /* finished. */
7462 case HLUA_E_OK:
7463 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7464
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007465 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007466 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007467 res->flags |= CF_READ_NULL;
7468 si_shutr(si);
7469 return;
7470
7471 /* yield. */
7472 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007473 if (hlua->wake_time != TICK_ETERNITY)
7474 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007475 return;
7476
7477 /* finished with error. */
7478 case HLUA_E_ERRMSG:
7479 /* Display log. */
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01007480 hlua_lock(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007481 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01007482 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007483 lua_pop(hlua->T, 1);
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01007484 hlua_unlock(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007485 goto error;
7486
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007487 case HLUA_E_ETMOUT:
7488 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007489 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007490 goto error;
7491
7492 case HLUA_E_NOMEM:
7493 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007494 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007495 goto error;
7496
7497 case HLUA_E_YIELD: /* unexpected */
7498 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007499 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007500 goto error;
7501
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007502 case HLUA_E_ERR:
7503 /* Display log. */
7504 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007505 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007506 goto error;
7507
7508 default:
7509 goto error;
7510 }
7511
7512error:
7513
7514 /* For all other cases, just close the stream. */
7515 si_shutw(si);
7516 si_shutr(si);
7517 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7518}
7519
7520static void hlua_applet_tcp_release(struct appctx *ctx)
7521{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007522 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007523 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007524 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007525 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007526}
7527
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007528/* The function returns 1 if the initialisation is complete, 0 if
7529 * an errors occurs and -1 if more data are required for initializing
7530 * the applet.
7531 */
7532static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7533{
7534 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007535 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007536 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007537 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007538 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007539 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007540
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007541 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01007542 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007543 if (!hlua) {
7544 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007545 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007546 return 0;
7547 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007548 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007549 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007550 ctx->ctx.hlua_apphttp.left_bytes = -1;
7551 ctx->ctx.hlua_apphttp.flags = 0;
7552
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007553 if (txn->req.flags & HTTP_MSGF_VER_11)
7554 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7555
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007556 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007557 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007558 if (!task) {
7559 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007560 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007561 return 0;
7562 }
7563 task->nice = 0;
7564 task->context = ctx;
7565 task->process = hlua_applet_wakeup;
7566 ctx->ctx.hlua_apphttp.task = task;
7567
7568 /* In the execution wrappers linked with a stream, the
7569 * Lua context can be not initialized. This behavior
7570 * permits to save performances because a systematic
7571 * Lua initialization cause 5% performances loss.
7572 */
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01007573 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007574 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007575 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007576 return 0;
7577 }
7578
7579 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007580 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007581
7582 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007583 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01007584 hlua_lock(hlua);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007585 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01007586 error = hlua_tostring_safe(hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01007587 else
7588 error = "critical error";
7589 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007590 ctx->rule->arg.hlua_rule->fcn->name, error);
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01007591 hlua_unlock(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007592 return 0;
7593 }
7594
7595 /* Check stack available size. */
7596 if (!lua_checkstack(hlua->T, 1)) {
7597 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007598 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007599 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007600 return 0;
7601 }
7602
7603 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01007604 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007605
7606 /* Create and and push object stream in the stack. */
7607 if (!hlua_applet_http_new(hlua->T, ctx)) {
7608 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007609 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007610 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007611 return 0;
7612 }
7613 hlua->nargs = 1;
7614
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007615 /* push keywords in the stack. */
7616 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7617 if (!lua_checkstack(hlua->T, 1)) {
7618 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007619 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007620 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007621 return 0;
7622 }
7623 lua_pushstring(hlua->T, *arg);
7624 hlua->nargs++;
7625 }
7626
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007627 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007628
7629 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007630 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007631
7632 return 1;
7633}
7634
Willy Tarreau60409db2019-08-21 14:14:50 +02007635void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007636{
7637 struct stream_interface *si = ctx->owner;
7638 struct stream *strm = si_strm(si);
7639 struct channel *req = si_oc(si);
7640 struct channel *res = si_ic(si);
7641 struct act_rule *rule = ctx->rule;
7642 struct proxy *px = strm->be;
7643 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7644 struct htx *req_htx, *res_htx;
7645
7646 res_htx = htx_from_buf(&res->buf);
7647
7648 /* If the stream is disconnect or closed, ldo nothing. */
7649 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7650 goto out;
7651
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007652 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007653 if (!b_size(&res->buf)) {
7654 si_rx_room_blk(si);
7655 goto out;
7656 }
7657 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007658 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007659 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7660
7661 /* Set the currently running flag. */
7662 if (!HLUA_IS_RUNNING(hlua) &&
7663 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Christopher Fauletbd878d22021-04-28 10:50:21 +02007664 if (!co_data(req)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007665 si_cant_get(si);
7666 goto out;
7667 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007668 }
7669
7670 /* Executes The applet if it is not done. */
7671 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7672
7673 /* Execute the function. */
7674 switch (hlua_ctx_resume(hlua, 1)) {
7675 /* finished. */
7676 case HLUA_E_OK:
7677 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7678 break;
7679
7680 /* yield. */
7681 case HLUA_E_AGAIN:
7682 if (hlua->wake_time != TICK_ETERNITY)
7683 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007684 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007685
7686 /* finished with error. */
7687 case HLUA_E_ERRMSG:
7688 /* Display log. */
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01007689 hlua_lock(hlua);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007690 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01007691 rule->arg.hlua_rule->fcn->name, hlua_tostring_safe(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007692 lua_pop(hlua->T, 1);
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01007693 hlua_unlock(hlua);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007694 goto error;
7695
7696 case HLUA_E_ETMOUT:
7697 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007698 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007699 goto error;
7700
7701 case HLUA_E_NOMEM:
7702 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007703 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007704 goto error;
7705
7706 case HLUA_E_YIELD: /* unexpected */
7707 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007708 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007709 goto error;
7710
7711 case HLUA_E_ERR:
7712 /* Display log. */
7713 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007714 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007715 goto error;
7716
7717 default:
7718 goto error;
7719 }
7720 }
7721
7722 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007723 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7724 goto done;
7725
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007726 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7727 goto error;
7728
Christopher Faulet868b3b12022-04-07 10:07:18 +02007729 /* no more data are expected. If the response buffer is empty
7730 * for a chunked message, be sure to add something (EOT block in
7731 * this case) to have something to send. It is important to be
7732 * sure the EOM flags will be handled by the endpoint.
7733 */
7734 if (htx_is_empty(res_htx) && (strm->txn->rsp.flags & (HTTP_MSGF_XFER_LEN|HTTP_MSGF_CNT_LEN)) == HTTP_MSGF_XFER_LEN) {
7735 if (!htx_add_endof(res_htx, HTX_BLK_EOT)) {
7736 si_rx_room_blk(si);
7737 goto out;
7738 }
7739 channel_add_input(res, 1);
7740 }
7741
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007742 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet79c0fc72022-03-07 15:50:54 +01007743 res->flags |= CF_EOI;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007744 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7745 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007746 }
7747
7748 done:
7749 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007750 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007751 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007752 si_shutr(si);
7753 }
7754
7755 /* eat the whole request */
7756 if (co_data(req)) {
7757 req_htx = htx_from_buf(&req->buf);
7758 co_htx_skip(req, req_htx, co_data(req));
7759 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007760 }
7761 }
7762
7763 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007764 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007765 return;
7766
7767 error:
7768
7769 /* If we are in HTTP mode, and we are not send any
7770 * data, return a 500 server error in best effort:
7771 * if there is no room available in the buffer,
7772 * just close the connection.
7773 */
7774 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02007775 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007776
7777 channel_erase(res);
7778 res->buf.data = b_data(err);
7779 memcpy(res->buf.area, b_head(err), b_data(err));
7780 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007781 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007782 }
7783 if (!(strm->flags & SF_ERR_MASK))
7784 strm->flags |= SF_ERR_RESOURCE;
7785 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7786 goto done;
7787}
7788
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007789static void hlua_applet_http_release(struct appctx *ctx)
7790{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007791 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007792 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007793 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007794 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007795}
7796
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007797/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007798 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007799 *
7800 * This function can fail with an abort() due to an Lua critical error.
7801 * We are in the configuration parsing process of HAProxy, this abort() is
7802 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007803 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007804static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7805 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007806{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007807 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007808 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007809
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007810 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007811 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007812 if (!rule->arg.hlua_rule) {
7813 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02007814 goto error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007815 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007816
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007817 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02007818 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
7819 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007820 if (!rule->arg.hlua_rule->args) {
7821 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02007822 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007823 }
7824
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007825 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01007826 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007827
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007828 /* Expect some arguments */
7829 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007830 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007831 memprintf(err, "expect %d arguments", fcn->nargs);
Christopher Faulet528526f2021-04-12 14:37:32 +02007832 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007833 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007834 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007835 if (!rule->arg.hlua_rule->args[i]) {
7836 memprintf(err, "out of memory error");
Christopher Faulet528526f2021-04-12 14:37:32 +02007837 goto error;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007838 }
7839 (*cur_arg)++;
7840 }
7841 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007842
Thierry FOURNIER42148732015-09-02 17:17:33 +02007843 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007844 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007845 return ACT_RET_PRS_OK;
Christopher Faulet528526f2021-04-12 14:37:32 +02007846
7847 error:
7848 if (rule->arg.hlua_rule) {
7849 if (rule->arg.hlua_rule->args) {
7850 for (i = 0; i < fcn->nargs; i++)
7851 ha_free(&rule->arg.hlua_rule->args[i]);
7852 ha_free(&rule->arg.hlua_rule->args);
7853 }
7854 ha_free(&rule->arg.hlua_rule);
7855 }
7856 return ACT_RET_PRS_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007857}
7858
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007859static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7860 struct act_rule *rule, char **err)
7861{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007862 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007863
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007864 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007865 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007866 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007867 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007868 * the call of this analyzer.
7869 */
7870 if (rule->from != ACT_F_HTTP_REQ) {
7871 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7872 return ACT_RET_PRS_ERR;
7873 }
7874
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007875 /* Memory for the rule. */
7876 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7877 if (!rule->arg.hlua_rule) {
7878 memprintf(err, "out of memory error");
7879 return ACT_RET_PRS_ERR;
7880 }
7881
7882 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01007883 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007884
7885 /* TODO: later accept arguments. */
7886 rule->arg.hlua_rule->args = NULL;
7887
7888 /* Add applet pointer in the rule. */
7889 rule->applet.obj_type = OBJ_TYPE_APPLET;
7890 rule->applet.name = fcn->name;
7891 rule->applet.init = hlua_applet_http_init;
7892 rule->applet.fct = hlua_applet_http_fct;
7893 rule->applet.release = hlua_applet_http_release;
7894 rule->applet.timeout = hlua_timeout_applet;
7895
7896 return ACT_RET_PRS_OK;
7897}
7898
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007899/* This function is an LUA binding used for registering
7900 * "sample-conv" functions. It expects a converter name used
7901 * in the haproxy configuration file, and an LUA function.
7902 */
7903__LJMP static int hlua_register_action(lua_State *L)
7904{
Christopher Faulet4fc9da02021-04-12 15:08:12 +02007905 struct action_kw_list *akl = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007906 const char *name;
7907 int ref;
7908 int len;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02007909 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007910 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007911 struct buffer *trash;
7912 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007913
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007914 /* Initialise the number of expected arguments at 0. */
7915 nargs = 0;
7916
7917 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7918 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007919
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01007920 if (hlua_gethlua(L)) {
7921 /* runtime processing */
7922 WILL_LJMP(luaL_error(L, "register_action: not available outside of body context"));
7923 }
7924
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007925 /* First argument : converter name. */
7926 name = MAY_LJMP(luaL_checkstring(L, 1));
7927
7928 /* Second argument : environment. */
7929 if (lua_type(L, 2) != LUA_TTABLE)
7930 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7931
7932 /* Third argument : lua function. */
7933 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7934
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007935 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007936 if (lua_gettop(L) >= 4)
7937 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7938
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007939 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007940 lua_pushnil(L);
7941 while (lua_next(L, 2) != 0) {
7942 if (lua_type(L, -1) != LUA_TSTRING)
7943 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7944
Thierry Fournierf67442e2020-11-28 20:41:07 +01007945 /* Check if action exists */
7946 trash = get_trash_chunk();
7947 chunk_printf(trash, "lua.%s", name);
7948 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
7949 akw = tcp_req_cont_action(trash->area);
7950 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
7951 akw = tcp_res_cont_action(trash->area);
7952 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
7953 akw = action_http_req_custom(trash->area);
7954 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
7955 akw = action_http_res_custom(trash->area);
7956 } else {
7957 akw = NULL;
7958 }
7959 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01007960 fcn = akw->private;
7961 if (fcn->function_ref[hlua_state_id] != -1) {
7962 ha_warning("Trying to register action 'lua.%s' more than once. "
7963 "This will become a hard error in version 2.5.\n", name);
7964 }
7965 fcn->function_ref[hlua_state_id] = ref;
7966
7967 /* pop the environment string. */
7968 lua_pop(L, 1);
7969 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007970 }
7971
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007972 /* Check required environment. Only accepted "http" or "tcp". */
7973 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007974 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007975 if (!akl)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02007976 goto alloc_error;;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01007977 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007978 if (!fcn)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02007979 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007980
7981 /* Fill fcn. */
7982 fcn->name = strdup(name);
7983 if (!fcn->name)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02007984 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01007985 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007986
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07007987 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007988 fcn->nargs = nargs;
7989
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007990 /* List head */
7991 akl->list.n = akl->list.p = NULL;
7992
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007993 /* action keyword. */
7994 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007995 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007996 if (!akl->kw[0].kw)
Christopher Faulet4fc9da02021-04-12 15:08:12 +02007997 goto alloc_error;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007998
7999 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
8000
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02008001 akl->kw[0].flags = 0;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008002 akl->kw[0].private = fcn;
8003 akl->kw[0].parse = action_register_lua;
8004
8005 /* select the action registering point. */
8006 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
8007 tcp_req_cont_keywords_register(akl);
8008 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
8009 tcp_res_cont_keywords_register(akl);
8010 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
8011 http_req_keywords_register(akl);
8012 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
8013 http_res_keywords_register(akl);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008014 else {
8015 release_hlua_function(fcn);
8016 if (akl)
8017 ha_free((char **)&(akl->kw[0].kw));
8018 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008019 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008020 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
8021 "are expected.", lua_tostring(L, -1)));
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008022 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008023
8024 /* pop the environment string. */
8025 lua_pop(L, 1);
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008026
8027 /* reset for next loop */
8028 akl = NULL;
8029 fcn = NULL;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008030 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008031 return ACT_RET_PRS_OK;
Christopher Faulet4fc9da02021-04-12 15:08:12 +02008032
8033 alloc_error:
8034 release_hlua_function(fcn);
8035 ha_free(&akl);
8036 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8037 return 0; /* Never reached */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008038}
8039
8040static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
8041 struct act_rule *rule, char **err)
8042{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02008043 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008044
Christopher Faulet280f85b2019-07-15 15:02:04 +02008045 if (px->mode == PR_MODE_HTTP) {
8046 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01008047 return ACT_RET_PRS_ERR;
8048 }
8049
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008050 /* Memory for the rule. */
8051 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
8052 if (!rule->arg.hlua_rule) {
8053 memprintf(err, "out of memory error");
8054 return ACT_RET_PRS_ERR;
8055 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008056
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008057 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01008058 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008059
8060 /* TODO: later accept arguments. */
8061 rule->arg.hlua_rule->args = NULL;
8062
8063 /* Add applet pointer in the rule. */
8064 rule->applet.obj_type = OBJ_TYPE_APPLET;
8065 rule->applet.name = fcn->name;
8066 rule->applet.init = hlua_applet_tcp_init;
8067 rule->applet.fct = hlua_applet_tcp_fct;
8068 rule->applet.release = hlua_applet_tcp_release;
8069 rule->applet.timeout = hlua_timeout_applet;
8070
8071 return 0;
8072}
8073
8074/* This function is an LUA binding used for registering
8075 * "sample-conv" functions. It expects a converter name used
8076 * in the haproxy configuration file, and an LUA function.
8077 */
8078__LJMP static int hlua_register_service(lua_State *L)
8079{
8080 struct action_kw_list *akl;
8081 const char *name;
8082 const char *env;
8083 int ref;
8084 int len;
Christopher Faulet5c028d72021-04-12 15:11:44 +02008085 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008086 struct buffer *trash;
8087 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008088
8089 MAY_LJMP(check_args(L, 3, "register_service"));
8090
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01008091 if (hlua_gethlua(L)) {
8092 /* runtime processing */
8093 WILL_LJMP(luaL_error(L, "register_service: not available outside of body context"));
8094 }
8095
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008096 /* First argument : converter name. */
8097 name = MAY_LJMP(luaL_checkstring(L, 1));
8098
8099 /* Second argument : environment. */
8100 env = MAY_LJMP(luaL_checkstring(L, 2));
8101
8102 /* Third argument : lua function. */
8103 ref = MAY_LJMP(hlua_checkfunction(L, 3));
8104
Thierry Fournierf67442e2020-11-28 20:41:07 +01008105 /* Check for service already registered */
8106 trash = get_trash_chunk();
8107 chunk_printf(trash, "lua.%s", name);
8108 akw = service_find(trash->area);
8109 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008110 fcn = akw->private;
8111 if (fcn->function_ref[hlua_state_id] != -1) {
8112 ha_warning("Trying to register service 'lua.%s' more than once. "
8113 "This will become a hard error in version 2.5.\n", name);
8114 }
8115 fcn->function_ref[hlua_state_id] = ref;
8116 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008117 }
8118
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008119 /* Allocate and fill the sample fetch keyword struct. */
8120 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
8121 if (!akl)
Christopher Faulet5c028d72021-04-12 15:11:44 +02008122 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008123 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008124 if (!fcn)
Christopher Faulet5c028d72021-04-12 15:11:44 +02008125 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008126
8127 /* Fill fcn. */
8128 len = strlen("<lua.>") + strlen(name) + 1;
8129 fcn->name = calloc(1, len);
8130 if (!fcn->name)
Christopher Faulet5c028d72021-04-12 15:11:44 +02008131 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008132 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01008133 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008134
8135 /* List head */
8136 akl->list.n = akl->list.p = NULL;
8137
8138 /* converter keyword. */
8139 len = strlen("lua.") + strlen(name) + 1;
8140 akl->kw[0].kw = calloc(1, len);
8141 if (!akl->kw[0].kw)
Christopher Faulet5c028d72021-04-12 15:11:44 +02008142 goto alloc_error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008143
8144 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
8145
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01008146 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008147 if (strcmp(env, "tcp") == 0)
8148 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008149 else if (strcmp(env, "http") == 0)
8150 akl->kw[0].parse = action_register_service_http;
Christopher Faulet5c028d72021-04-12 15:11:44 +02008151 else {
8152 release_hlua_function(fcn);
8153 if (akl)
8154 ha_free((char **)&(akl->kw[0].kw));
8155 ha_free(&akl);
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008156 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01008157 "'tcp' or 'http' are expected.", env));
Christopher Faulet5c028d72021-04-12 15:11:44 +02008158 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008159
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02008160 akl->kw[0].flags = 0;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008161 akl->kw[0].private = fcn;
8162
8163 /* End of array. */
8164 memset(&akl->kw[1], 0, sizeof(*akl->kw));
8165
8166 /* Register this new converter */
8167 service_keywords_register(akl);
8168
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008169 return 0;
Christopher Faulet5c028d72021-04-12 15:11:44 +02008170
8171 alloc_error:
8172 release_hlua_function(fcn);
8173 ha_free(&akl);
8174 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
8175 return 0; /* Never reached */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008176}
8177
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008178/* This function initialises Lua cli handler. It copies the
8179 * arguments in the Lua stack and create channel IO objects.
8180 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02008181static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008182{
8183 struct hlua *hlua;
8184 struct hlua_function *fcn;
8185 int i;
8186 const char *error;
8187
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008188 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008189 appctx->ctx.hlua_cli.fcn = private;
8190
Willy Tarreaubafbe012017-11-24 17:34:44 +01008191 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008192 if (!hlua) {
8193 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008194 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008195 }
8196 HLUA_INIT(hlua);
8197 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008198
8199 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05008200 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008201 * applet_http. It is absolutely compatible.
8202 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008203 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008204 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01008205 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008206 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008207 }
8208 appctx->ctx.hlua_cli.task->nice = 0;
8209 appctx->ctx.hlua_cli.task->context = appctx;
8210 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
8211
8212 /* Initialises the Lua context */
Aurelien DARRAGON5483bde2023-03-21 14:02:16 +01008213 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 +01008214 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008215 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008216 }
8217
8218 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008219 if (!SET_SAFE_LJMP(hlua)) {
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01008220 hlua_lock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008221 if (lua_type(hlua->T, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008222 error = hlua_tostring_safe(hlua->T, -1);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008223 else
8224 error = "critical error";
8225 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
Aurelien DARRAGONd4df5622024-03-04 11:17:58 +01008226 hlua_unlock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008227 goto error;
8228 }
8229
8230 /* Check stack available size. */
8231 if (!lua_checkstack(hlua->T, 2)) {
8232 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
8233 goto error;
8234 }
8235
8236 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01008237 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008238
8239 /* Once the arguments parsed, the CLI is like an AppletTCP,
8240 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008241 */
8242 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
8243 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
8244 goto error;
8245 }
8246 hlua->nargs = 1;
8247
8248 /* push keywords in the stack. */
8249 for (i = 0; *args[i]; i++) {
8250 /* Check stack available size. */
8251 if (!lua_checkstack(hlua->T, 1)) {
8252 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
8253 goto error;
8254 }
8255 lua_pushstring(hlua->T, args[i]);
8256 hlua->nargs++;
8257 }
8258
8259 /* We must initialize the execution timeouts. */
8260 hlua->max_time = hlua_timeout_session;
8261
8262 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008263 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008264
8265 /* It's ok */
8266 return 0;
8267
8268 /* It's not ok. */
8269error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +01008270 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008271 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008272 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008273 return 1;
8274}
8275
8276static int hlua_cli_io_handler_fct(struct appctx *appctx)
8277{
8278 struct hlua *hlua;
8279 struct stream_interface *si;
8280 struct hlua_function *fcn;
8281
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008282 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008283 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01008284 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008285
8286 /* If the stream is disconnect or closed, ldo nothing. */
8287 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8288 return 1;
8289
8290 /* Execute the function. */
8291 switch (hlua_ctx_resume(hlua, 1)) {
8292
8293 /* finished. */
8294 case HLUA_E_OK:
8295 return 1;
8296
8297 /* yield. */
8298 case HLUA_E_AGAIN:
8299 /* We want write. */
8300 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008301 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008302 /* Set the timeout. */
8303 if (hlua->wake_time != TICK_ETERNITY)
8304 task_schedule(hlua->task, hlua->wake_time);
8305 return 0;
8306
8307 /* finished with error. */
8308 case HLUA_E_ERRMSG:
8309 /* Display log. */
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01008310 hlua_lock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008311 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008312 fcn->name, hlua_tostring_safe(hlua->T, -1));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008313 lua_pop(hlua->T, 1);
Aurelien DARRAGON6ab7ec92024-03-01 21:17:51 +01008314 hlua_unlock(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008315 return 1;
8316
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008317 case HLUA_E_ETMOUT:
8318 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8319 fcn->name);
8320 return 1;
8321
8322 case HLUA_E_NOMEM:
8323 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8324 fcn->name);
8325 return 1;
8326
8327 case HLUA_E_YIELD: /* unexpected */
8328 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8329 fcn->name);
8330 return 1;
8331
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008332 case HLUA_E_ERR:
8333 /* Display log. */
8334 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8335 fcn->name);
8336 return 1;
8337
8338 default:
8339 return 1;
8340 }
8341
8342 return 1;
8343}
8344
8345static void hlua_cli_io_release_fct(struct appctx *appctx)
8346{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008347 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008348 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008349}
8350
8351/* This function is an LUA binding used for registering
8352 * new keywords in the cli. It expects a list of keywords
8353 * which are the "path". It is limited to 5 keywords. A
8354 * description of the command, a function to be executed
8355 * for the parsing and a function for io handlers.
8356 */
8357__LJMP static int hlua_register_cli(lua_State *L)
8358{
8359 struct cli_kw_list *cli_kws;
8360 const char *message;
8361 int ref_io;
8362 int len;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008363 struct hlua_function *fcn = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008364 int index;
8365 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008366 struct buffer *trash;
8367 const char *kw[5];
8368 struct cli_kw *cli_kw;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008369 const char *errmsg;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008370
8371 MAY_LJMP(check_args(L, 3, "register_cli"));
8372
Aurelien DARRAGON8985ab82023-02-24 09:43:54 +01008373 if (hlua_gethlua(L)) {
8374 /* runtime processing */
8375 WILL_LJMP(luaL_error(L, "register_cli: not available outside of body context"));
8376 }
8377
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008378 /* First argument : an array of maximum 5 keywords. */
8379 if (!lua_istable(L, 1))
8380 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8381
8382 /* Second argument : string with contextual message. */
8383 message = MAY_LJMP(luaL_checkstring(L, 2));
8384
8385 /* Third and fourth argument : lua function. */
8386 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8387
Thierry Fournierf67442e2020-11-28 20:41:07 +01008388 /* Check for CLI service already registered */
8389 trash = get_trash_chunk();
8390 index = 0;
8391 lua_pushnil(L);
8392 memset(kw, 0, sizeof(kw));
8393 while (lua_next(L, 1) != 0) {
8394 if (index >= CLI_PREFIX_KW_NB)
8395 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8396 if (lua_type(L, -1) != LUA_TSTRING)
8397 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8398 kw[index] = lua_tostring(L, -1);
8399 if (index == 0)
8400 chunk_printf(trash, "%s", kw[index]);
8401 else
8402 chunk_appendf(trash, " %s", kw[index]);
8403 index++;
8404 lua_pop(L, 1);
8405 }
8406 cli_kw = cli_find_kw_exact((char **)kw);
8407 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008408 fcn = cli_kw->private;
8409 if (fcn->function_ref[hlua_state_id] != -1) {
8410 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
8411 "This will become a hard error in version 2.5.\n", trash->area);
8412 }
8413 fcn->function_ref[hlua_state_id] = ref_io;
8414 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008415 }
8416
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008417 /* Allocate and fill the sample fetch keyword struct. */
8418 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008419 if (!cli_kws) {
8420 errmsg = "Lua out of memory error.";
8421 goto error;
8422 }
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008423 fcn = new_hlua_function();
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008424 if (!fcn) {
8425 errmsg = "Lua out of memory error.";
8426 goto error;
8427 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008428
8429 /* Fill path. */
8430 index = 0;
8431 lua_pushnil(L);
8432 while(lua_next(L, 1) != 0) {
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008433 if (index >= 5) {
8434 errmsg = "1st argument must be a table with a maximum of 5 entries";
8435 goto error;
8436 }
8437 if (lua_type(L, -1) != LUA_TSTRING) {
8438 errmsg = "1st argument must be a table filled with strings";
8439 goto error;
8440 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008441 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008442 if (!cli_kws->kw[0].str_kw[index]) {
8443 errmsg = "Lua out of memory error.";
8444 goto error;
8445 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008446 index++;
8447 lua_pop(L, 1);
8448 }
8449
8450 /* Copy help message. */
8451 cli_kws->kw[0].usage = strdup(message);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008452 if (!cli_kws->kw[0].usage) {
8453 errmsg = "Lua out of memory error.";
8454 goto error;
8455 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008456
8457 /* Fill fcn io handler. */
8458 len = strlen("<lua.cli>") + 1;
8459 for (i = 0; i < index; i++)
8460 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8461 fcn->name = calloc(1, len);
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008462 if (!fcn->name) {
8463 errmsg = "Lua out of memory error.";
8464 goto error;
8465 }
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008466 strncat((char *)fcn->name, "<lua.cli", len);
8467 for (i = 0; i < index; i++) {
8468 strncat((char *)fcn->name, ".", len);
8469 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8470 }
8471 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +01008472 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008473
8474 /* Fill last entries. */
8475 cli_kws->kw[0].private = fcn;
8476 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8477 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8478 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8479
8480 /* Register this new converter */
8481 cli_register_kw(cli_kws);
8482
8483 return 0;
Christopher Faulet3a9a12b2021-04-12 15:31:29 +02008484
8485 error:
8486 release_hlua_function(fcn);
8487 if (cli_kws) {
8488 for (i = 0; i < index; i++)
8489 ha_free((char **)&(cli_kws->kw[0].str_kw[i]));
8490 ha_free((char **)&(cli_kws->kw[0].usage));
8491 }
8492 ha_free(&cli_kws);
8493 WILL_LJMP(luaL_error(L, errmsg));
8494 return 0; /* Never reached */
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008495}
8496
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008497static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008498 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008499 char **err, unsigned int *timeout)
8500{
8501 const char *error;
8502
8503 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02008504 if (error == PARSE_TIME_OVER) {
8505 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
8506 args[1], args[0]);
8507 return -1;
8508 }
8509 else if (error == PARSE_TIME_UNDER) {
8510 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
8511 args[1], args[0]);
8512 return -1;
8513 }
8514 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008515 memprintf(err, "%s: invalid timeout", args[0]);
8516 return -1;
8517 }
8518 return 0;
8519}
8520
8521static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008522 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008523 char **err)
8524{
8525 return hlua_read_timeout(args, section_type, curpx, defpx,
8526 file, line, err, &hlua_timeout_session);
8527}
8528
8529static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008530 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008531 char **err)
8532{
8533 return hlua_read_timeout(args, section_type, curpx, defpx,
8534 file, line, err, &hlua_timeout_task);
8535}
8536
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008537static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008538 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008539 char **err)
8540{
8541 return hlua_read_timeout(args, section_type, curpx, defpx,
8542 file, line, err, &hlua_timeout_applet);
8543}
8544
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008545static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008546 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008547 char **err)
8548{
8549 char *error;
8550
8551 hlua_nb_instruction = strtoll(args[1], &error, 10);
8552 if (*error != '\0') {
8553 memprintf(err, "%s: invalid number", args[0]);
8554 return -1;
8555 }
8556 return 0;
8557}
8558
Willy Tarreau32f61e22015-03-18 17:54:59 +01008559static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008560 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +01008561 char **err)
8562{
8563 char *error;
8564
8565 if (*(args[1]) == 0) {
8566 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8567 return -1;
8568 }
8569 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8570 if (*error != '\0') {
8571 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8572 return -1;
8573 }
8574 return 0;
8575}
8576
8577
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008578/* This function is called by the main configuration key "lua-load". It loads and
8579 * execute an lua file during the parsing of the HAProxy configuration file. It is
8580 * the main lua entry point.
8581 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008582 * This function runs with the HAProxy keywords API. It returns -1 if an error
8583 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008584 *
8585 * In some error case, LUA set an error message in top of the stack. This function
8586 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008587 *
8588 * This function can fail with an abort() due to an Lua critical error.
8589 * We are in the configuration parsing process of HAProxy, this abort() is
8590 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008591 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008592static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008593{
8594 int error;
8595
8596 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008597 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008598 if (error) {
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008599 memprintf(err, "error in Lua file '%s': %s", filename, hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008600 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008601 return -1;
8602 }
8603
8604 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008605 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008606 switch (error) {
8607 case LUA_OK:
8608 break;
8609 case LUA_ERRRUN:
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008610 memprintf(err, "Lua runtime error: %s\n", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008611 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008612 return -1;
8613 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +01008614 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008615 return -1;
8616 case LUA_ERRERR:
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008617 memprintf(err, "Lua message handler error: %s\n", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008618 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008619 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +02008620#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008621 case LUA_ERRGCMM:
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008622 memprintf(err, "Lua garbage collector error: %s\n", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008623 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008624 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +02008625#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008626 default:
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008627 memprintf(err, "Lua unknown error: %s\n", hlua_tostring_safe(L, -1));
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008628 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008629 return -1;
8630 }
8631
8632 return 0;
8633}
8634
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008635static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008636 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008637 char **err)
8638{
8639 if (*(args[1]) == 0) {
8640 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
8641 return -1;
8642 }
8643
Thierry Fournier59f11be2020-11-29 00:37:41 +01008644 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +01008645 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008646 ha_set_tid(0);
Thierry Fournierafc63e22020-11-28 17:06:51 +01008647 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008648}
8649
Thierry Fournier59f11be2020-11-29 00:37:41 +01008650static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008651 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +01008652 char **err)
8653{
8654 int len;
8655
8656 if (*(args[1]) == 0) {
8657 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
8658 return -1;
8659 }
8660
8661 if (per_thread_load == NULL) {
8662 /* allocate the first entry large enough to store the final NULL */
8663 per_thread_load = calloc(1, sizeof(*per_thread_load));
8664 if (per_thread_load == NULL) {
8665 memprintf(err, "out of memory error");
8666 return -1;
8667 }
8668 }
8669
8670 /* count used entries */
8671 for (len = 0; per_thread_load[len] != NULL; len++)
8672 ;
8673
8674 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
8675 if (per_thread_load == NULL) {
8676 memprintf(err, "out of memory error");
8677 return -1;
8678 }
8679
8680 per_thread_load[len] = strdup(args[1]);
8681 per_thread_load[len + 1] = NULL;
8682
8683 if (per_thread_load[len] == NULL) {
8684 memprintf(err, "out of memory error");
8685 return -1;
8686 }
8687
8688 /* loading for thread 1 only */
8689 hlua_state_id = 1;
8690 ha_set_tid(0);
8691 return hlua_load_state(args[1], hlua_states[1], err);
8692}
8693
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008694/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
8695 * in the given <ctx>.
8696 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +01008697static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008698{
Thierry Fournier3fb9e512020-11-28 10:13:12 +01008699 lua_getglobal(L, "package"); /* push package variable */
8700 lua_pushstring(L, path); /* push given path */
8701 lua_pushstring(L, ";"); /* push semicolon */
8702 lua_getfield(L, -3, type); /* push old path */
8703 lua_concat(L, 3); /* concatenate to new path */
8704 lua_setfield(L, -2, type); /* store new path */
8705 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008706
8707 return 0;
8708}
8709
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008710static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008711 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008712 char **err)
8713{
8714 char *path;
8715 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008716 struct prepend_path *p = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008717
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008718 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008719 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008720 }
8721
8722 if (!(*args[1])) {
8723 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008724 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008725 }
8726 path = args[1];
8727
8728 if (*args[2]) {
8729 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
8730 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008731 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008732 }
8733 type = args[2];
8734 }
8735
Thierry Fournier59f11be2020-11-29 00:37:41 +01008736 p = calloc(1, sizeof(*p));
8737 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +01008738 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008739 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008740 }
8741 p->path = strdup(path);
8742 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +01008743 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008744 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008745 }
8746 p->type = strdup(type);
8747 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +01008748 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008749 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008750 }
Willy Tarreau2b718102021-04-21 07:32:39 +02008751 LIST_APPEND(&prepend_path_list, &p->l);
Thierry Fournier59f11be2020-11-29 00:37:41 +01008752
8753 hlua_prepend_path(hlua_states[0], type, path);
8754 hlua_prepend_path(hlua_states[1], type, path);
8755 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008756
8757err2:
8758 free(p->type);
8759 free(p->path);
8760err:
8761 free(p);
8762 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008763}
8764
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008765/* configuration keywords declaration */
8766static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008767 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008768 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +01008769 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008770 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8771 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008772 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008773 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008774 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008775 { 0, NULL, NULL },
8776}};
8777
Willy Tarreau0108d902018-11-25 19:14:37 +01008778INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8779
Christopher Fauletafd8f102018-11-08 11:34:21 +01008780
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008781/* This function can fail with an abort() due to an Lua critical error.
8782 * We are in the initialisation process of HAProxy, this abort() is
8783 * tolerated.
8784 */
Thierry Fournierb8cef172020-11-28 15:37:17 +01008785int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008786{
8787 struct hlua_init_function *init;
8788 const char *msg;
8789 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008790 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +01008791 const char *kind;
8792 const char *trace;
8793 int return_status = 1;
8794#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
8795 int nres;
8796#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008797
Willy Tarreaucdb53462020-12-02 12:12:00 +01008798 /* disable memory limit checks if limit is not set */
8799 if (!hlua_global_allocator.limit)
8800 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
8801
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008802 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +01008803 if (setjmp(safe_ljmp_env) != 0) {
8804 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +01008805 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008806 error = hlua_tostring_safe(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008807 else
8808 error = "critical error";
8809 fprintf(stderr, "Lua post-init: %s.\n", error);
8810 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +01008811 } else {
8812 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008813 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008814
Thierry Fournierb8cef172020-11-28 15:37:17 +01008815 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008816
Thierry Fournierc7492592020-11-28 23:57:24 +01008817 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +01008818 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Aurelien DARRAGON93591b42023-03-20 16:29:55 +01008819 /* function ref should be released right away since it was pushed
8820 * on the stack and will not be used anymore
8821 */
8822 hlua_unref(L, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +01008823
8824#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Aurelien DARRAGON2dec9502023-09-08 19:29:08 +02008825 ret = lua_resume(L, NULL, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +01008826#else
Aurelien DARRAGON2dec9502023-09-08 19:29:08 +02008827 ret = lua_resume(L, NULL, 0);
Thierry Fournier670db242020-11-28 10:49:59 +01008828#endif
8829 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008830 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +01008831
8832 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +01008833 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +01008834 break;
Thierry Fournier670db242020-11-28 10:49:59 +01008835
8836 case LUA_ERRERR:
8837 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008838 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +01008839 case LUA_ERRRUN:
8840 if (!kind)
8841 kind = "runtime error";
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01008842 msg = hlua_tostring_safe(L, -1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01008843 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +01008844 if (msg)
8845 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
8846 else
8847 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
Aurelien DARRAGONadac9322024-03-01 19:54:16 +01008848
8849 lua_settop(L, 0); /* Empty the stack. */
Thierry Fournier670db242020-11-28 10:49:59 +01008850 return_status = 0;
8851 break;
8852
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008853 default:
Thierry Fournier670db242020-11-28 10:49:59 +01008854 /* Unknown error */
8855 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008856 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +01008857 case LUA_YIELD:
8858 /* yield is not configured at this step, this state doesn't happen */
8859 if (!kind)
8860 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008861 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +01008862 case LUA_ERRMEM:
8863 if (!kind)
8864 kind = "out of memory error";
Aurelien DARRAGON93f5d8d2023-08-09 10:11:49 +02008865 lua_settop(L, 0); /* Empty the stack. */
Christopher Fauletd09cc512021-03-24 14:48:45 +01008866 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +01008867 ha_alert("Lua init: %s: %s\n", kind, trace);
8868 return_status = 0;
8869 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008870 }
Thierry Fournier670db242020-11-28 10:49:59 +01008871 if (!return_status)
8872 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008873 }
Thierry Fournier3c539322020-11-28 16:05:05 +01008874
8875 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +01008876 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008877}
8878
Thierry Fournierb8cef172020-11-28 15:37:17 +01008879int hlua_post_init()
8880{
Thierry Fournier59f11be2020-11-29 00:37:41 +01008881 int ret;
8882 int i;
8883 int errors;
8884 char *err = NULL;
8885 struct hlua_function *fcn;
8886
Willy Tarreau42afc592021-08-30 09:35:18 +02008887#if defined(USE_OPENSSL)
Thierry Fournierb8cef172020-11-28 15:37:17 +01008888 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01008889 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +01008890 int saved_used_backed = global.ssl_used_backend;
8891 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01008892 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +01008893 global.ssl_used_backend = saved_used_backed;
8894 }
8895#endif
8896
Thierry Fournierc7492592020-11-28 23:57:24 +01008897 /* Perform post init of common thread */
8898 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008899 ha_set_tid(0);
8900 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
8901 if (ret == 0)
8902 return 0;
8903
8904 /* init remaining lua states and load files */
8905 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
8906
8907 /* set thread context */
8908 ha_set_tid(hlua_state_id - 1);
8909
8910 /* Init lua state */
8911 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
8912
8913 /* Load lua files */
8914 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
8915 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
8916 if (ret != 0) {
8917 ha_alert("Lua init: %s\n", err);
8918 return 0;
8919 }
8920 }
8921 }
8922
8923 /* Reset thread context */
8924 ha_set_tid(0);
8925
8926 /* Execute post init for all states */
8927 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
8928
8929 /* set thread context */
8930 ha_set_tid(hlua_state_id - 1);
8931
8932 /* run post init */
8933 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
8934 if (ret == 0)
8935 return 0;
8936 }
8937
8938 /* Reset thread context */
8939 ha_set_tid(0);
8940
8941 /* control functions registering. Each function must have:
8942 * - only the function_ref[0] set positive and all other to -1
8943 * - only the function_ref[0] set to -1 and all other positive
8944 * This ensure a same reference is not used both in shared
8945 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05008946 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +01008947 * complicated to found for the end user.
8948 */
8949 errors = 0;
8950 list_for_each_entry(fcn, &referenced_functions, l) {
8951 ret = 0;
8952 for (i = 1; i < global.nbthread + 1; i++) {
8953 if (fcn->function_ref[i] == -1)
8954 ret--;
8955 else
8956 ret++;
8957 }
8958 if (abs(ret) != global.nbthread) {
8959 ha_alert("Lua function '%s' is not referenced in all thread. "
8960 "Expect function in all thread or in none thread.\n", fcn->name);
8961 errors++;
8962 continue;
8963 }
8964
8965 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05008966 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
8967 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +01008968 "exclusive.\n", fcn->name);
8969 errors++;
8970 }
8971 }
8972
8973 if (errors > 0)
8974 return 0;
8975
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05008976 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +01008977 * -1 in order to have probably a segfault if someone use it
8978 */
8979 hlua_state_id = -1;
8980
8981 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +01008982}
8983
Willy Tarreau32f61e22015-03-18 17:54:59 +01008984/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8985 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8986 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +01008987 * allocation. <nsize> is the requested new size. A new allocation is
8988 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +01008989 * zero. This one verifies that the limits are respected but is optimized
8990 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreaue00ad052021-10-22 16:00:02 +02008991 *
8992 * Warning: while this API ressembles glibc's realloc() a lot, glibc surpasses
8993 * POSIX by making realloc(ptr,0) an effective free(), but others do not do
8994 * that and will simply allocate zero as if it were the result of malloc(0),
8995 * so mapping this onto realloc() will lead to memory leaks on non-glibc
8996 * systems.
Willy Tarreau32f61e22015-03-18 17:54:59 +01008997 */
8998static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8999{
9000 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +01009001 size_t limit, old, new;
9002
Tim Duesterhus22586522021-01-08 10:35:33 +01009003 if (unlikely(!ptr && !nsize))
9004 return NULL;
9005
Willy Tarreaucdb53462020-12-02 12:12:00 +01009006 /* a limit of ~0 means unlimited and boot complete, so there's no need
9007 * for accounting anymore.
9008 */
Willy Tarreaue00ad052021-10-22 16:00:02 +02009009 if (likely(~zone->limit == 0)) {
9010 if (!nsize)
9011 ha_free(&ptr);
9012 else
9013 ptr = realloc(ptr, nsize);
9014 return ptr;
9015 }
Willy Tarreau32f61e22015-03-18 17:54:59 +01009016
Willy Tarreaud36c7fa2020-12-02 12:26:29 +01009017 if (!ptr)
9018 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +01009019
Willy Tarreaucdb53462020-12-02 12:12:00 +01009020 /* enforce strict limits across all threads */
9021 limit = zone->limit;
9022 old = _HA_ATOMIC_LOAD(&zone->allocated);
9023 do {
9024 new = old + nsize - osize;
9025 if (unlikely(nsize && limit && new > limit))
9026 return NULL;
9027 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +01009028
Willy Tarreaue00ad052021-10-22 16:00:02 +02009029 if (!nsize)
9030 ha_free(&ptr);
9031 else
9032 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +01009033
9034 if (unlikely(!ptr && nsize)) // failed
9035 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
9036
9037 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +01009038 return ptr;
9039}
9040
Thierry Fournierecb83c22020-11-28 15:49:44 +01009041/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009042 * We are in the initialisation process of HAProxy, this abort() is
9043 * tolerated.
9044 */
Thierry Fournierecb83c22020-11-28 15:49:44 +01009045lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01009046{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009047 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009048 int idx;
9049 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009050 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009051 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01009052 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009053 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009054 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +01009055 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009056
Thierry FOURNIER380d0932015-01-23 14:27:52 +01009057 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009058 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01009059
firexinghebdd336c2023-07-13 11:03:34 +08009060 if (!L) {
9061 fprintf(stderr,
9062 "Lua init: critical error: lua_newstate() returned NULL."
9063 " This may possibly be caused by a memory allocation error.\n");
9064 exit(1);
9065 }
9066
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009067 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009068 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01009069 *context = NULL;
9070
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009071 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02009072 * the Lua function can fail with an abort. We are in the initialisation
9073 * process of HAProxy, this abort() is tolerated.
9074 */
9075
Thierry Fournier3c539322020-11-28 16:05:05 +01009076 /* Call post initialisation function in safe environment. */
9077 if (setjmp(safe_ljmp_env) != 0) {
9078 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009079 if (lua_type(L, -1) == LUA_TSTRING)
Aurelien DARRAGONa3741612024-03-01 15:55:17 +01009080 error_msg = hlua_tostring_safe(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +01009081 else
9082 error_msg = "critical error";
9083 fprintf(stderr, "Lua init: %s.\n", error_msg);
9084 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +01009085 } else {
9086 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +01009087 }
9088
Thierry FOURNIER380d0932015-01-23 14:27:52 +01009089 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009090 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01009091#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
9092#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
9093#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009094 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01009095#endif
9096#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009097 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01009098#endif
9099#undef HLUA_PREPEND_PATH_TOSTRING
9100#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009101
Thierry Fournier59f11be2020-11-29 00:37:41 +01009102 /* Apply configured prepend path */
9103 list_for_each_entry(pp, &prepend_path_list, l)
9104 hlua_prepend_path(L, pp->type, pp->path);
9105
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009106 /*
9107 *
9108 * Create "core" object.
9109 *
9110 */
9111
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01009112 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009113 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009114
Thierry Fournierecb83c22020-11-28 15:49:44 +01009115 /* set the thread id */
9116 hlua_class_const_int(L, "thread", thread_num);
9117
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009118 /* Push the loglevel constants. */
Christopher Faulet8263e942024-02-29 15:41:17 +01009119 hlua_class_const_int(L, "silent", -1);
Willy Tarreau80f5fae2015-02-27 16:38:20 +01009120 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009121 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01009122
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009123 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009124 hlua_class_function(L, "register_init", hlua_register_init);
9125 hlua_class_function(L, "register_task", hlua_register_task);
9126 hlua_class_function(L, "register_fetches", hlua_register_fetches);
9127 hlua_class_function(L, "register_converters", hlua_register_converters);
9128 hlua_class_function(L, "register_action", hlua_register_action);
9129 hlua_class_function(L, "register_service", hlua_register_service);
9130 hlua_class_function(L, "register_cli", hlua_register_cli);
9131 hlua_class_function(L, "yield", hlua_yield);
9132 hlua_class_function(L, "set_nice", hlua_set_nice);
9133 hlua_class_function(L, "sleep", hlua_sleep);
9134 hlua_class_function(L, "msleep", hlua_msleep);
9135 hlua_class_function(L, "add_acl", hlua_add_acl);
9136 hlua_class_function(L, "del_acl", hlua_del_acl);
9137 hlua_class_function(L, "set_map", hlua_set_map);
9138 hlua_class_function(L, "del_map", hlua_del_map);
9139 hlua_class_function(L, "tcp", hlua_socket_new);
9140 hlua_class_function(L, "log", hlua_log);
9141 hlua_class_function(L, "Debug", hlua_log_debug);
9142 hlua_class_function(L, "Info", hlua_log_info);
9143 hlua_class_function(L, "Warning", hlua_log_warning);
9144 hlua_class_function(L, "Alert", hlua_log_alert);
9145 hlua_class_function(L, "done", hlua_done);
9146 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01009147
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009148 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009149
9150 /*
9151 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +01009152 * Create "act" object.
9153 *
9154 */
9155
9156 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009157 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +01009158
9159 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009160 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
9161 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
9162 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
9163 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
9164 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
9165 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
9166 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
9167 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +01009168
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009169 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01009170
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009171 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +01009172
9173 /*
9174 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009175 * Register class Map
9176 *
9177 */
9178
9179 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009180 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009181
9182 /* register pattern types. */
9183 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009184 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01009185 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02009186 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009187 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01009188 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009189
9190 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009191 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009192
9193 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009194 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009195
Ilya Shipitsind4259502020-04-08 01:07:56 +05009196 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009197 lua_pushstring(L, "__index");
9198 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009199
9200 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009201 hlua_class_function(L, "lookup", hlua_map_lookup);
9202 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009203
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009204 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009205
Thierry Fournier45e78d72016-02-19 18:34:46 +01009206 /* Register previous table in the registry with reference and named entry.
9207 * The function hlua_register_metatable() pops the stack, so we
9208 * previously create a copy of the table.
9209 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009210 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
9211 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009212
9213 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009214 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009215
9216 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009217 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +02009218
9219 /*
9220 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009221 * Register class Channel
9222 *
9223 */
9224
9225 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009226 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009227
Ilya Shipitsind4259502020-04-08 01:07:56 +05009228 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009229 lua_pushstring(L, "__index");
9230 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009231
9232 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009233 hlua_class_function(L, "get", hlua_channel_get);
9234 hlua_class_function(L, "dup", hlua_channel_dup);
9235 hlua_class_function(L, "getline", hlua_channel_getline);
9236 hlua_class_function(L, "set", hlua_channel_set);
9237 hlua_class_function(L, "append", hlua_channel_append);
9238 hlua_class_function(L, "send", hlua_channel_send);
9239 hlua_class_function(L, "forward", hlua_channel_forward);
9240 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
9241 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
9242 hlua_class_function(L, "is_full", hlua_channel_is_full);
9243 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009244
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009245 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009246
9247 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009248 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01009249
9250 /*
9251 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009252 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009253 *
9254 */
9255
9256 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009257 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009258
Ilya Shipitsind4259502020-04-08 01:07:56 +05009259 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009260 lua_pushstring(L, "__index");
9261 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009262
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009263 /* Browse existing fetches and create the associated
9264 * object method.
9265 */
9266 sf = NULL;
9267 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009268 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
9269 * by an underscore.
9270 */
Willy Tarreaufa92f362021-08-26 16:48:53 +02009271 strlcpy2(trash.area, sf->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02009272 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009273 if (*p == '.' || *p == '-' || *p == '+')
9274 *p = '_';
9275
9276 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009277 lua_pushstring(L, trash.area);
9278 lua_pushlightuserdata(L, sf);
9279 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
9280 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01009281 }
9282
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009283 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009284
9285 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009286 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009287
9288 /*
9289 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009290 * Register class Converters
9291 *
9292 */
9293
9294 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009295 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009296
9297 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009298 lua_pushstring(L, "__index");
9299 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009300
9301 /* Browse existing converters and create the associated
9302 * object method.
9303 */
9304 sc = NULL;
9305 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009306 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
9307 * by an underscore.
9308 */
Willy Tarreaufa92f362021-08-26 16:48:53 +02009309 strlcpy2(trash.area, sc->kw, trash.size);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02009310 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009311 if (*p == '.' || *p == '-' || *p == '+')
9312 *p = '_';
9313
9314 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009315 lua_pushstring(L, trash.area);
9316 lua_pushlightuserdata(L, sc);
9317 lua_pushcclosure(L, hlua_run_sample_conv, 1);
9318 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009319 }
9320
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009321 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009322
9323 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009324 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01009325
9326 /*
9327 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009328 * Register class HTTP
9329 *
9330 */
9331
9332 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009333 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009334
Ilya Shipitsind4259502020-04-08 01:07:56 +05009335 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009336 lua_pushstring(L, "__index");
9337 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009338
9339 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009340 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
9341 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
9342 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
9343 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
9344 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
9345 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
9346 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
9347 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
9348 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
9349 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009350
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009351 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
9352 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
9353 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
9354 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
9355 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
9356 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
9357 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009358
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009359 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009360
9361 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009362 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009363
9364 /*
9365 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009366 * Register class AppletTCP
9367 *
9368 */
9369
9370 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009371 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009372
Ilya Shipitsind4259502020-04-08 01:07:56 +05009373 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009374 lua_pushstring(L, "__index");
9375 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009376
9377 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009378 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
9379 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
9380 hlua_class_function(L, "send", hlua_applet_tcp_send);
9381 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
9382 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
9383 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
9384 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
9385 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009386
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009387 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009388
9389 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009390 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009391
9392 /*
9393 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009394 * Register class AppletHTTP
9395 *
9396 */
9397
9398 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009399 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009400
Ilya Shipitsind4259502020-04-08 01:07:56 +05009401 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009402 lua_pushstring(L, "__index");
9403 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009404
9405 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009406 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
9407 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
9408 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
9409 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
9410 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
9411 hlua_class_function(L, "getline", hlua_applet_http_getline);
9412 hlua_class_function(L, "receive", hlua_applet_http_recv);
9413 hlua_class_function(L, "send", hlua_applet_http_send);
9414 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
9415 hlua_class_function(L, "set_status", hlua_applet_http_status);
9416 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009417
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009418 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009419
9420 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009421 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009422
9423 /*
9424 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009425 * Register class TXN
9426 *
9427 */
9428
9429 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009430 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009431
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 FOURNIERbb53c7b2015-03-11 18:28:02 +01009435
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01009436 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009437 hlua_class_function(L, "set_priv", hlua_set_priv);
9438 hlua_class_function(L, "get_priv", hlua_get_priv);
9439 hlua_class_function(L, "set_var", hlua_set_var);
9440 hlua_class_function(L, "unset_var", hlua_unset_var);
9441 hlua_class_function(L, "get_var", hlua_get_var);
9442 hlua_class_function(L, "done", hlua_txn_done);
9443 hlua_class_function(L, "reply", hlua_txn_reply_new);
9444 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
9445 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
9446 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
9447 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
9448 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
9449 hlua_class_function(L, "deflog", hlua_txn_deflog);
9450 hlua_class_function(L, "log", hlua_txn_log);
9451 hlua_class_function(L, "Debug", hlua_txn_log_debug);
9452 hlua_class_function(L, "Info", hlua_txn_log_info);
9453 hlua_class_function(L, "Warning", hlua_txn_log_warning);
9454 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01009455
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009456 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009457
9458 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009459 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009460
9461 /*
9462 *
Christopher Faulet700d9e82020-01-31 12:21:52 +01009463 * Register class reply
9464 *
9465 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009466 lua_newtable(L);
9467 lua_pushstring(L, "__index");
9468 lua_newtable(L);
9469 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
9470 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
9471 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
9472 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
9473 lua_settable(L, -3); /* Sets the __index entry. */
9474 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +01009475
9476
9477 /*
9478 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009479 * Register class Socket
9480 *
9481 */
9482
9483 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009484 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009485
Ilya Shipitsind4259502020-04-08 01:07:56 +05009486 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009487 lua_pushstring(L, "__index");
9488 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009489
Baptiste Assmann84bb4932015-03-02 21:40:06 +01009490#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009491 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01009492#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009493 hlua_class_function(L, "connect", hlua_socket_connect);
9494 hlua_class_function(L, "send", hlua_socket_send);
9495 hlua_class_function(L, "receive", hlua_socket_receive);
9496 hlua_class_function(L, "close", hlua_socket_close);
9497 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
9498 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
9499 hlua_class_function(L, "setoption", hlua_socket_setoption);
9500 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009501
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009502 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009503
9504 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009505 lua_pushstring(L, "__gc");
9506 lua_pushcclosure(L, hlua_socket_gc, 0);
9507 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009508
9509 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009510 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009511
Thierry Fournieraafc7772020-12-04 11:47:47 +01009512 lua_atpanic(L, hlua_panic_safe);
9513
9514 return L;
9515}
9516
9517void hlua_init(void) {
9518 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01009519 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +01009520#ifdef USE_OPENSSL
9521 struct srv_kw *kw;
9522 int tmp_error;
9523 char *error;
9524 char *args[] = { /* SSL client configuration. */
9525 "ssl",
9526 "verify",
9527 "none",
9528 NULL
9529 };
9530#endif
9531
9532 /* Init post init function list head */
9533 for (i = 0; i < MAX_THREADS + 1; i++)
9534 LIST_INIT(&hlua_init_functions[i]);
9535
9536 /* Init state for common/shared lua parts */
9537 hlua_state_id = 0;
9538 ha_set_tid(0);
9539 hlua_states[0] = hlua_init_state(0);
9540
9541 /* Init state 1 for thread 0. We have at least one thread. */
9542 hlua_state_id = 1;
9543 ha_set_tid(0);
9544 hlua_states[1] = hlua_init_state(1);
9545
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009546 /* Proxy and server configuration initialisation. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01009547 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_LUA, &errmsg);
9548 if (!socket_proxy) {
9549 fprintf(stderr, "Lua init: %s\n", errmsg);
9550 exit(1);
9551 }
9552 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009553
9554 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009555 socket_tcp = new_server(socket_proxy);
9556 if (!socket_tcp) {
9557 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
9558 exit(1);
9559 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009560
9561#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009562 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009563 socket_ssl = new_server(socket_proxy);
9564 if (!socket_ssl) {
9565 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
9566 exit(1);
9567 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009568
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009569 socket_ssl->use_ssl = 1;
9570 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009571
Bertrand Jacquin80839ff2021-01-21 19:14:46 +00009572 for (i = 0; args[i] != NULL; i++) {
9573 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009574 /*
9575 *
9576 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009577 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009578 * features like client certificates and ssl_verify.
9579 *
9580 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009581 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009582 if (tmp_error != 0) {
9583 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
9584 abort(); /* This must be never arrives because the command line
9585 not editable by the user. */
9586 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +00009587 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009588 }
9589 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009590#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01009591
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01009592}
Willy Tarreaubb57d942016-12-21 19:04:56 +01009593
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +02009594static void hlua_deinit()
9595{
Willy Tarreau186f3762020-12-04 11:48:12 +01009596 int thr;
9597
9598 for (thr = 0; thr < MAX_THREADS+1; thr++) {
9599 if (hlua_states[thr])
9600 lua_close(hlua_states[thr]);
9601 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +01009602
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009603 free_server(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +01009604
Willy Tarreau0f143af2021-03-05 10:41:48 +01009605#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009606 free_server(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +01009607#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01009608
9609 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +02009610}
9611
9612REGISTER_POST_DEINIT(hlua_deinit);
9613
Willy Tarreau80713382018-11-26 10:19:54 +01009614static void hlua_register_build_options(void)
9615{
Willy Tarreaubb57d942016-12-21 19:04:56 +01009616 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01009617
Willy Tarreaubb57d942016-12-21 19:04:56 +01009618 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
9619 hap_register_build_opts(ptr, 1);
9620}
Willy Tarreau80713382018-11-26 10:19:54 +01009621
9622INITCALL0(STG_REGISTER, hlua_register_build_options);