blob: 8f88f6fe6d1c981cb0a22647b9648761e5710351 [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 Jacquin892e4fd2021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Mark Lakes56cc1252018-03-27 09:48:06 +020016#include <limits.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020017#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010018
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010019#include <lauxlib.h>
20#include <lua.h>
21#include <lualib.h>
22
Thierry FOURNIER463119c2015-03-10 00:35:36 +010023#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
24#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010025#endif
26
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027#include <ebpttree.h>
28
29#include <common/cfgparse.h>
Willy Tarreaub059b892018-10-16 17:57:36 +020030#include <common/compiler.h>
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +020031#include <common/hathreads.h>
Willy Tarreau0108d902018-11-25 19:14:37 +010032#include <common/initcall.h>
33#include <common/xref.h>
Christopher Faulet724a12c2018-12-13 22:12:15 +010034#include <common/h1.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010035
William Lallemand9ed62032016-11-21 17:49:11 +010036#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010037#include <types/hlua.h>
38#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010039#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010040
Thierry FOURNIER55da1652015-01-23 11:36:30 +010041#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020042#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010043#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010044#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010045#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010046#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010047#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010048#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010049#include <proto/hlua_fcn.h>
Willy Tarreau79e57332018-10-02 16:01:16 +020050#include <proto/http_fetch.h>
Christopher Faulet724a12c2018-12-13 22:12:15 +010051#include <proto/http_htx.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020052#include <proto/http_rules.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020053#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010054#include <proto/obj_type.h>
Patrick Hemmer268a7072018-05-11 12:52:31 -040055#include <proto/queue.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010056#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010057#include <proto/payload.h>
58#include <proto/proto_http.h>
59#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010060#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020061#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020062#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010063#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010064#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010065#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020066#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010067
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010068/* Lua uses longjmp to perform yield or throwing errors. This
69 * macro is used only for identifying the function that can
70 * not return because a longjmp is executed.
71 * __LJMP marks a prototype of hlua file that can use longjmp.
72 * WILL_LJMP() marks an lua function that will use longjmp.
73 * MAY_LJMP() marks an lua function that may use longjmp.
74 */
75#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020076#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010077#define MAY_LJMP(func) func
78
Thierry FOURNIERbabae282015-09-17 11:36:37 +020079/* This couple of function executes securely some Lua calls outside of
80 * the lua runtime environment. Each Lua call can return a longjmp
81 * if it encounter a memory error.
82 *
83 * Lua documentation extract:
84 *
85 * If an error happens outside any protected environment, Lua calls
86 * a panic function (see lua_atpanic) and then calls abort, thus
87 * exiting the host application. Your panic function can avoid this
88 * exit by never returning (e.g., doing a long jump to your own
89 * recovery point outside Lua).
90 *
91 * The panic function runs as if it were a message handler (see
92 * §2.3); in particular, the error message is at the top of the
93 * stack. However, there is no guarantee about stack space. To push
94 * anything on the stack, the panic function must first check the
95 * available space (see §4.2).
96 *
97 * We must check all the Lua entry point. This includes:
98 * - The include/proto/hlua.h exported functions
99 * - the task wrapper function
100 * - The action wrapper function
101 * - The converters wrapper function
102 * - The sample-fetch wrapper functions
103 *
104 * It is tolerated that the initilisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800105 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200106 *
107 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
108 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
109 * because they must be exists in the program stack when the longjmp
110 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200111 *
112 * Note that the Lua processing is not really thread safe. It provides
113 * heavy system which consists to add our own lock function in the Lua
114 * code and recompile the library. This system will probably not accepted
115 * by maintainers of various distribs.
116 *
117 * Our main excution point of the Lua is the function lua_resume(). A
118 * quick looking on the Lua sources displays a lua_lock() a the start
119 * of function and a lua_unlock() at the end of the function. So I
120 * conclude that the Lua thread safe mode just perform a mutex around
121 * all execution. So I prefer to do this in the HAProxy code, it will be
122 * easier for distro maintainers.
123 *
124 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
125 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
126 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200127 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100128__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200129THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200130static int hlua_panic_safe(lua_State *L) { return 0; }
131static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
132
133#define SET_SAFE_LJMP(__L) \
134 ({ \
135 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100136 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200137 if (setjmp(safe_ljmp_env) != 0) { \
138 lua_atpanic(__L, hlua_panic_safe); \
139 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100140 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200141 } else { \
142 lua_atpanic(__L, hlua_panic_ljmp); \
143 ret = 1; \
144 } \
145 ret; \
146 })
147
148/* If we are the last function catching Lua errors, we
149 * must reset the panic function.
150 */
151#define RESET_SAFE_LJMP(__L) \
152 do { \
153 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100154 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200155 } while(0)
156
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200157/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200158#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100159/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200160#define APPLET_HDR_SENT 0x04 /* Response header sent. */
161#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
162#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100163#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100164#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200165
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100166/* The main Lua execution context. */
167struct hlua gL;
168
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100169/* This is the memory pool containing struct lua for applets
170 * (including cli).
171 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100172DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100173
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100174/* Used for Socket connection. */
175static struct proxy socket_proxy;
176static struct server socket_tcp;
177#ifdef USE_OPENSSL
178static struct server socket_ssl;
179#endif
180
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100181/* List head of the function called at the initialisation time. */
182struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
183
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100184/* The following variables contains the reference of the different
185 * Lua classes. These references are useful for identify metadata
186 * associated with an object.
187 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100188static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100189static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100190static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100191static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100192static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100193static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200194static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200195static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200196static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100197
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100198/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200199 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100200 * short timeout. Lua linked with tasks doesn't have a timeout
201 * because a task may remain alive during all the haproxy execution.
202 */
203static unsigned int hlua_timeout_session = 4000; /* session timeout. */
204static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200205static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100206
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100207/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
208 * it is used for preventing infinite loops.
209 *
210 * I test the scheer with an infinite loop containing one incrementation
211 * and one test. I run this loop between 10 seconds, I raise a ceil of
212 * 710M loops from one interrupt each 9000 instructions, so I fix the value
213 * to one interrupt each 10 000 instructions.
214 *
215 * configured | Number of
216 * instructions | loops executed
217 * between two | in milions
218 * forced yields |
219 * ---------------+---------------
220 * 10 | 160
221 * 500 | 670
222 * 1000 | 680
223 * 5000 | 700
224 * 7000 | 700
225 * 8000 | 700
226 * 9000 | 710 <- ceil
227 * 10000 | 710
228 * 100000 | 710
229 * 1000000 | 710
230 *
231 */
232static unsigned int hlua_nb_instruction = 10000;
233
Willy Tarreau32f61e22015-03-18 17:54:59 +0100234/* Descriptor for the memory allocation state. If limit is not null, it will
235 * be enforced on any memory allocation.
236 */
237struct hlua_mem_allocator {
238 size_t allocated;
239 size_t limit;
240};
241
242static struct hlua_mem_allocator hlua_global_allocator;
243
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200244static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200245 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200246 "Cache-Control: no-cache\r\n"
247 "Connection: close\r\n"
248 "Content-Type: text/html\r\n"
249 "\r\n"
Joseph Herlant7fe15772018-11-15 10:07:32 -0800250 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occurred.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200251
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100252/* These functions converts types between HAProxy internal args or
253 * sample and LUA types. Another function permits to check if the
254 * LUA stack contains arguments according with an required ARG_T
255 * format.
256 */
257static int hlua_arg2lua(lua_State *L, const struct arg *arg);
258static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100259__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100260 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100261static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100262static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100263static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
264
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200265__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
266
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200267#define SEND_ERR(__be, __fmt, __args...) \
268 do { \
269 send_log(__be, LOG_ERR, __fmt, ## __args); \
270 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100271 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200272 } while (0)
273
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100274/* Used to check an Lua function type in the stack. It creates and
275 * returns a reference of the function. This function throws an
276 * error if the rgument is not a "function".
277 */
278__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
279{
280 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100281 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100282 WILL_LJMP(luaL_argerror(L, argno, msg));
283 }
284 lua_pushvalue(L, argno);
285 return luaL_ref(L, LUA_REGISTRYINDEX);
286}
287
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200288/* Return the string that is of the top of the stack. */
289const char *hlua_get_top_error_string(lua_State *L)
290{
291 if (lua_gettop(L) < 1)
292 return "unknown error";
293 if (lua_type(L, -1) != LUA_TSTRING)
294 return "unknown error";
295 return lua_tostring(L, -1);
296}
297
Christopher Faulet979865e2021-03-24 14:48:45 +0100298__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200299{
300 lua_Debug ar;
301 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200302 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200303
304 while (lua_getstack(L, level++, &ar)) {
305
306 /* Add separator */
Christopher Faulet979865e2021-03-24 14:48:45 +0100307 if (b_data(msg))
308 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200309
310 /* Fill fields:
311 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
312 * 'l': fills in the field currentline;
313 * 'n': fills in the field name and namewhat;
314 * 't': fills in the field istailcall;
315 */
316 lua_getinfo(L, "Slnt", &ar);
317
318 /* Append code localisation */
319 if (ar.currentline > 0)
Christopher Faulet979865e2021-03-24 14:48:45 +0100320 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200321 else
Christopher Faulet979865e2021-03-24 14:48:45 +0100322 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200323
324 /*
325 * Get function name
326 *
327 * if namewhat is no empty, name is defined.
328 * what contains "Lua" for Lua function, "C" for C function,
329 * or "main" for main code.
330 */
331 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Faulet979865e2021-03-24 14:48:45 +0100332 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200333
334 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Faulet979865e2021-03-24 14:48:45 +0100335 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200336
337 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Faulet979865e2021-03-24 14:48:45 +0100338 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200339
340 else /* nothing left... */
341 chunk_appendf(msg, "?");
342
343
344 /* Display tailed call */
345 if (ar.istailcall)
346 chunk_appendf(msg, " ...");
347 }
348
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200349 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200350}
351
352
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100353/* This function check the number of arguments available in the
354 * stack. If the number of arguments available is not the same
355 * then <nb> an error is throwed.
356 */
357__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
358{
359 if (lua_gettop(L) == nb)
360 return;
361 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
362}
363
Mark Lakes22154b42018-01-29 14:38:40 -0800364/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100365 * and the line number where the error is encountered.
366 */
367static int hlua_pusherror(lua_State *L, const char *fmt, ...)
368{
369 va_list argp;
370 va_start(argp, fmt);
371 luaL_where(L, 1);
372 lua_pushvfstring(L, fmt, argp);
373 va_end(argp);
374 lua_concat(L, 2);
375 return 1;
376}
377
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100378/* This functions is used with sample fetch and converters. It
379 * converts the HAProxy configuration argument in a lua stack
380 * values.
381 *
382 * It takes an array of "arg", and each entry of the array is
383 * converted and pushed in the LUA stack.
384 */
385static int hlua_arg2lua(lua_State *L, const struct arg *arg)
386{
387 switch (arg->type) {
388 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100389 case ARGT_TIME:
390 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100391 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100392 break;
393
394 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200395 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100396 break;
397
398 case ARGT_IPV4:
399 case ARGT_IPV6:
400 case ARGT_MSK4:
401 case ARGT_MSK6:
402 case ARGT_FE:
403 case ARGT_BE:
404 case ARGT_TAB:
405 case ARGT_SRV:
406 case ARGT_USR:
407 case ARGT_MAP:
408 default:
409 lua_pushnil(L);
410 break;
411 }
412 return 1;
413}
414
415/* This function take one entrie in an LUA stack at the index "ud",
416 * and try to convert it in an HAProxy argument entry. This is useful
417 * with sample fetch wrappers. The input arguments are gived to the
418 * lua wrapper and converted as arg list by thi function.
419 */
420static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
421{
422 switch (lua_type(L, ud)) {
423
424 case LUA_TNUMBER:
425 case LUA_TBOOLEAN:
426 arg->type = ARGT_SINT;
427 arg->data.sint = lua_tointeger(L, ud);
428 break;
429
430 case LUA_TSTRING:
431 arg->type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200432 arg->data.str.area = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.data);
Tim Duesterhusf371b832019-09-29 23:03:07 +0200433 /* We don't know the actual size of the underlying allocation, so be conservative. */
434 arg->data.str.size = arg->data.str.data;
435 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100436 break;
437
438 case LUA_TUSERDATA:
439 case LUA_TNIL:
440 case LUA_TTABLE:
441 case LUA_TFUNCTION:
442 case LUA_TTHREAD:
443 case LUA_TLIGHTUSERDATA:
444 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200445 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100446 break;
447 }
448 return 1;
449}
450
451/* the following functions are used to convert a struct sample
452 * in Lua type. This useful to convert the return of the
453 * fetchs or converters.
454 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100455static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100456{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200457 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100458 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100459 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200460 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100461 break;
462
463 case SMP_T_BIN:
464 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200465 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100466 break;
467
468 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200469 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100470 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
471 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
472 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
473 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
474 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
475 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
476 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
477 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
478 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200479 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100480 break;
481 default:
482 lua_pushnil(L);
483 break;
484 }
485 break;
486
487 case SMP_T_IPV4:
488 case SMP_T_IPV6:
489 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200490 if (sample_casts[smp->data.type][SMP_T_STR] &&
491 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200492 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100493 else
494 lua_pushnil(L);
495 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100496 default:
497 lua_pushnil(L);
498 break;
499 }
500 return 1;
501}
502
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100503/* the following functions are used to convert a struct sample
504 * in Lua strings. This is useful to convert the return of the
505 * fetchs or converters.
506 */
507static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
508{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200509 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100510
511 case SMP_T_BIN:
512 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200513 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100514 break;
515
516 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200517 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100518 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
519 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
520 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
521 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
522 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
523 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
524 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
525 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
526 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200527 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100528 break;
529 default:
530 lua_pushstring(L, "");
531 break;
532 }
533 break;
534
535 case SMP_T_SINT:
536 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100537 case SMP_T_IPV4:
538 case SMP_T_IPV6:
539 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200540 if (sample_casts[smp->data.type][SMP_T_STR] &&
541 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200542 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100543 else
544 lua_pushstring(L, "");
545 break;
546 default:
547 lua_pushstring(L, "");
548 break;
549 }
550 return 1;
551}
552
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100553/* the following functions are used to convert an Lua type in a
554 * struct sample. This is useful to provide data from a converter
555 * to the LUA code.
556 */
557static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
558{
559 switch (lua_type(L, ud)) {
560
561 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200562 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200563 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100564 break;
565
566
567 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200568 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200569 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100570 break;
571
572 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200573 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100574 smp->flags |= SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200575 smp->data.u.str.area = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.data);
Tim Duesterhusf371b832019-09-29 23:03:07 +0200576 /* We don't know the actual size of the underlying allocation, so be conservative. */
577 smp->data.u.str.size = smp->data.u.str.data;
578 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100579 break;
580
581 case LUA_TUSERDATA:
582 case LUA_TNIL:
583 case LUA_TTABLE:
584 case LUA_TFUNCTION:
585 case LUA_TTHREAD:
586 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200587 case LUA_TNONE:
588 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200589 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200590 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100591 break;
592 }
593 return 1;
594}
595
596/* This function check the "argp" builded by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800597 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100599 *
600 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
601 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100603__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100604 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100605{
606 int min_arg;
607 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100608 struct proxy *px;
609 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100610
611 idx = 0;
612 min_arg = ARGM(mask);
613 mask >>= ARGM_BITS;
614
615 while (1) {
616
617 /* Check oversize. */
618 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100619 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100620 }
621
622 /* Check for mandatory arguments. */
623 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100624 if (idx < min_arg) {
625
626 /* If miss other argument than the first one, we return an error. */
627 if (idx > 0)
628 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
629
630 /* If first argument have a certain type, some default values
631 * may be used. See the function smp_resolve_args().
632 */
633 switch (mask & ARGT_MASK) {
634
635 case ARGT_FE:
636 if (!(p->cap & PR_CAP_FE))
637 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
638 argp[idx].data.prx = p;
639 argp[idx].type = ARGT_FE;
640 argp[idx+1].type = ARGT_STOP;
641 break;
642
643 case ARGT_BE:
644 if (!(p->cap & PR_CAP_BE))
645 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
646 argp[idx].data.prx = p;
647 argp[idx].type = ARGT_BE;
648 argp[idx+1].type = ARGT_STOP;
649 break;
650
651 case ARGT_TAB:
652 argp[idx].data.prx = p;
653 argp[idx].type = ARGT_TAB;
654 argp[idx+1].type = ARGT_STOP;
655 break;
656
657 default:
658 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
659 break;
660 }
661 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662 return 0;
663 }
664
665 /* Check for exceed the number of requiered argument. */
666 if ((mask & ARGT_MASK) == ARGT_STOP &&
667 argp[idx].type != ARGT_STOP) {
668 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
669 }
670
671 if ((mask & ARGT_MASK) == ARGT_STOP &&
672 argp[idx].type == ARGT_STOP) {
673 return 0;
674 }
675
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100676 /* Convert some argument types. */
677 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100678 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100679 if (argp[idx].type != ARGT_SINT)
680 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
681 argp[idx].type = ARGT_SINT;
682 break;
683
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100684 case ARGT_TIME:
685 if (argp[idx].type != ARGT_SINT)
686 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200687 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100688 break;
689
690 case ARGT_SIZE:
691 if (argp[idx].type != ARGT_SINT)
692 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200693 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100694 break;
695
696 case ARGT_FE:
697 if (argp[idx].type != ARGT_STR)
698 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200699 memcpy(trash.area, argp[idx].data.str.area,
700 argp[idx].data.str.data);
701 trash.area[argp[idx].data.str.data] = 0;
702 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100703 if (!argp[idx].data.prx)
704 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
705 argp[idx].type = ARGT_FE;
706 break;
707
708 case ARGT_BE:
709 if (argp[idx].type != ARGT_STR)
710 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200711 memcpy(trash.area, argp[idx].data.str.area,
712 argp[idx].data.str.data);
713 trash.area[argp[idx].data.str.data] = 0;
714 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100715 if (!argp[idx].data.prx)
716 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
717 argp[idx].type = ARGT_BE;
718 break;
719
720 case ARGT_TAB:
721 if (argp[idx].type != ARGT_STR)
722 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200723 memcpy(trash.area, argp[idx].data.str.area,
724 argp[idx].data.str.data);
725 trash.area[argp[idx].data.str.data] = 0;
Tim Duesterhuse351e762019-09-29 23:03:09 +0200726 argp[idx].data.t = stktable_find_by_name(trash.area);
727 if (!argp[idx].data.t)
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100728 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
729 argp[idx].type = ARGT_TAB;
730 break;
731
732 case ARGT_SRV:
733 if (argp[idx].type != ARGT_STR)
734 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200735 memcpy(trash.area, argp[idx].data.str.area,
736 argp[idx].data.str.data);
737 trash.area[argp[idx].data.str.data] = 0;
738 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100739 if (sname) {
740 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200741 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200742 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100743 if (!px)
744 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
745 }
746 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200747 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100748 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100749 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100750 argp[idx].data.srv = findserver(px, sname);
751 if (!argp[idx].data.srv)
752 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
753 argp[idx].type = ARGT_SRV;
754 break;
755
756 case ARGT_IPV4:
Christopher Faulete7f1fcf2020-08-07 09:07:26 +0200757 if (argp[idx].type != ARGT_STR)
758 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200759 memcpy(trash.area, argp[idx].data.str.area,
760 argp[idx].data.str.data);
761 trash.area[argp[idx].data.str.data] = 0;
762 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100763 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
764 argp[idx].type = ARGT_IPV4;
765 break;
766
767 case ARGT_MSK4:
Christopher Fauletff8de2c2020-08-07 09:11:22 +0200768 if (argp[idx].type == ARGT_SINT)
769 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
770 else if (argp[idx].type == ARGT_STR) {
771 memcpy(trash.area, argp[idx].data.str.area,
772 argp[idx].data.str.data);
773 trash.area[argp[idx].data.str.data] = 0;
774 if (!str2mask(trash.area, &argp[idx].data.ipv4))
775 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
776 }
777 else
778 WILL_LJMP(luaL_argerror(L, first + idx, "integer or string expected"));
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100779 argp[idx].type = ARGT_MSK4;
780 break;
781
782 case ARGT_IPV6:
Christopher Faulete7f1fcf2020-08-07 09:07:26 +0200783 if (argp[idx].type != ARGT_STR)
784 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200785 memcpy(trash.area, argp[idx].data.str.area,
786 argp[idx].data.str.data);
787 trash.area[argp[idx].data.str.data] = 0;
788 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100789 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
790 argp[idx].type = ARGT_IPV6;
791 break;
792
793 case ARGT_MSK6:
Christopher Fauletff8de2c2020-08-07 09:11:22 +0200794 if (argp[idx].type == ARGT_SINT)
795 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
796 else if (argp[idx].type == ARGT_STR) {
797 memcpy(trash.area, argp[idx].data.str.area,
798 argp[idx].data.str.data);
799 trash.area[argp[idx].data.str.data] = 0;
800 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
801 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
802 }
803 else
804 WILL_LJMP(luaL_argerror(L, first + idx, "integer or string expected"));
Tim Duesterhusb814da62018-01-25 16:24:50 +0100805 argp[idx].type = ARGT_MSK6;
806 break;
807
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100808 case ARGT_MAP:
809 case ARGT_REG:
810 case ARGT_USR:
811 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100812 break;
813 }
814
815 /* Check for type of argument. */
816 if ((mask & ARGT_MASK) != argp[idx].type) {
817 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
818 arg_type_names[(mask & ARGT_MASK)],
819 arg_type_names[argp[idx].type & ARGT_MASK]);
820 WILL_LJMP(luaL_argerror(L, first + idx, msg));
821 }
822
823 /* Next argument. */
824 mask >>= ARGT_BITS;
825 idx++;
826 }
827}
828
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100829/*
830 * The following functions are used to make correspondance between the the
831 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100832 *
833 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100834 * - hlua_sethlua : create the association between hlua context and lua_state.
835 */
836static inline struct hlua *hlua_gethlua(lua_State *L)
837{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100838 struct hlua **hlua = lua_getextraspace(L);
839 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100840}
841static inline void hlua_sethlua(struct hlua *hlua)
842{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100843 struct hlua **hlua_store = lua_getextraspace(hlua->T);
844 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100845}
846
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100847/* This function is used to send logs. It try to send on screen (stderr)
848 * and on the default syslog server.
849 */
850static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
851{
852 struct tm tm;
853 char *p;
854
855 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200856 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100857 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200858 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200859 /* Break the message if exceed the buffer size. */
860 *(p-4) = ' ';
861 *(p-3) = '.';
862 *(p-2) = '.';
863 *(p-1) = '.';
864 break;
865 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100866 if (isprint(*msg))
867 *p = *msg;
868 else
869 *p = '.';
870 }
871 *p = '\0';
872
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200873 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100874 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletb290edf2020-10-02 18:13:52 +0200875 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
876 return;
877
Willy Tarreaua678b432015-08-28 10:14:59 +0200878 get_localtime(date.tv_sec, &tm);
879 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100880 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200881 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100882 fflush(stderr);
883 }
884}
885
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100886/* This function just ensure that the yield will be always
887 * returned with a timeout and permit to set some flags
888 */
889__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100890 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100891{
892 struct hlua *hlua = hlua_gethlua(L);
893
894 /* Set the wake timeout. If timeout is required, we set
895 * the expiration time.
896 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200897 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100898
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100899 hlua->flags |= flags;
900
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100901 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +0200902 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100903}
904
Willy Tarreau87b09662015-04-03 00:22:06 +0200905/* This function initialises the Lua environment stored in the stream.
906 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100907 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200908 *
909 * This function is particular. it initialises a new Lua thread. If the
910 * initialisation fails (example: out of memory error), the lua function
911 * throws an error (longjmp).
912 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100913 * In some case (at least one), this function can be called from safe
914 * environement, so we must not initialise it. While the support of
915 * threads appear, the safe environment set a lock to ensure only one
916 * Lua execution at a time. If we initialize safe environment in another
917 * safe environmenet, we have a dead lock.
918 *
919 * set "already_safe" true if the context is initialized form safe
920 * Lua fonction.
921 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800922 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200923 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800924 * MUST NOT manipulate the created thread stack state, because it is not
925 * proctected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100926 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100927int hlua_ctx_init(struct hlua *lua, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100928{
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100929 if (!already_safe) {
930 if (!SET_SAFE_LJMP(gL.T)) {
931 lua->Tref = LUA_REFNIL;
932 return 0;
933 }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200934 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100935 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100936 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100937 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100938 lua->T = lua_newthread(gL.T);
939 if (!lua->T) {
940 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100941 if (!already_safe)
942 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100943 return 0;
944 }
945 hlua_sethlua(lua);
946 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
947 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100948 if (!already_safe)
949 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100950 return 1;
951}
952
Willy Tarreau87b09662015-04-03 00:22:06 +0200953/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100954 * is destroyed. The destroy also the memory context. The struct "lua"
955 * is not freed.
956 */
957void hlua_ctx_destroy(struct hlua *lua)
958{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100959 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100960 return;
961
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100962 if (!lua->T)
963 goto end;
964
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100965 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200966 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100967
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200968 if (!SET_SAFE_LJMP(lua->T))
969 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100970 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200971 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200972
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200973 if (!SET_SAFE_LJMP(gL.T))
974 return;
975 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
976 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200977 /* Forces a garbage collecting process. If the Lua program is finished
978 * without error, we run the GC on the thread pointer. Its freed all
979 * the unused memory.
980 * If the thread is finnish with an error or is currently yielded,
981 * it seems that the GC applied on the thread doesn't clean anything,
982 * so e run the GC on the main thread.
983 * NOTE: maybe this action locks all the Lua threads untiml the en of
984 * the garbage collection.
985 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200986 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200987 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200988 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200989 lua_gc(gL.T, LUA_GCCOLLECT, 0);
990 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200991 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200992
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200993 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100994
995end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100996 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100997}
998
999/* This function is used to restore the Lua context when a coroutine
1000 * fails. This function copy the common memory between old coroutine
1001 * and the new coroutine. The old coroutine is destroyed, and its
1002 * replaced by the new coroutine.
1003 * If the flag "keep_msg" is set, the last entry of the old is assumed
1004 * as string error message and it is copied in the new stack.
1005 */
1006static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1007{
1008 lua_State *T;
1009 int new_ref;
1010
1011 /* Renew the main LUA stack doesn't have sense. */
1012 if (lua == &gL)
1013 return 0;
1014
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001015 /* New Lua coroutine. */
1016 T = lua_newthread(gL.T);
1017 if (!T)
1018 return 0;
1019
1020 /* Copy last error message. */
1021 if (keep_msg)
1022 lua_xmove(lua->T, T, 1);
1023
1024 /* Copy data between the coroutines. */
1025 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1026 lua_xmove(lua->T, T, 1);
1027 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
1028
1029 /* Destroy old data. */
1030 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1031
1032 /* The thread is garbage collected by Lua. */
1033 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1034
1035 /* Fill the struct with the new coroutine values. */
1036 lua->Mref = new_ref;
1037 lua->T = T;
1038 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1039
1040 /* Set context. */
1041 hlua_sethlua(lua);
1042
1043 return 1;
1044}
1045
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001046void hlua_hook(lua_State *L, lua_Debug *ar)
1047{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001048 struct hlua *hlua = hlua_gethlua(L);
1049
1050 /* Lua cannot yield when its returning from a function,
1051 * so, we can fix the interrupt hook to 1 instruction,
1052 * expecting that the function is finnished.
1053 */
1054 if (lua_gethookmask(L) & LUA_MASKRET) {
1055 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1056 return;
1057 }
1058
1059 /* restore the interrupt condition. */
1060 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1061
1062 /* If we interrupt the Lua processing in yieldable state, we yield.
1063 * If the state is not yieldable, trying yield causes an error.
1064 */
1065 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001066 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001067
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001068 /* If we cannot yield, update the clock and check the timeout. */
1069 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001070 hlua->run_time += now_ms - hlua->start_time;
1071 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001072 lua_pushfstring(L, "execution timeout");
1073 WILL_LJMP(lua_error(L));
1074 }
1075
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001076 /* Update the start time. */
1077 hlua->start_time = now_ms;
1078
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001079 /* Try to interrupt the process at the end of the current
1080 * unyieldable function.
1081 */
1082 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001083}
1084
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001085/* This function start or resumes the Lua stack execution. If the flag
1086 * "yield_allowed" if no set and the LUA stack execution returns a yield
1087 * The function return an error.
1088 *
1089 * The function can returns 4 values:
1090 * - HLUA_E_OK : The execution is terminated without any errors.
1091 * - HLUA_E_AGAIN : The execution must continue at the next associated
1092 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001093 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001094 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001095 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001096 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001097 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001098 * LUA code.
1099 */
1100static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1101{
Christopher Faulet20699902020-07-28 10:33:25 +02001102#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1103 int nres;
1104#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001105 int ret;
1106 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001107 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001108
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001109 /* Initialise run time counter. */
1110 if (!HLUA_IS_RUNNING(lua))
1111 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001112
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001113 /* Lock the whole Lua execution. This lock must be before the
1114 * label "resume_execution".
1115 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001116 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001117
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001118resume_execution:
1119
1120 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1121 * instructions. it is used for preventing infinite loops.
1122 */
1123 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1124
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001125 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001126 HLUA_SET_RUN(lua);
1127 HLUA_CLR_CTRLYIELD(lua);
1128 HLUA_CLR_WAKERESWR(lua);
1129 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001130
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001131 /* Update the start time. */
1132 lua->start_time = now_ms;
1133
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001134 /* Call the function. */
Christopher Faulet20699902020-07-28 10:33:25 +02001135#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1136 ret = lua_resume(lua->T, gL.T, lua->nargs, &nres);
1137#else
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001138 ret = lua_resume(lua->T, gL.T, lua->nargs);
Christopher Faulet20699902020-07-28 10:33:25 +02001139#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001140 switch (ret) {
1141
1142 case LUA_OK:
1143 ret = HLUA_E_OK;
1144 break;
1145
1146 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001147 /* Check if the execution timeout is expired. It it is the case, we
1148 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001149 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001150 tv_update_date(0, 1);
1151 lua->run_time += now_ms - lua->start_time;
1152 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001153 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001154 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001155 break;
1156 }
1157 /* Process the forced yield. if the general yield is not allowed or
1158 * if no task were associated this the current Lua execution
1159 * coroutine, we resume the execution. Else we want to return in the
1160 * scheduler and we want to be waked up again, to continue the
1161 * current Lua execution. So we schedule our own task.
1162 */
1163 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001164 if (!yield_allowed || !lua->task)
1165 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001166 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001167 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001168 if (!yield_allowed) {
1169 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001170 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001171 break;
1172 }
1173 ret = HLUA_E_AGAIN;
1174 break;
1175
1176 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001177
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001178 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001179 * because the errors ares the only one mean to return immediately
1180 * from and lua execution.
1181 */
1182 if (lua->flags & HLUA_EXIT) {
1183 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001184 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001185 break;
1186 }
1187
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001188 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001189 if (!lua_checkstack(lua->T, 1)) {
1190 ret = HLUA_E_ERR;
1191 break;
1192 }
1193 msg = lua_tostring(lua->T, -1);
1194 lua_settop(lua->T, 0); /* Empty the stack. */
1195 lua_pop(lua->T, 1);
Christopher Faulet979865e2021-03-24 14:48:45 +01001196 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001197 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001198 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001199 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001200 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001201 ret = HLUA_E_ERRMSG;
1202 break;
1203
1204 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001205 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001206 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001207 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001208 break;
1209
1210 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001211 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001212 if (!lua_checkstack(lua->T, 1)) {
1213 ret = HLUA_E_ERR;
1214 break;
1215 }
1216 msg = lua_tostring(lua->T, -1);
1217 lua_settop(lua->T, 0); /* Empty the stack. */
1218 lua_pop(lua->T, 1);
1219 if (msg)
1220 lua_pushfstring(lua->T, "message handler error: %s", msg);
1221 else
1222 lua_pushfstring(lua->T, "message handler error");
1223 ret = HLUA_E_ERRMSG;
1224 break;
1225
1226 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001227 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001228 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001229 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001230 break;
1231 }
1232
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001233 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001234 if (lua->flags & HLUA_MUST_GC &&
1235 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001236 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1237
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001238 switch (ret) {
1239 case HLUA_E_AGAIN:
1240 break;
1241
1242 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001243 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001244 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001245 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001246 break;
1247
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001248 case HLUA_E_ETMOUT:
1249 case HLUA_E_NOMEM:
1250 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001251 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001252 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001253 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001254 hlua_ctx_renew(lua, 0);
1255 break;
1256
1257 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001258 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001259 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001260 break;
1261 }
1262
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001263 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001264 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001265
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001266 return ret;
1267}
1268
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001269/* This function exit the current code. */
1270__LJMP static int hlua_done(lua_State *L)
1271{
1272 struct hlua *hlua = hlua_gethlua(L);
1273
1274 hlua->flags |= HLUA_EXIT;
1275 WILL_LJMP(lua_error(L));
1276
1277 return 0;
1278}
1279
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001280/* This function is an LUA binding. It provides a function
1281 * for deleting ACL from a referenced ACL file.
1282 */
1283__LJMP static int hlua_del_acl(lua_State *L)
1284{
1285 const char *name;
1286 const char *key;
1287 struct pat_ref *ref;
1288
1289 MAY_LJMP(check_args(L, 2, "del_acl"));
1290
1291 name = MAY_LJMP(luaL_checkstring(L, 1));
1292 key = MAY_LJMP(luaL_checkstring(L, 2));
1293
1294 ref = pat_ref_lookup(name);
1295 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001296 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001297
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001298 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001299 pat_ref_delete(ref, key);
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001300 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001301 return 0;
1302}
1303
1304/* This function is an LUA binding. It provides a function
1305 * for deleting map entry from a referenced map file.
1306 */
1307static int hlua_del_map(lua_State *L)
1308{
1309 const char *name;
1310 const char *key;
1311 struct pat_ref *ref;
1312
1313 MAY_LJMP(check_args(L, 2, "del_map"));
1314
1315 name = MAY_LJMP(luaL_checkstring(L, 1));
1316 key = MAY_LJMP(luaL_checkstring(L, 2));
1317
1318 ref = pat_ref_lookup(name);
1319 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001320 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001321
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001322 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001323 pat_ref_delete(ref, key);
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001324 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001325 return 0;
1326}
1327
1328/* This function is an LUA binding. It provides a function
1329 * for adding ACL pattern from a referenced ACL file.
1330 */
1331static int hlua_add_acl(lua_State *L)
1332{
1333 const char *name;
1334 const char *key;
1335 struct pat_ref *ref;
1336
1337 MAY_LJMP(check_args(L, 2, "add_acl"));
1338
1339 name = MAY_LJMP(luaL_checkstring(L, 1));
1340 key = MAY_LJMP(luaL_checkstring(L, 2));
1341
1342 ref = pat_ref_lookup(name);
1343 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001344 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001345
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001346 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001347 if (pat_ref_find_elt(ref, key) == NULL)
1348 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001349 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001350 return 0;
1351}
1352
1353/* This function is an LUA binding. It provides a function
1354 * for setting map pattern and sample from a referenced map
1355 * file.
1356 */
1357static int hlua_set_map(lua_State *L)
1358{
1359 const char *name;
1360 const char *key;
1361 const char *value;
1362 struct pat_ref *ref;
1363
1364 MAY_LJMP(check_args(L, 3, "set_map"));
1365
1366 name = MAY_LJMP(luaL_checkstring(L, 1));
1367 key = MAY_LJMP(luaL_checkstring(L, 2));
1368 value = MAY_LJMP(luaL_checkstring(L, 3));
1369
1370 ref = pat_ref_lookup(name);
1371 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001372 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001373
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001374 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001375 if (pat_ref_find_elt(ref, key) != NULL)
1376 pat_ref_set(ref, key, value, NULL);
1377 else
1378 pat_ref_add(ref, key, value, NULL);
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001379 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001380 return 0;
1381}
1382
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001383/* A class is a lot of memory that contain data. This data can be a table,
1384 * an integer or user data. This data is associated with a metatable. This
1385 * metatable have an original version registred in the global context with
1386 * the name of the object (_G[<name>] = <metable> ).
1387 *
1388 * A metable is a table that modify the standard behavior of a standard
1389 * access to the associated data. The entries of this new metatable are
1390 * defined as is:
1391 *
1392 * http://lua-users.org/wiki/MetatableEvents
1393 *
1394 * __index
1395 *
1396 * we access an absent field in a table, the result is nil. This is
1397 * true, but it is not the whole truth. Actually, such access triggers
1398 * the interpreter to look for an __index metamethod: If there is no
1399 * such method, as usually happens, then the access results in nil;
1400 * otherwise, the metamethod will provide the result.
1401 *
1402 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1403 * the key does not appear in the table, but the metatable has an __index
1404 * property:
1405 *
1406 * - if the value is a function, the function is called, passing in the
1407 * table and the key; the return value of that function is returned as
1408 * the result.
1409 *
1410 * - if the value is another table, the value of the key in that table is
1411 * asked for and returned (and if it doesn't exist in that table, but that
1412 * table's metatable has an __index property, then it continues on up)
1413 *
1414 * - Use "rawget(myTable,key)" to skip this metamethod.
1415 *
1416 * http://www.lua.org/pil/13.4.1.html
1417 *
1418 * __newindex
1419 *
1420 * Like __index, but control property assignment.
1421 *
1422 * __mode - Control weak references. A string value with one or both
1423 * of the characters 'k' and 'v' which specifies that the the
1424 * keys and/or values in the table are weak references.
1425 *
1426 * __call - Treat a table like a function. When a table is followed by
1427 * parenthesis such as "myTable( 'foo' )" and the metatable has
1428 * a __call key pointing to a function, that function is invoked
1429 * (passing any specified arguments) and the return value is
1430 * returned.
1431 *
1432 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1433 * called, if the metatable for myTable has a __metatable
1434 * key, the value of that key is returned instead of the
1435 * actual metatable.
1436 *
1437 * __tostring - Control string representation. When the builtin
1438 * "tostring( myTable )" function is called, if the metatable
1439 * for myTable has a __tostring property set to a function,
1440 * that function is invoked (passing myTable to it) and the
1441 * return value is used as the string representation.
1442 *
1443 * __len - Control table length. When the table length is requested using
1444 * the length operator ( '#' ), if the metatable for myTable has
1445 * a __len key pointing to a function, that function is invoked
1446 * (passing myTable to it) and the return value used as the value
1447 * of "#myTable".
1448 *
1449 * __gc - Userdata finalizer code. When userdata is set to be garbage
1450 * collected, if the metatable has a __gc field pointing to a
1451 * function, that function is first invoked, passing the userdata
1452 * to it. The __gc metamethod is not called for tables.
1453 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1454 *
1455 * Special metamethods for redefining standard operators:
1456 * http://www.lua.org/pil/13.1.html
1457 *
1458 * __add "+"
1459 * __sub "-"
1460 * __mul "*"
1461 * __div "/"
1462 * __unm "!"
1463 * __pow "^"
1464 * __concat ".."
1465 *
1466 * Special methods for redfining standar relations
1467 * http://www.lua.org/pil/13.2.html
1468 *
1469 * __eq "=="
1470 * __lt "<"
1471 * __le "<="
1472 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001473
1474/*
1475 *
1476 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001477 * Class Map
1478 *
1479 *
1480 */
1481
1482/* Returns a struct hlua_map if the stack entry "ud" is
1483 * a class session, otherwise it throws an error.
1484 */
1485__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1486{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001487 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001488}
1489
1490/* This function is the map constructor. It don't need
1491 * the class Map object. It creates and return a new Map
1492 * object. It must be called only during "body" or "init"
1493 * context because it process some filesystem accesses.
1494 */
1495__LJMP static int hlua_map_new(struct lua_State *L)
1496{
1497 const char *fn;
1498 int match = PAT_MATCH_STR;
1499 struct sample_conv conv;
1500 const char *file = "";
1501 int line = 0;
1502 lua_Debug ar;
1503 char *err = NULL;
1504 struct arg args[2];
1505
1506 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1507 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1508
1509 fn = MAY_LJMP(luaL_checkstring(L, 1));
1510
1511 if (lua_gettop(L) >= 2) {
1512 match = MAY_LJMP(luaL_checkinteger(L, 2));
1513 if (match < 0 || match >= PAT_MATCH_NUM)
1514 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1515 }
1516
1517 /* Get Lua filename and line number. */
1518 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1519 lua_getinfo(L, "Sl", &ar); /* get info about it */
1520 if (ar.currentline > 0) { /* is there info? */
1521 file = ar.short_src;
1522 line = ar.currentline;
1523 }
1524 }
1525
1526 /* fill fake sample_conv struct. */
1527 conv.kw = ""; /* unused. */
1528 conv.process = NULL; /* unused. */
1529 conv.arg_mask = 0; /* unused. */
1530 conv.val_args = NULL; /* unused. */
1531 conv.out_type = SMP_T_STR;
1532 conv.private = (void *)(long)match;
1533 switch (match) {
1534 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1535 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1536 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1537 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1538 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1539 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1540 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001541 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001542 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1543 default:
1544 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1545 }
1546
1547 /* fill fake args. */
1548 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001549 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001550 args[1].type = ARGT_STOP;
1551
1552 /* load the map. */
1553 if (!sample_load_map(args, &conv, file, line, &err)) {
1554 /* error case: we cant use luaL_error because we must
1555 * free the err variable.
1556 */
1557 luaL_where(L, 1);
1558 lua_pushfstring(L, "'new': %s.", err);
1559 lua_concat(L, 2);
1560 free(err);
1561 WILL_LJMP(lua_error(L));
1562 }
1563
1564 /* create the lua object. */
1565 lua_newtable(L);
1566 lua_pushlightuserdata(L, args[0].data.map);
1567 lua_rawseti(L, -2, 0);
1568
1569 /* Pop a class Map metatable and affect it to the userdata. */
1570 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1571 lua_setmetatable(L, -2);
1572
1573
1574 return 1;
1575}
1576
1577__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1578{
1579 struct map_descriptor *desc;
1580 struct pattern *pat;
1581 struct sample smp;
1582
1583 MAY_LJMP(check_args(L, 2, "lookup"));
1584 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001585 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001586 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001587 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001588 }
1589 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001590 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001591 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001592 smp.data.u.str.area = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.data));
Thierry Fournier8e553842020-11-10 20:38:20 +01001593 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001594 }
1595
1596 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001597 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001598 if (str)
1599 lua_pushstring(L, "");
1600 else
1601 lua_pushnil(L);
1602 return 1;
1603 }
1604
1605 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001606 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001607 return 1;
1608}
1609
1610__LJMP static int hlua_map_lookup(struct lua_State *L)
1611{
1612 return _hlua_map_lookup(L, 0);
1613}
1614
1615__LJMP static int hlua_map_slookup(struct lua_State *L)
1616{
1617 return _hlua_map_lookup(L, 1);
1618}
1619
1620/*
1621 *
1622 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001623 * Class Socket
1624 *
1625 *
1626 */
1627
1628__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1629{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001630 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001631}
1632
1633/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001634 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001635 * received.
1636 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001637static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001638{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001639 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001640 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001641
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001642 if (appctx->ctx.hlua_cosocket.die) {
1643 si_shutw(si);
1644 si_shutr(si);
1645 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001646 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1647 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001648 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1649 }
1650
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001651 /* If the connection object is not available, close all the
1652 * streams and wakeup everything waiting for.
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001653 */
1654 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001655 si_shutw(si);
1656 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001657 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001658 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1659 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001660 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661 }
1662
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001663 /* If we cant write, wakeup the pending write signals. */
1664 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001665 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001666
1667 /* If we cant read, wakeup the pending read signals. */
1668 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001669 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001670
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001671 /* if the connection is not estabkished, inform the stream that we want
1672 * to be notified whenever the connection completes.
1673 */
1674 if (!(c->flags & CO_FL_CONNECTED)) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001675 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001676 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001677 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001678 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001679 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001680
1681 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001682 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001683
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001684 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001685 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001686 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001687
1688 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001689 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001690 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001691
1692 /* Some data were injected in the buffer, notify the stream
1693 * interface.
1694 */
1695 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001696 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001697
1698 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001699 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001700 */
1701 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001702 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703}
1704
Willy Tarreau87b09662015-04-03 00:22:06 +02001705/* This function is called when the "struct stream" is destroyed.
1706 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001707 * Wake all the pending signals.
1708 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001709static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001710{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001711 struct xref *peer;
1712
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001714 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1715 if (peer)
1716 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001717
1718 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001719 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1720 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001721}
1722
1723/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001724 * uses this object. If the stream does not exists, just quit.
1725 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001726 * pending signal can rest in the read and write lists. destroy
1727 * it.
1728 */
1729__LJMP static int hlua_socket_gc(lua_State *L)
1730{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001731 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001732 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001733 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001734
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001735 MAY_LJMP(check_args(L, 1, "__gc"));
1736
1737 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001738 peer = xref_get_peer_and_lock(&socket->xref);
1739 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001740 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001741 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001742
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001743 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001744 appctx->ctx.hlua_cosocket.die = 1;
1745 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001746
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001747 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001748 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001749 return 0;
1750}
1751
1752/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001753 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001754 */
sada05ed3302018-05-11 11:48:18 -07001755__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001756{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001757 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001758 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001759 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001760
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001761 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001762
1763 /* Check if we run on the same thread than the xreator thread.
1764 * We cannot access to the socket if the thread is different.
1765 */
1766 if (socket->tid != tid)
1767 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1768
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001769 peer = xref_get_peer_and_lock(&socket->xref);
1770 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001771 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001772 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001773
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001774 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001775 appctx->ctx.hlua_cosocket.die = 1;
1776 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001777
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001778 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001779 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001780 return 0;
1781}
1782
sada05ed3302018-05-11 11:48:18 -07001783/* The close function calls close_helper.
1784 */
1785__LJMP static int hlua_socket_close(lua_State *L)
1786{
1787 MAY_LJMP(check_args(L, 1, "close"));
1788 return hlua_socket_close_helper(L);
1789}
1790
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001791/* This Lua function assumes that the stack contain three parameters.
1792 * 1 - USERDATA containing a struct socket
1793 * 2 - INTEGER with values of the macro defined below
1794 * If the integer is -1, we must read at most one line.
1795 * If the integer is -2, we ust read all the data until the
1796 * end of the stream.
1797 * If the integer is positive value, we must read a number of
1798 * bytes corresponding to this value.
1799 */
1800#define HLSR_READ_LINE (-1)
1801#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001802__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001803{
1804 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1805 int wanted = lua_tointeger(L, 2);
1806 struct hlua *hlua = hlua_gethlua(L);
1807 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001808 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001809 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001810 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001811 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001812 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001813 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001814 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001815 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001816 struct stream_interface *si;
1817 struct stream *s;
1818 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001819 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001820
1821 /* Check if this lua stack is schedulable. */
1822 if (!hlua || !hlua->task)
1823 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1824 "'frontend', 'backend' or 'task'"));
1825
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001826 /* Check if we run on the same thread than the xreator thread.
1827 * We cannot access to the socket if the thread is different.
1828 */
1829 if (socket->tid != tid)
1830 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1831
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001832 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001833 peer = xref_get_peer_and_lock(&socket->xref);
1834 if (!peer)
1835 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001836 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1837 si = appctx->owner;
1838 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001839
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001840 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001841 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001842 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001843 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001844 if (nblk < 0) /* Connection close. */
1845 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001846 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001847 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001848
1849 /* remove final \r\n. */
1850 if (nblk == 1) {
1851 if (blk1[len1-1] == '\n') {
1852 len1--;
1853 skip_at_end++;
1854 if (blk1[len1-1] == '\r') {
1855 len1--;
1856 skip_at_end++;
1857 }
1858 }
1859 }
1860 else {
1861 if (blk2[len2-1] == '\n') {
1862 len2--;
1863 skip_at_end++;
1864 if (blk2[len2-1] == '\r') {
1865 len2--;
1866 skip_at_end++;
1867 }
1868 }
1869 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001870 }
1871
1872 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001873 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001874 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001875 if (nblk < 0) /* Connection close. */
1876 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001877 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001878 goto connection_empty;
1879 }
1880
1881 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001882 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001883 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001884 if (nblk < 0) /* Connection close. */
1885 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001886 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001887 goto connection_empty;
1888
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001889 missing_bytes = wanted - socket->b.n;
1890 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001891 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001892 len1 = missing_bytes;
1893 } if (nblk == 2 && len1 + len2 > missing_bytes)
1894 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895 }
1896
1897 len = len1;
1898
1899 luaL_addlstring(&socket->b, blk1, len1);
1900 if (nblk == 2) {
1901 len += len2;
1902 luaL_addlstring(&socket->b, blk2, len2);
1903 }
1904
1905 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001906 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001907
1908 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001909 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001910
1911 /* If the pattern reclaim to read all the data
1912 * in the connection, got out.
1913 */
1914 if (wanted == HLSR_READ_ALL)
1915 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001916 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001917 goto connection_empty;
1918
1919 /* Return result. */
1920 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001921 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001922 return 1;
1923
1924connection_closed:
1925
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001926 xref_unlock(&socket->xref, peer);
1927
1928no_peer:
1929
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001930 /* If the buffer containds data. */
1931 if (socket->b.n > 0) {
1932 luaL_pushresult(&socket->b);
1933 return 1;
1934 }
1935 lua_pushnil(L);
1936 lua_pushstring(L, "connection closed.");
1937 return 2;
1938
1939connection_empty:
1940
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001941 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1942 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001943 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001944 }
1945 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001946 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947 return 0;
1948}
1949
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001950/* This Lua function gets two parameters. The first one can be string
1951 * or a number. If the string is "*l", the user requires one line. If
1952 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001953 * If the value is a number, the user require a number of bytes equal
1954 * to the value. The default value is "*l" (a line).
1955 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001956 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957 * integer takes this values:
1958 * -1 : read a line
1959 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001960 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001961 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001962 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001963 * concatenated with the read data.
1964 */
1965__LJMP static int hlua_socket_receive(struct lua_State *L)
1966{
1967 int wanted = HLSR_READ_LINE;
1968 const char *pattern;
1969 int type;
1970 char *error;
1971 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001972 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001973
1974 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1975 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1976
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001977 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001978
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001979 /* Check if we run on the same thread than the xreator thread.
1980 * We cannot access to the socket if the thread is different.
1981 */
1982 if (socket->tid != tid)
1983 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1984
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985 /* check for pattern. */
1986 if (lua_gettop(L) >= 2) {
1987 type = lua_type(L, 2);
1988 if (type == LUA_TSTRING) {
1989 pattern = lua_tostring(L, 2);
1990 if (strcmp(pattern, "*a") == 0)
1991 wanted = HLSR_READ_ALL;
1992 else if (strcmp(pattern, "*l") == 0)
1993 wanted = HLSR_READ_LINE;
1994 else {
1995 wanted = strtoll(pattern, &error, 10);
1996 if (*error != '\0')
1997 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1998 }
1999 }
2000 else if (type == LUA_TNUMBER) {
2001 wanted = lua_tointeger(L, 2);
2002 if (wanted < 0)
2003 WILL_LJMP(luaL_error(L, "Unsupported size."));
2004 }
2005 }
2006
2007 /* Set pattern. */
2008 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002009
2010 /* Check if we would replace the top by itself. */
2011 if (lua_gettop(L) != 2)
2012 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002013
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002014 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015 luaL_buffinit(L, &socket->b);
2016
2017 /* Check prefix. */
2018 if (lua_gettop(L) >= 3) {
2019 if (lua_type(L, 3) != LUA_TSTRING)
2020 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2021 pattern = lua_tolstring(L, 3, &len);
2022 luaL_addlstring(&socket->b, pattern, len);
2023 }
2024
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002025 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002026}
2027
2028/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002029 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002030 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002031static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002032{
2033 struct hlua_socket *socket;
2034 struct hlua *hlua = hlua_gethlua(L);
2035 struct appctx *appctx;
2036 size_t buf_len;
2037 const char *buf;
2038 int len;
2039 int send_len;
2040 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002041 struct xref *peer;
2042 struct stream_interface *si;
2043 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002044
2045 /* Check if this lua stack is schedulable. */
2046 if (!hlua || !hlua->task)
2047 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2048 "'frontend', 'backend' or 'task'"));
2049
2050 /* Get object */
2051 socket = MAY_LJMP(hlua_checksocket(L, 1));
2052 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002053 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002054
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002055 /* Check if we run on the same thread than the xreator thread.
2056 * We cannot access to the socket if the thread is different.
2057 */
2058 if (socket->tid != tid)
2059 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2060
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002061 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002062 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002063 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002064 lua_pushinteger(L, -1);
2065 return 1;
2066 }
2067 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2068 si = appctx->owner;
2069 s = si_strm(si);
2070
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002072 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002073 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074 lua_pushinteger(L, -1);
2075 return 1;
2076 }
2077
2078 /* Update the input buffer data. */
2079 buf += sent;
2080 send_len = buf_len - sent;
2081
2082 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002083 if (sent >= buf_len) {
2084 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002086 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002088 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002089 * the request buffer if its not required.
2090 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002091 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002092 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002093 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002094 }
2095
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002096 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002097 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002098 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002099 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002100 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002101
2102 /* send data */
2103 if (len < send_len)
2104 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002105 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002106
2107 /* "Not enough space" (-1), "Buffer too little to contain
2108 * the data" (-2) are not expected because the available length
2109 * is tested.
2110 * Other unknown error are also not expected.
2111 */
2112 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002113 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002114 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002115
sada05ed3302018-05-11 11:48:18 -07002116 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002118 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002119 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120 return 1;
2121 }
2122
2123 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002124 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002125
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002126 s->req.rex = TICK_ETERNITY;
2127 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002128
2129 /* Update length sent. */
2130 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002131 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002132
2133 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002134 if (sent + len >= buf_len) {
2135 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002136 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002137 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002138
2139hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002140 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2141 xref_unlock(&socket->xref, peer);
2142 WILL_LJMP(luaL_error(L, "out of memory"));
2143 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002144 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002145 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146 return 0;
2147}
2148
2149/* This function initiate the send of data. It just check the input
2150 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002151 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152 * "hlua_socket_write_yield" that can yield.
2153 *
2154 * The Lua function gets between 3 and 4 parameters. The first one is
2155 * the associated object. The second is a string buffer. The third is
2156 * a facultative integer that represents where is the buffer position
2157 * of the start of the data that can send. The first byte is the
2158 * position "1". The default value is "1". The fourth argument is a
2159 * facultative integer that represents where is the buffer position
2160 * of the end of the data that can send. The default is the last byte.
2161 */
2162static int hlua_socket_send(struct lua_State *L)
2163{
2164 int i;
2165 int j;
2166 const char *buf;
2167 size_t buf_len;
2168
2169 /* Check number of arguments. */
2170 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2171 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2172
2173 /* Get the string. */
2174 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2175
2176 /* Get and check j. */
2177 if (lua_gettop(L) == 4) {
2178 j = MAY_LJMP(luaL_checkinteger(L, 4));
2179 if (j < 0)
2180 j = buf_len + j + 1;
2181 if (j > buf_len)
2182 j = buf_len + 1;
2183 lua_pop(L, 1);
2184 }
2185 else
2186 j = buf_len;
2187
2188 /* Get and check i. */
2189 if (lua_gettop(L) == 3) {
2190 i = MAY_LJMP(luaL_checkinteger(L, 3));
2191 if (i < 0)
2192 i = buf_len + i + 1;
2193 if (i > buf_len)
2194 i = buf_len + 1;
2195 lua_pop(L, 1);
2196 } else
2197 i = 1;
2198
2199 /* Check bth i and j. */
2200 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002201 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202 return 1;
2203 }
2204 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002205 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002206 return 1;
2207 }
2208 if (i == 0)
2209 i = 1;
2210 if (j == 0)
2211 j = 1;
2212
2213 /* Pop the string. */
2214 lua_pop(L, 1);
2215
2216 /* Update the buffer length. */
2217 buf += i - 1;
2218 buf_len = j - i + 1;
2219 lua_pushlstring(L, buf, buf_len);
2220
2221 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002222 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002223
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002224 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002225}
2226
Willy Tarreau22b0a682015-06-17 19:43:49 +02002227#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2229{
2230 static char buffer[SOCKET_INFO_MAX_LEN];
2231 int ret;
2232 int len;
2233 char *p;
2234
2235 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2236 if (ret <= 0) {
2237 lua_pushnil(L);
2238 return 1;
2239 }
2240
2241 if (ret == AF_UNIX) {
2242 lua_pushstring(L, buffer+1);
2243 return 1;
2244 }
2245 else if (ret == AF_INET6) {
2246 buffer[0] = '[';
2247 len = strlen(buffer);
2248 buffer[len] = ']';
2249 len++;
2250 buffer[len] = ':';
2251 len++;
2252 p = buffer;
2253 }
2254 else if (ret == AF_INET) {
2255 p = buffer + 1;
2256 len = strlen(p);
2257 p[len] = ':';
2258 len++;
2259 }
2260 else {
2261 lua_pushnil(L);
2262 return 1;
2263 }
2264
2265 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2266 lua_pushnil(L);
2267 return 1;
2268 }
2269
2270 lua_pushstring(L, p);
2271 return 1;
2272}
2273
2274/* Returns information about the peer of the connection. */
2275__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2276{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002277 struct hlua_socket *socket;
2278 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002279 struct xref *peer;
2280 struct appctx *appctx;
2281 struct stream_interface *si;
2282 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002283 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002284
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002285 MAY_LJMP(check_args(L, 1, "getpeername"));
2286
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002287 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002289 /* Check if we run on the same thread than the xreator thread.
2290 * We cannot access to the socket if the thread is different.
2291 */
2292 if (socket->tid != tid)
2293 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2294
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002295 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002296 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002297 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298 lua_pushnil(L);
2299 return 1;
2300 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002301 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2302 si = appctx->owner;
2303 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002305 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002307 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002308 lua_pushnil(L);
2309 return 1;
2310 }
2311
Willy Tarreaua71f6422016-11-16 17:00:14 +01002312 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002314 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002315 lua_pushnil(L);
2316 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317 }
2318
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002319 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2320 xref_unlock(&socket->xref, peer);
2321 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322}
2323
2324/* Returns information about my connection side. */
2325static int hlua_socket_getsockname(struct lua_State *L)
2326{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002327 struct hlua_socket *socket;
2328 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002329 struct appctx *appctx;
2330 struct xref *peer;
2331 struct stream_interface *si;
2332 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002333 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002334
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002335 MAY_LJMP(check_args(L, 1, "getsockname"));
2336
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002337 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002338
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002339 /* Check if we run on the same thread than the xreator thread.
2340 * We cannot access to the socket if the thread is different.
2341 */
2342 if (socket->tid != tid)
2343 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2344
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002345 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002346 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002347 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348 lua_pushnil(L);
2349 return 1;
2350 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002351 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2352 si = appctx->owner;
2353 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002354
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002355 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002357 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358 lua_pushnil(L);
2359 return 1;
2360 }
2361
Willy Tarreaua71f6422016-11-16 17:00:14 +01002362 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002363 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002364 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002365 lua_pushnil(L);
2366 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002367 }
2368
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002369 ret = hlua_socket_info(L, &conn->addr.from);
2370 xref_unlock(&socket->xref, peer);
2371 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002372}
2373
2374/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002375static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376 .obj_type = OBJ_TYPE_APPLET,
2377 .name = "<LUA_TCP>",
2378 .fct = hlua_socket_handler,
2379 .release = hlua_socket_release,
2380};
2381
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002382__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383{
2384 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2385 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002386 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002387 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002388 struct stream_interface *si;
2389 struct stream *s;
2390
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002391 /* Check if we run on the same thread than the xreator thread.
2392 * We cannot access to the socket if the thread is different.
2393 */
2394 if (socket->tid != tid)
2395 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2396
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002397 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002398 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002399 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002400 lua_pushnil(L);
2401 lua_pushstring(L, "Can't connect");
2402 return 2;
2403 }
2404 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2405 si = appctx->owner;
2406 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002408 /* Check if we run on the same thread than the xreator thread.
2409 * We cannot access to the socket if the thread is different.
2410 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002411 if (socket->tid != tid) {
2412 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002413 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002414 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002415
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002416 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002417 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002418 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002419 lua_pushnil(L);
2420 lua_pushstring(L, "Can't connect");
2421 return 2;
2422 }
2423
Willy Tarreaue09101e2018-10-16 17:37:12 +02002424 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002425
2426 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002427 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002428 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002429 lua_pushinteger(L, 1);
2430 return 1;
2431 }
2432
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002433 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2434 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002435 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002436 }
2437 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002438 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439 return 0;
2440}
2441
2442/* This function fail or initite the connection. */
2443__LJMP static int hlua_socket_connect(struct lua_State *L)
2444{
2445 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002446 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447 const char *ip;
2448 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002449 struct hlua *hlua;
2450 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002451 int low, high;
2452 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002453 struct xref *peer;
2454 struct stream_interface *si;
2455 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002456
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002457 if (lua_gettop(L) < 2)
2458 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002459
2460 /* Get args. */
2461 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002462
2463 /* Check if we run on the same thread than the xreator thread.
2464 * We cannot access to the socket if the thread is different.
2465 */
2466 if (socket->tid != tid)
2467 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2468
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002469 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002470 if (lua_gettop(L) >= 3) {
2471 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002472 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002473
Tim Duesterhus6edab862018-01-06 19:04:45 +01002474 /* Force the ip to end with a colon, to support IPv6 addresses
2475 * that are not enclosed within square brackets.
2476 */
2477 if (port > 0) {
2478 luaL_buffinit(L, &b);
2479 luaL_addstring(&b, ip);
2480 luaL_addchar(&b, ':');
2481 luaL_pushresult(&b);
2482 ip = lua_tolstring(L, lua_gettop(L), NULL);
2483 }
2484 }
2485
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002486 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002487 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002488 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002489 lua_pushnil(L);
2490 return 1;
2491 }
2492 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2493 si = appctx->owner;
2494 s = si_strm(si);
2495
2496 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002497 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002498 if (!conn) {
2499 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002500 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002501 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502
Willy Tarreau3adac082015-09-26 17:51:09 +02002503 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002504 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002505
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002507 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002508 if (!addr) {
2509 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002510 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002511 }
2512 if (low != high) {
2513 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002514 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002515 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002516 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002517
2518 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002519 if (low == 0) {
2520 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002521 if (port == -1) {
2522 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002523 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002524 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002525 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2526 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002527 if (port == -1) {
2528 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002529 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002530 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002531 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2532 }
2533 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002534
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002535 hlua = hlua_gethlua(L);
Willy Tarreaue09101e2018-10-16 17:37:12 +02002536 appctx = __objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002537
2538 /* inform the stream that we want to be notified whenever the
2539 * connection completes.
2540 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002541 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002542 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002543 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002544
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002545 hlua->flags |= HLUA_MUST_GC;
2546
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002547 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2548 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002549 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002550 }
2551 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002552
2553 task_wakeup(s->task, TASK_WOKEN_INIT);
2554 /* Return yield waiting for connection. */
2555
Willy Tarreau9635e032018-10-16 17:52:55 +02002556 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002557
2558 return 0;
2559}
2560
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002561#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002562__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2563{
2564 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002565 struct xref *peer;
2566 struct appctx *appctx;
2567 struct stream_interface *si;
2568 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002569
2570 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2571 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002572
2573 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002574 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002575 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002576 lua_pushnil(L);
2577 return 1;
2578 }
2579 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2580 si = appctx->owner;
2581 s = si_strm(si);
2582
2583 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002584 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585 return MAY_LJMP(hlua_socket_connect(L));
2586}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002587#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002588
2589__LJMP static int hlua_socket_setoption(struct lua_State *L)
2590{
2591 return 0;
2592}
2593
2594__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2595{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002596 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002597 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002598 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002599 struct xref *peer;
2600 struct appctx *appctx;
2601 struct stream_interface *si;
2602 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002603
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002604 MAY_LJMP(check_args(L, 2, "settimeout"));
2605
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002606 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002607
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002608 /* convert the timeout to millis */
2609 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002610
Thierry Fournier17a921b2018-03-08 09:59:02 +01002611 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002612 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002613 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2614
Mark Lakes56cc1252018-03-27 09:48:06 +02002615 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002616 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002617
2618 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002619 if (tmout == 0)
2620 tmout++; /* very small timeouts are adjusted to a minium of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002621
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002622 /* Check if we run on the same thread than the xreator thread.
2623 * We cannot access to the socket if the thread is different.
2624 */
2625 if (socket->tid != tid)
2626 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2627
Mark Lakes56cc1252018-03-27 09:48:06 +02002628 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002629 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002630 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002631 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2632 WILL_LJMP(lua_error(L));
2633 return 0;
2634 }
2635 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2636 si = appctx->owner;
2637 s = si_strm(si);
2638
Cyril Bonté7bb63452018-08-17 23:51:02 +02002639 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002640 s->req.rto = tmout;
2641 s->req.wto = tmout;
2642 s->res.rto = tmout;
2643 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002644 s->req.rex = tick_add_ifset(now_ms, tmout);
2645 s->req.wex = tick_add_ifset(now_ms, tmout);
2646 s->res.rex = tick_add_ifset(now_ms, tmout);
2647 s->res.wex = tick_add_ifset(now_ms, tmout);
2648
2649 s->task->expire = tick_add_ifset(now_ms, tmout);
2650 task_queue(s->task);
2651
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002652 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002653
Thierry Fourniere9636f12018-03-08 09:54:32 +01002654 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002655 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002656}
2657
2658__LJMP static int hlua_socket_new(lua_State *L)
2659{
2660 struct hlua_socket *socket;
2661 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002662 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002663 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002664
2665 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002666 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002667 hlua_pusherror(L, "socket: full stack");
2668 goto out_fail_conf;
2669 }
2670
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002671 /* Create the object: obj[0] = userdata. */
2672 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002673 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002674 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002675 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002676 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002677
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002678 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002679 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002680 hlua_pusherror(L, "socket: uninitialized pools.");
2681 goto out_fail_conf;
2682 }
2683
Willy Tarreau87b09662015-04-03 00:22:06 +02002684 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002685 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2686 lua_setmetatable(L, -2);
2687
Willy Tarreaud420a972015-04-06 00:39:18 +02002688 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002689 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002690 if (!appctx) {
2691 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002692 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002693 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002694
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002695 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002696 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002697 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2698 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002699
Willy Tarreaud420a972015-04-06 00:39:18 +02002700 /* Now create a session, task and stream for this applet */
2701 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2702 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002703 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002704 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002705 }
2706
Willy Tarreau87787ac2017-08-28 16:22:54 +02002707 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002708 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002709 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002710 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002711 }
2712
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002713 /* Initialise cross reference between stream and Lua socket object. */
2714 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002715
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002716 /* Configure "right" stream interface. this "si" is used to connect
2717 * and retrieve data from the server. The connection is initialized
2718 * with the "struct server".
2719 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002720 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002721
2722 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002723 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2724 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002725
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002726 return 1;
2727
Willy Tarreaud420a972015-04-06 00:39:18 +02002728 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002729 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002730 out_fail_sess:
2731 appctx_free(appctx);
2732 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002733 WILL_LJMP(lua_error(L));
2734 return 0;
2735}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002736
2737/*
2738 *
2739 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740 * Class Channel
2741 *
2742 *
2743 */
2744
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002745/* This function is called before the Lua execution. It stores
2746 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002747 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002748static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002749{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002750 c->mode = stream->be->mode;
2751 switch (c->mode) {
2752 case PR_MODE_HTTP:
2753 c->data.http.dir = opt & SMP_OPT_DIR;
2754 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2755 c->data.http.state = stream->txn->req.msg_state;
2756 else
2757 c->data.http.state = stream->txn->rsp.msg_state;
2758 break;
2759 default:
2760 break;
2761 }
2762}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002763
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002764/* This function is called after the Lua execution. it
2765 * returns true if the parser state is consistent, otherwise,
2766 * it return false.
2767 *
2768 * In HTTP mode, the parser state must be in the same state
2769 * or greater when we exit the function. Even if we do a
2770 * control yield. This prevent to break the HTTP message
2771 * from the Lua code.
2772 */
2773static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2774{
2775 if (c->mode != stream->be->mode)
2776 return 0;
2777
2778 switch (c->mode) {
2779 case PR_MODE_HTTP:
2780 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002781 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002782 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2783 return stream->txn->req.msg_state >= c->data.http.state;
2784 else
2785 return stream->txn->rsp.msg_state >= c->data.http.state;
2786 default:
2787 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002788 }
2789 return 1;
2790}
2791
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002792/* Returns the struct hlua_channel join to the class channel in the
2793 * stack entry "ud" or throws an argument error.
2794 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002795__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002796{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002797 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002798}
2799
Willy Tarreau47860ed2015-03-10 14:07:50 +01002800/* Pushes the channel onto the top of the stack. If the stask does not have a
2801 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002802 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002803static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002804{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002805 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002806 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002807 return 0;
2808
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002809 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002810 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002811 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002812
2813 /* Pop a class sesison metatable and affect it to the userdata. */
2814 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2815 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002816 return 1;
2817}
2818
2819/* Duplicate all the data present in the input channel and put it
2820 * in a string LUA variables. Returns -1 and push a nil value in
2821 * the stack if the channel is closed and all the data are consumed,
2822 * returns 0 if no data are available, otherwise it returns the length
2823 * of the builded string.
2824 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002825static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826{
2827 char *blk1;
2828 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002829 size_t len1;
2830 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002831 int ret;
2832 luaL_Buffer b;
2833
Willy Tarreau06d80a92017-10-19 14:32:15 +02002834 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002835 if (unlikely(ret == 0))
2836 return 0;
2837
2838 if (unlikely(ret < 0)) {
2839 lua_pushnil(L);
2840 return -1;
2841 }
2842
2843 luaL_buffinit(L, &b);
2844 luaL_addlstring(&b, blk1, len1);
2845 if (unlikely(ret == 2))
2846 luaL_addlstring(&b, blk2, len2);
2847 luaL_pushresult(&b);
2848
2849 if (unlikely(ret == 2))
2850 return len1 + len2;
2851 return len1;
2852}
2853
2854/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2855 * a yield. This function keep the data in the buffer.
2856 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002857__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002858{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002859 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002860
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002861 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2862
Thierry Fournier414ecb02020-08-15 14:35:51 +02002863 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
2864 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002865 WILL_LJMP(lua_error(L));
Thierry Fournier414ecb02020-08-15 14:35:51 +02002866 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002867
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002868 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002869 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002870 return 1;
2871}
2872
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002873/* Check arguments for the function "hlua_channel_dup_yield". */
2874__LJMP static int hlua_channel_dup(lua_State *L)
2875{
2876 MAY_LJMP(check_args(L, 1, "dup"));
2877 MAY_LJMP(hlua_checkchannel(L, 1));
2878 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2879}
2880
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002881/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2882 * a yield. This function consumes the data in the buffer. It returns
2883 * a string containing the data or a nil pointer if no data are available
2884 * and the channel is closed.
2885 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002886__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002887{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002888 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002889 int ret;
2890
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002891 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002892
Thierry Fournier414ecb02020-08-15 14:35:51 +02002893 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
2894 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002895 WILL_LJMP(lua_error(L));
Thierry Fournier414ecb02020-08-15 14:35:51 +02002896 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002897
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002898 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002899 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002900 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002901
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002902 if (unlikely(ret == -1))
2903 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002904
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002905 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002906 return 1;
2907}
2908
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002909/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002910__LJMP static int hlua_channel_get(lua_State *L)
2911{
2912 MAY_LJMP(check_args(L, 1, "get"));
2913 MAY_LJMP(hlua_checkchannel(L, 1));
2914 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2915}
2916
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002917/* This functions consumes and returns one line. If the channel is closed,
2918 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002919 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002920 * value.
2921 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002922__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002923{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002924 char *blk1;
2925 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002926 size_t len1;
2927 size_t len2;
2928 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002929 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002930 int ret;
2931 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002932
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002933 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2934
Thierry Fournier414ecb02020-08-15 14:35:51 +02002935 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
2936 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002937 WILL_LJMP(lua_error(L));
Thierry Fournier414ecb02020-08-15 14:35:51 +02002938 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002939
Willy Tarreau06d80a92017-10-19 14:32:15 +02002940 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002941 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002942 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002943
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002944 if (ret == -1) {
2945 lua_pushnil(L);
2946 return 1;
2947 }
2948
2949 luaL_buffinit(L, &b);
2950 luaL_addlstring(&b, blk1, len1);
2951 len = len1;
2952 if (unlikely(ret == 2)) {
2953 luaL_addlstring(&b, blk2, len2);
2954 len += len2;
2955 }
2956 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002957 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002958 return 1;
2959}
2960
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002961/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002962__LJMP static int hlua_channel_getline(lua_State *L)
2963{
2964 MAY_LJMP(check_args(L, 1, "getline"));
2965 MAY_LJMP(hlua_checkchannel(L, 1));
2966 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2967}
2968
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002969/* This function takes a string as input, and append it at the
2970 * input side of channel. If the data is too big, but a space
2971 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002972 * yields. If the data is bigger than the buffer, or if the
2973 * channel is closed, it returns -1. Otherwise, it returns the
2974 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002975 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002976__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002977{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002978 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002979 size_t len;
2980 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2981 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2982 int ret;
2983 int max;
2984
Thierry Fournier414ecb02020-08-15 14:35:51 +02002985 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
2986 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002987 WILL_LJMP(lua_error(L));
Thierry Fournier414ecb02020-08-15 14:35:51 +02002988 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002989
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002990 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002991 * the request buffer if its not required.
2992 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002993 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002994 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002995 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002996 }
2997
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002998 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002999 if (max > len - l)
3000 max = len - l;
3001
Willy Tarreau06d80a92017-10-19 14:32:15 +02003002 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003003 if (ret == -2 || ret == -3) {
3004 lua_pushinteger(L, -1);
3005 return 1;
3006 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01003007 if (ret == -1) {
3008 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02003009 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01003010 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003011 l += ret;
3012 lua_pop(L, 1);
3013 lua_pushinteger(L, l);
3014
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003015 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003016 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003017 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003018 * in this case, we cannot add more data, so we cannot yield,
3019 * we return the amount of copyied data.
3020 */
3021 return 1;
3022 }
3023 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02003024 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003025 return 1;
3026}
3027
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003028/* Just a wrapper of "hlua_channel_append_yield". It returns the length
3029 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003030 * buffer size is too little for the data.
3031 */
3032__LJMP static int hlua_channel_append(lua_State *L)
3033{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003034 size_t len;
3035
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003036 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003037 MAY_LJMP(hlua_checkchannel(L, 1));
3038 MAY_LJMP(luaL_checklstring(L, 2, &len));
3039 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003040 lua_pushinteger(L, 0);
3041
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003042 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003043}
3044
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003045/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003047 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048 * or -1 if the channel is closed or if the buffer size is too
3049 * little for the data.
3050 */
3051__LJMP static int hlua_channel_set(lua_State *L)
3052{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003053 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003054
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003055 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003056 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057 lua_pushinteger(L, 0);
3058
Thierry Fournier414ecb02020-08-15 14:35:51 +02003059 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
3060 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003061 WILL_LJMP(lua_error(L));
Thierry Fournier414ecb02020-08-15 14:35:51 +02003062 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003063
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003064 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003065
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003066 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003067}
3068
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003069/* Append data in the output side of the buffer. This data is immediately
3070 * sent. The function returns the amount of data written. If the buffer
3071 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003072 * if the channel is closed.
3073 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003074__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003075{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003076 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003077 size_t len;
3078 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3079 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3080 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003081 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003082
Thierry Fournier414ecb02020-08-15 14:35:51 +02003083 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
3084 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003085 WILL_LJMP(lua_error(L));
Thierry Fournier414ecb02020-08-15 14:35:51 +02003086 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003087
Willy Tarreau47860ed2015-03-10 14:07:50 +01003088 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003089 lua_pushinteger(L, -1);
3090 return 1;
3091 }
3092
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003093 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003094 * the request buffer if its not required.
3095 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003096 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01003097 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003098 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003099 }
3100
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003101 /* The written data will be immediately sent, so we can check
3102 * the available space without taking in account the reserve.
3103 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003104 * data, because the buffer will be flushed.
3105 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003106 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003107
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003108 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003109 * in this case, we cannot add more data, so we cannot yield,
3110 * we return the amount of copyied data.
3111 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003112 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003113 return 1;
3114
3115 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003116 if (max > len - l)
3117 max = len - l;
3118
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003119 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003120 * detects a non contiguous buffer and realign it.
3121 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003122 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003123 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003124
3125 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003126 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003127
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003128 /* buffer replace considers that the input part is filled.
3129 * so, I must forward these new data in the output part.
3130 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003131 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003132
3133 l += max;
3134 lua_pop(L, 1);
3135 lua_pushinteger(L, l);
3136
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003137 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003138 * in this case, we cannot add more data, so we cannot yield,
3139 * we return the amount of copyied data.
3140 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003141 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003142 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003143 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003144
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003145 if (l < len) {
3146 /* If we are waiting for space in the response buffer, we
3147 * must set the flag WAKERESWR. This flag required the task
3148 * wake up if any activity is detected on the response buffer.
3149 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003150 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003151 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003152 else
3153 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003154 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003155 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003156
3157 return 1;
3158}
3159
3160/* Just a wraper of "_hlua_channel_send". This wrapper permits
3161 * yield the LUA process, and resume it without checking the
3162 * input arguments.
3163 */
3164__LJMP static int hlua_channel_send(lua_State *L)
3165{
3166 MAY_LJMP(check_args(L, 2, "send"));
3167 lua_pushinteger(L, 0);
3168
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003169 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003170}
3171
3172/* This function forward and amount of butes. The data pass from
3173 * the input side of the buffer to the output side, and can be
3174 * forwarded. This function never fails.
3175 *
3176 * The Lua function takes an amount of bytes to be forwarded in
3177 * imput. It returns the number of bytes forwarded.
3178 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003179__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003180{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003181 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003182 int len;
3183 int l;
3184 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003185 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003186
3187 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003188
Thierry Fournier414ecb02020-08-15 14:35:51 +02003189 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
3190 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003191 WILL_LJMP(lua_error(L));
Thierry Fournier414ecb02020-08-15 14:35:51 +02003192 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003193
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003194 len = MAY_LJMP(luaL_checkinteger(L, 2));
3195 l = MAY_LJMP(luaL_checkinteger(L, -1));
3196
3197 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003198 if (max > ci_data(chn))
3199 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003200 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003201 l += max;
3202
3203 lua_pop(L, 1);
3204 lua_pushinteger(L, l);
3205
3206 /* Check if it miss bytes to forward. */
3207 if (l < len) {
3208 /* The the input channel or the output channel are closed, we
3209 * must return the amount of data forwarded.
3210 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003211 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003212 return 1;
3213
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003214 /* If we are waiting for space data in the response buffer, we
3215 * must set the flag WAKERESWR. This flag required the task
3216 * wake up if any activity is detected on the response buffer.
3217 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003218 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003219 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003220 else
3221 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003222
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003223 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003224 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003225 }
3226
3227 return 1;
3228}
3229
3230/* Just check the input and prepare the stack for the previous
3231 * function "hlua_channel_forward_yield"
3232 */
3233__LJMP static int hlua_channel_forward(lua_State *L)
3234{
3235 MAY_LJMP(check_args(L, 2, "forward"));
3236 MAY_LJMP(hlua_checkchannel(L, 1));
3237 MAY_LJMP(luaL_checkinteger(L, 2));
3238
3239 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003240 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003241}
3242
3243/* Just returns the number of bytes available in the input
3244 * side of the buffer. This function never fails.
3245 */
3246__LJMP static int hlua_channel_get_in_len(lua_State *L)
3247{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003248 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003249
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003250 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003251 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003252 if (IS_HTX_STRM(chn_strm(chn))) {
3253 struct htx *htx = htxbuf(&chn->buf);
3254 lua_pushinteger(L, htx->data - co_data(chn));
3255 }
3256 else
3257 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003258 return 1;
3259}
3260
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003261/* Returns true if the channel is full. */
3262__LJMP static int hlua_channel_is_full(lua_State *L)
3263{
3264 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003265
3266 MAY_LJMP(check_args(L, 1, "is_full"));
3267 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0136ebb2020-02-26 11:59:19 +01003268 /* ignore the reserve, we are not on a producer side (ie in an
3269 * applet).
3270 */
3271 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003272 return 1;
3273}
3274
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003275/* Just returns the number of bytes available in the output
3276 * side of the buffer. This function never fails.
3277 */
3278__LJMP static int hlua_channel_get_out_len(lua_State *L)
3279{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003280 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003281
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003282 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003283 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003284 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003285 return 1;
3286}
3287
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003288/*
3289 *
3290 *
3291 * Class Fetches
3292 *
3293 *
3294 */
3295
3296/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003297 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003298 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003299__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003300{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003301 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003302}
3303
3304/* This function creates and push in the stack a fetch object according
3305 * with a current TXN.
3306 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003307static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003308{
Willy Tarreau7073c472015-04-06 11:15:40 +02003309 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003310
3311 /* Check stack size. */
3312 if (!lua_checkstack(L, 3))
3313 return 0;
3314
3315 /* Create the object: obj[0] = userdata.
3316 * Note that the base of the Fetches object is the
3317 * transaction object.
3318 */
3319 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003320 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003321 lua_rawseti(L, -2, 0);
3322
Willy Tarreau7073c472015-04-06 11:15:40 +02003323 hsmp->s = txn->s;
3324 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003325 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003326 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003327
3328 /* Pop a class sesison metatable and affect it to the userdata. */
3329 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3330 lua_setmetatable(L, -2);
3331
3332 return 1;
3333}
3334
3335/* This function is an LUA binding. It is called with each sample-fetch.
3336 * It uses closure argument to store the associated sample-fetch. It
3337 * returns only one argument or throws an error. An error is thrown
3338 * only if an error is encountered during the argument parsing. If
3339 * the "sample-fetch" function fails, nil is returned.
3340 */
3341__LJMP static int hlua_run_sample_fetch(lua_State *L)
3342{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003343 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003344 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003345 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003346 int i;
3347 struct sample smp;
3348
3349 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003350 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003351
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003352 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003353 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003354
Thierry FOURNIERca988662015-12-20 18:43:03 +01003355 /* Check execution authorization. */
3356 if (f->use & SMP_USE_HTTP_ANY &&
3357 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3358 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3359 "is not available in Lua services", f->kw);
3360 WILL_LJMP(lua_error(L));
3361 }
3362
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003363 /* Get extra arguments. */
3364 for (i = 0; i < lua_gettop(L) - 1; i++) {
3365 if (i >= ARGM_NBARGS)
3366 break;
3367 hlua_lua2arg(L, i + 2, &args[i]);
3368 }
3369 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003370 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003371
3372 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003373 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003374
3375 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003376 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003377 lua_pushfstring(L, "error in arguments");
3378 WILL_LJMP(lua_error(L));
3379 }
3380
3381 /* Initialise the sample. */
3382 memset(&smp, 0, sizeof(smp));
3383
3384 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003385 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003386 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003387 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003388 lua_pushstring(L, "");
3389 else
3390 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003391 return 1;
3392 }
3393
3394 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003395 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003396 hlua_smp2lua_str(L, &smp);
3397 else
3398 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003399 return 1;
3400}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003401
3402/*
3403 *
3404 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003405 * Class Converters
3406 *
3407 *
3408 */
3409
3410/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003411 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003412 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003413__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003414{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003415 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003416}
3417
3418/* This function creates and push in the stack a Converters object
3419 * according with a current TXN.
3420 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003421static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003422{
Willy Tarreau7073c472015-04-06 11:15:40 +02003423 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003424
3425 /* Check stack size. */
3426 if (!lua_checkstack(L, 3))
3427 return 0;
3428
3429 /* Create the object: obj[0] = userdata.
3430 * Note that the base of the Converters object is the
3431 * same than the TXN object.
3432 */
3433 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003434 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003435 lua_rawseti(L, -2, 0);
3436
Willy Tarreau7073c472015-04-06 11:15:40 +02003437 hsmp->s = txn->s;
3438 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003439 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003440 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003441
Willy Tarreau87b09662015-04-03 00:22:06 +02003442 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003443 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3444 lua_setmetatable(L, -2);
3445
3446 return 1;
3447}
3448
3449/* This function is an LUA binding. It is called with each converter.
3450 * It uses closure argument to store the associated converter. It
3451 * returns only one argument or throws an error. An error is thrown
3452 * only if an error is encountered during the argument parsing. If
3453 * the converter function function fails, nil is returned.
3454 */
3455__LJMP static int hlua_run_sample_conv(lua_State *L)
3456{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003457 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003458 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003459 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003460 int i;
3461 struct sample smp;
3462
3463 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003464 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003465
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003466 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003467 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003468
3469 /* Get extra arguments. */
3470 for (i = 0; i < lua_gettop(L) - 2; i++) {
3471 if (i >= ARGM_NBARGS)
3472 break;
3473 hlua_lua2arg(L, i + 3, &args[i]);
3474 }
3475 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003476 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003477
3478 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003479 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003480
3481 /* Run the special args checker. */
3482 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3483 hlua_pusherror(L, "error in arguments");
3484 WILL_LJMP(lua_error(L));
3485 }
3486
3487 /* Initialise the sample. */
Amaury Denoyelleca492f32020-10-29 17:21:20 +01003488 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003489 if (!hlua_lua2smp(L, 2, &smp)) {
3490 hlua_pusherror(L, "error in the input argument");
3491 WILL_LJMP(lua_error(L));
3492 }
3493
Willy Tarreau1777ea62016-03-10 16:15:46 +01003494 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3495
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003496 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003497 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003498 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003499 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003500 WILL_LJMP(lua_error(L));
3501 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003502 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3503 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003504 hlua_pusherror(L, "error during the input argument casting");
3505 WILL_LJMP(lua_error(L));
3506 }
3507
3508 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003509 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003510 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003511 lua_pushstring(L, "");
3512 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003513 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003514 return 1;
3515 }
3516
3517 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003518 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003519 hlua_smp2lua_str(L, &smp);
3520 else
3521 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003522 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003523}
3524
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003525/*
3526 *
3527 *
3528 * Class AppletTCP
3529 *
3530 *
3531 */
3532
3533/* Returns a struct hlua_txn if the stack entry "ud" is
3534 * a class stream, otherwise it throws an error.
3535 */
3536__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3537{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003538 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003539}
3540
3541/* This function creates and push in the stack an Applet object
3542 * according with a current TXN.
3543 */
3544static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3545{
3546 struct hlua_appctx *appctx;
3547 struct stream_interface *si = ctx->owner;
3548 struct stream *s = si_strm(si);
3549 struct proxy *p = s->be;
3550
3551 /* Check stack size. */
3552 if (!lua_checkstack(L, 3))
3553 return 0;
3554
3555 /* Create the object: obj[0] = userdata.
3556 * Note that the base of the Converters object is the
3557 * same than the TXN object.
3558 */
3559 lua_newtable(L);
3560 appctx = lua_newuserdata(L, sizeof(*appctx));
3561 lua_rawseti(L, -2, 0);
3562 appctx->appctx = ctx;
3563 appctx->htxn.s = s;
3564 appctx->htxn.p = p;
3565
3566 /* Create the "f" field that contains a list of fetches. */
3567 lua_pushstring(L, "f");
3568 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3569 return 0;
3570 lua_settable(L, -3);
3571
3572 /* Create the "sf" field that contains a list of stringsafe fetches. */
3573 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003574 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003575 return 0;
3576 lua_settable(L, -3);
3577
3578 /* Create the "c" field that contains a list of converters. */
3579 lua_pushstring(L, "c");
3580 if (!hlua_converters_new(L, &appctx->htxn, 0))
3581 return 0;
3582 lua_settable(L, -3);
3583
3584 /* Create the "sc" field that contains a list of stringsafe converters. */
3585 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003586 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003587 return 0;
3588 lua_settable(L, -3);
3589
3590 /* Pop a class stream metatable and affect it to the table. */
3591 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3592 lua_setmetatable(L, -2);
3593
3594 return 1;
3595}
3596
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003597__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3598{
3599 struct hlua_appctx *appctx;
3600 struct stream *s;
3601 const char *name;
3602 size_t len;
3603 struct sample smp;
3604
3605 MAY_LJMP(check_args(L, 3, "set_var"));
3606
3607 /* It is useles to retrieve the stream, but this function
3608 * runs only in a stream context.
3609 */
3610 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3611 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3612 s = appctx->htxn.s;
3613
3614 /* Converts the third argument in a sample. */
Amaury Denoyelleca492f32020-10-29 17:21:20 +01003615 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003616 hlua_lua2smp(L, 3, &smp);
3617
3618 /* Store the sample in a variable. */
3619 smp_set_owner(&smp, s->be, s->sess, s, 0);
3620 vars_set_by_name(name, len, &smp);
3621 return 0;
3622}
3623
3624__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3625{
3626 struct hlua_appctx *appctx;
3627 struct stream *s;
3628 const char *name;
3629 size_t len;
3630 struct sample smp;
3631
3632 MAY_LJMP(check_args(L, 2, "unset_var"));
3633
3634 /* It is useles to retrieve the stream, but this function
3635 * runs only in a stream context.
3636 */
3637 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3638 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3639 s = appctx->htxn.s;
3640
3641 /* Unset the variable. */
3642 smp_set_owner(&smp, s->be, s->sess, s, 0);
3643 vars_unset_by_name(name, len, &smp);
3644 return 0;
3645}
3646
3647__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3648{
3649 struct hlua_appctx *appctx;
3650 struct stream *s;
3651 const char *name;
3652 size_t len;
3653 struct sample smp;
3654
3655 MAY_LJMP(check_args(L, 2, "get_var"));
3656
3657 /* It is useles to retrieve the stream, but this function
3658 * runs only in a stream context.
3659 */
3660 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3661 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3662 s = appctx->htxn.s;
3663
3664 smp_set_owner(&smp, s->be, s->sess, s, 0);
3665 if (!vars_get_by_name(name, len, &smp)) {
3666 lua_pushnil(L);
3667 return 1;
3668 }
3669
3670 return hlua_smp2lua(L, &smp);
3671}
3672
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003673__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3674{
3675 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3676 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003677 struct hlua *hlua;
3678
3679 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003680 if (!s->hlua)
3681 return 0;
3682 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003683
3684 MAY_LJMP(check_args(L, 2, "set_priv"));
3685
3686 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003687 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003688
3689 /* Get and store new value. */
3690 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3691 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3692
3693 return 0;
3694}
3695
3696__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3697{
3698 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3699 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003700 struct hlua *hlua;
3701
3702 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003703 if (!s->hlua) {
3704 lua_pushnil(L);
3705 return 1;
3706 }
3707 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003708
3709 /* Push configuration index in the stack. */
3710 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3711
3712 return 1;
3713}
3714
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003715/* If expected data not yet available, it returns a yield. This function
3716 * consumes the data in the buffer. It returns a string containing the
3717 * data. This string can be empty.
3718 */
3719__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3720{
3721 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3722 struct stream_interface *si = appctx->appctx->owner;
3723 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003724 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003725 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003726 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003727 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003728
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003729 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003730 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003731
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003732 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003733 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003734 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003735 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003736 }
3737
3738 /* End of data: commit the total strings and return. */
3739 if (ret < 0) {
3740 luaL_pushresult(&appctx->b);
3741 return 1;
3742 }
3743
3744 /* Ensure that the block 2 length is usable. */
3745 if (ret == 1)
3746 len2 = 0;
3747
3748 /* dont check the max length read and dont check. */
3749 luaL_addlstring(&appctx->b, blk1, len1);
3750 luaL_addlstring(&appctx->b, blk2, len2);
3751
3752 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003753 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003754 luaL_pushresult(&appctx->b);
3755 return 1;
3756}
3757
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003758/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003759__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3760{
3761 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3762
3763 /* Initialise the string catenation. */
3764 luaL_buffinit(L, &appctx->b);
3765
3766 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3767}
3768
3769/* If expected data not yet available, it returns a yield. This function
3770 * consumes the data in the buffer. It returns a string containing the
3771 * data. This string can be empty.
3772 */
3773__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3774{
3775 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3776 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003777 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003778 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003779 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003780 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003781 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003782 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003783
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003784 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003785 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003786
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003787 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003788 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003789 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003790 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003791 }
3792
3793 /* End of data: commit the total strings and return. */
3794 if (ret < 0) {
3795 luaL_pushresult(&appctx->b);
3796 return 1;
3797 }
3798
3799 /* Ensure that the block 2 length is usable. */
3800 if (ret == 1)
3801 len2 = 0;
3802
3803 if (len == -1) {
3804
3805 /* If len == -1, catenate all the data avalaile and
3806 * yield because we want to get all the data until
3807 * the end of data stream.
3808 */
3809 luaL_addlstring(&appctx->b, blk1, len1);
3810 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003811 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003812 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003813 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003814
3815 } else {
3816
3817 /* Copy the fisrt block caping to the length required. */
3818 if (len1 > len)
3819 len1 = len;
3820 luaL_addlstring(&appctx->b, blk1, len1);
3821 len -= len1;
3822
3823 /* Copy the second block. */
3824 if (len2 > len)
3825 len2 = len;
3826 luaL_addlstring(&appctx->b, blk2, len2);
3827 len -= len2;
3828
3829 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003830 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003831
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003832 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003833 if (len > 0) {
3834 lua_pushinteger(L, len);
3835 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003836 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003837 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003838 }
3839
3840 /* return the result. */
3841 luaL_pushresult(&appctx->b);
3842 return 1;
3843 }
3844
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003845 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003846 hlua_pusherror(L, "Lua: internal error");
3847 WILL_LJMP(lua_error(L));
3848 return 0;
3849}
3850
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003851/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003852__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3853{
3854 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3855 int len = -1;
3856
3857 if (lua_gettop(L) > 2)
3858 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3859 if (lua_gettop(L) >= 2) {
3860 len = MAY_LJMP(luaL_checkinteger(L, 2));
3861 lua_pop(L, 1);
3862 }
3863
3864 /* Confirm or set the required length */
3865 lua_pushinteger(L, len);
3866
3867 /* Initialise the string catenation. */
3868 luaL_buffinit(L, &appctx->b);
3869
3870 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3871}
3872
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003873/* Append data in the output side of the buffer. This data is immediately
3874 * sent. The function returns the amount of data written. If the buffer
3875 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003876 * if the channel is closed.
3877 */
3878__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3879{
3880 size_t len;
3881 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3882 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3883 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3884 struct stream_interface *si = appctx->appctx->owner;
3885 struct channel *chn = si_ic(si);
3886 int max;
3887
3888 /* Get the max amount of data which can write as input in the channel. */
3889 max = channel_recv_max(chn);
3890 if (max > (len - l))
3891 max = len - l;
3892
3893 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003894 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003895
3896 /* update counters. */
3897 l += max;
3898 lua_pop(L, 1);
3899 lua_pushinteger(L, l);
3900
3901 /* If some data is not send, declares the situation to the
3902 * applet, and returns a yield.
3903 */
3904 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003905 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003906 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003907 }
3908
3909 return 1;
3910}
3911
3912/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3913 * yield the LUA process, and resume it without checking the
3914 * input arguments.
3915 */
3916__LJMP static int hlua_applet_tcp_send(lua_State *L)
3917{
3918 MAY_LJMP(check_args(L, 2, "send"));
3919 lua_pushinteger(L, 0);
3920
3921 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3922}
3923
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003924/*
3925 *
3926 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003927 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003928 *
3929 *
3930 */
3931
3932/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003933 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003934 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003935__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003936{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003937 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003938}
3939
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003940/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003941 * according with a current TXN.
3942 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003943static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003944{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003945 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003946 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003947 struct stream_interface *si = ctx->owner;
3948 struct stream *s = si_strm(si);
3949 struct proxy *px = s->be;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003950
3951 /* Check stack size. */
3952 if (!lua_checkstack(L, 3))
3953 return 0;
3954
3955 /* Create the object: obj[0] = userdata.
3956 * Note that the base of the Converters object is the
3957 * same than the TXN object.
3958 */
3959 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003960 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003961 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003962 appctx->appctx = ctx;
3963 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003964 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003965 appctx->htxn.s = s;
3966 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003967
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003968 /* Create the "f" field that contains a list of fetches. */
3969 lua_pushstring(L, "f");
3970 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3971 return 0;
3972 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003973
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003974 /* Create the "sf" field that contains a list of stringsafe fetches. */
3975 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003976 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003977 return 0;
3978 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003979
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003980 /* Create the "c" field that contains a list of converters. */
3981 lua_pushstring(L, "c");
3982 if (!hlua_converters_new(L, &appctx->htxn, 0))
3983 return 0;
3984 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003985
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003986 /* Create the "sc" field that contains a list of stringsafe converters. */
3987 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003988 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003989 return 0;
3990 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003991
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003992 if (IS_HTX_STRM(s)) {
3993 /* HTX version */
3994 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet29f17582019-05-23 11:03:26 +02003995 struct htx_blk *blk;
3996 struct htx_sl *sl;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003997 struct ist path;
3998 unsigned long long len = 0;
3999 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004000
Christopher Faulet29f17582019-05-23 11:03:26 +02004001 blk = htx_get_first_blk(htx);
Christopher Faulet43a686d2019-11-18 15:50:25 +01004002 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Faulet29f17582019-05-23 11:03:26 +02004003 sl = htx_get_blk_ptr(htx, blk);
4004
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004005 /* Stores the request method. */
4006 lua_pushstring(L, "method");
4007 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4008 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004009
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004010 /* Stores the http version. */
4011 lua_pushstring(L, "version");
4012 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4013 lua_settable(L, -3);
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004014
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004015 /* creates an array of headers. hlua_http_get_headers() crates and push
4016 * the array on the top of the stack.
4017 */
4018 lua_pushstring(L, "headers");
4019 htxn.s = s;
4020 htxn.p = px;
4021 htxn.dir = SMP_OPT_DIR_REQ;
4022 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
4023 return 0;
4024 lua_settable(L, -3);
4025
4026 path = http_get_path(htx_sl_req_uri(sl));
4027 if (path.ptr) {
4028 char *p, *q, *end;
4029
4030 p = path.ptr;
4031 end = path.ptr + path.len;
4032 q = p;
4033 while (q < end && *q != '?')
4034 q++;
4035
4036 /* Stores the request path. */
4037 lua_pushstring(L, "path");
4038 lua_pushlstring(L, p, q - p);
4039 lua_settable(L, -3);
4040
4041 /* Stores the query string. */
4042 lua_pushstring(L, "qs");
4043 if (*q == '?')
4044 q++;
4045 lua_pushlstring(L, q, end - q);
4046 lua_settable(L, -3);
4047 }
4048
Christopher Fauleta3f15502019-05-13 15:27:23 +02004049 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004050 struct htx_blk *blk = htx_get_blk(htx, pos);
4051 enum htx_blk_type type = htx_get_blk_type(blk);
4052
Christopher Faulet54b5e212019-06-04 10:08:28 +02004053 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004054 break;
4055 if (type == HTX_BLK_DATA)
4056 len += htx_get_blksz(blk);
4057 }
4058 if (htx->extra != ULLONG_MAX)
4059 len += htx->extra;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004060
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004061 /* Stores the request path. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004062 lua_pushstring(L, "length");
4063 lua_pushinteger(L, len);
4064 lua_settable(L, -3);
4065 }
4066 else {
4067 /* Legacy HTTP version */
4068 struct http_txn *txn = s->txn;
4069 const char *path;
4070 const char *end;
4071 const char *p;
4072
4073 /* Stores the request method. */
4074 lua_pushstring(L, "method");
4075 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004076 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004077
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004078 /* Stores the http version. */
4079 lua_pushstring(L, "version");
4080 lua_pushlstring(L, ci_head(txn->req.chn) + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004081 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004082
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004083 /* creates an array of headers. hlua_http_get_headers() crates and push
4084 * the array on the top of the stack.
4085 */
4086 lua_pushstring(L, "headers");
4087 htxn.s = s;
4088 htxn.p = px;
4089 htxn.dir = SMP_OPT_DIR_REQ;
4090 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
4091 return 0;
4092 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004093
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004094 /* Get path and qs */
4095 path = http_txn_get_path(txn);
4096 if (path) {
4097 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
4098 p = path;
4099 while (p < end && *p != '?')
4100 p++;
4101
4102 /* Stores the request path. */
4103 lua_pushstring(L, "path");
4104 lua_pushlstring(L, path, p - path);
4105 lua_settable(L, -3);
4106
4107 /* Stores the query string. */
4108 lua_pushstring(L, "qs");
4109 if (*p == '?')
4110 p++;
4111 lua_pushlstring(L, p, end - p);
4112 lua_settable(L, -3);
4113 }
4114
4115 /* Stores the request path. */
4116 lua_pushstring(L, "length");
4117 lua_pushinteger(L, txn->req.body_len);
4118 lua_settable(L, -3);
4119 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004120
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004121 /* Create an empty array of HTTP request headers. */
4122 lua_pushstring(L, "response");
4123 lua_newtable(L);
4124 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004125
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004126 /* Pop a class stream metatable and affect it to the table. */
4127 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4128 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004129
4130 return 1;
4131}
4132
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004133__LJMP static int hlua_applet_http_set_var(lua_State *L)
4134{
4135 struct hlua_appctx *appctx;
4136 struct stream *s;
4137 const char *name;
4138 size_t len;
4139 struct sample smp;
4140
4141 MAY_LJMP(check_args(L, 3, "set_var"));
4142
4143 /* It is useles to retrieve the stream, but this function
4144 * runs only in a stream context.
4145 */
4146 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4147 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4148 s = appctx->htxn.s;
4149
4150 /* Converts the third argument in a sample. */
Amaury Denoyelleca492f32020-10-29 17:21:20 +01004151 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004152 hlua_lua2smp(L, 3, &smp);
4153
4154 /* Store the sample in a variable. */
4155 smp_set_owner(&smp, s->be, s->sess, s, 0);
4156 vars_set_by_name(name, len, &smp);
4157 return 0;
4158}
4159
4160__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4161{
4162 struct hlua_appctx *appctx;
4163 struct stream *s;
4164 const char *name;
4165 size_t len;
4166 struct sample smp;
4167
4168 MAY_LJMP(check_args(L, 2, "unset_var"));
4169
4170 /* It is useles to retrieve the stream, but this function
4171 * runs only in a stream context.
4172 */
4173 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4174 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4175 s = appctx->htxn.s;
4176
4177 /* Unset the variable. */
4178 smp_set_owner(&smp, s->be, s->sess, s, 0);
4179 vars_unset_by_name(name, len, &smp);
4180 return 0;
4181}
4182
4183__LJMP static int hlua_applet_http_get_var(lua_State *L)
4184{
4185 struct hlua_appctx *appctx;
4186 struct stream *s;
4187 const char *name;
4188 size_t len;
4189 struct sample smp;
4190
4191 MAY_LJMP(check_args(L, 2, "get_var"));
4192
4193 /* It is useles to retrieve the stream, but this function
4194 * runs only in a stream context.
4195 */
4196 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4197 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4198 s = appctx->htxn.s;
4199
4200 smp_set_owner(&smp, s->be, s->sess, s, 0);
4201 if (!vars_get_by_name(name, len, &smp)) {
4202 lua_pushnil(L);
4203 return 1;
4204 }
4205
4206 return hlua_smp2lua(L, &smp);
4207}
4208
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004209__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4210{
4211 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4212 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004213 struct hlua *hlua;
4214
4215 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004216 if (!s->hlua)
4217 return 0;
4218 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004219
4220 MAY_LJMP(check_args(L, 2, "set_priv"));
4221
4222 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004223 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004224
4225 /* Get and store new value. */
4226 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4227 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4228
4229 return 0;
4230}
4231
4232__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4233{
4234 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4235 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004236 struct hlua *hlua;
4237
4238 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004239 if (!s->hlua) {
4240 lua_pushnil(L);
4241 return 1;
4242 }
4243 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004244
4245 /* Push configuration index in the stack. */
4246 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4247
4248 return 1;
4249}
4250
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004251/* If expected data not yet available, it returns a yield. This function
4252 * consumes the data in the buffer. It returns a string containing the
4253 * data. This string can be empty.
4254 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004255__LJMP static int hlua_applet_htx_getline_yield(lua_State *L, int status, lua_KContext ctx)
4256{
4257 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4258 struct stream_interface *si = appctx->appctx->owner;
4259 struct channel *req = si_oc(si);
4260 struct htx *htx;
4261 struct htx_blk *blk;
4262 size_t count;
4263 int stop = 0;
4264
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004265 htx = htx_from_buf(&req->buf);
4266 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004267 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004268
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004269 while (count && !stop && blk) {
4270 enum htx_blk_type type = htx_get_blk_type(blk);
4271 uint32_t sz = htx_get_blksz(blk);
4272 struct ist v;
4273 uint32_t vlen;
4274 char *nl;
4275
Christopher Faulete461e342018-12-18 16:43:35 +01004276 if (type == HTX_BLK_EOM) {
4277 stop = 1;
4278 break;
4279 }
4280
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004281 vlen = sz;
4282 if (vlen > count) {
4283 if (type != HTX_BLK_DATA)
4284 break;
4285 vlen = count;
4286 }
4287
4288 switch (type) {
4289 case HTX_BLK_UNUSED:
4290 break;
4291
4292 case HTX_BLK_DATA:
4293 v = htx_get_blk_value(htx, blk);
4294 v.len = vlen;
4295 nl = istchr(v, '\n');
4296 if (nl != NULL) {
4297 stop = 1;
4298 vlen = nl - v.ptr + 1;
4299 }
4300 luaL_addlstring(&appctx->b, v.ptr, vlen);
4301 break;
4302
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004303 case HTX_BLK_TLR:
4304 case HTX_BLK_EOM:
4305 stop = 1;
4306 break;
4307
4308 default:
4309 break;
4310 }
4311
4312 co_set_data(req, co_data(req) - vlen);
4313 count -= vlen;
4314 if (sz == vlen)
4315 blk = htx_remove_blk(htx, blk);
4316 else {
4317 htx_cut_data_blk(htx, blk, vlen);
4318 break;
4319 }
4320 }
4321
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004322 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004323 if (!stop) {
4324 si_cant_get(si);
4325 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_getline_yield, TICK_ETERNITY, 0));
4326 }
4327
4328 /* return the result. */
4329 luaL_pushresult(&appctx->b);
4330 return 1;
4331}
4332
4333
4334/* If expected data not yet available, it returns a yield. This function
4335 * consumes the data in the buffer. It returns a string containing the
4336 * data. This string can be empty.
4337 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004338__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004339{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004340 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4341 struct stream_interface *si = appctx->appctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004342 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004343 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004344 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004345 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004346 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004347
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004348 /* Check for the end of the data. */
4349 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4350 luaL_pushresult(&appctx->b);
4351 return 1;
4352 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004353
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004354 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004355 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004356
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004357 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004358 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004359 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004360 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004361 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004362
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004363 /* End of data: commit the total strings and return. */
4364 if (ret < 0) {
4365 luaL_pushresult(&appctx->b);
4366 return 1;
4367 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004368
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004369 /* Ensure that the block 2 length is usable. */
4370 if (ret == 1)
4371 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004372
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004373 /* Copy the fisrt block caping to the length required. */
4374 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4375 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4376 luaL_addlstring(&appctx->b, blk1, len1);
4377 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004378
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004379 /* Copy the second block. */
4380 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4381 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4382 luaL_addlstring(&appctx->b, blk2, len2);
4383 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004384
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004385 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004386 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004387 luaL_pushresult(&appctx->b);
4388 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004389}
4390
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004391/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004392__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004393{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004394 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004395
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004396 /* Initialise the string catenation. */
4397 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004398
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004399 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
4400 return MAY_LJMP(hlua_applet_htx_getline_yield(L, 0, 0));
4401 else
4402 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004403}
4404
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004405/* If expected data not yet available, it returns a yield. This function
4406 * consumes the data in the buffer. It returns a string containing the
4407 * data. This string can be empty.
4408 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004409__LJMP static int hlua_applet_htx_recv_yield(lua_State *L, int status, lua_KContext ctx)
4410{
4411 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4412 struct stream_interface *si = appctx->appctx->owner;
4413 struct channel *req = si_oc(si);
4414 struct htx *htx;
4415 struct htx_blk *blk;
4416 size_t count;
4417 int len;
4418
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004419 htx = htx_from_buf(&req->buf);
4420 len = MAY_LJMP(luaL_checkinteger(L, 2));
4421 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004422 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004423 while (count && len && blk) {
4424 enum htx_blk_type type = htx_get_blk_type(blk);
4425 uint32_t sz = htx_get_blksz(blk);
4426 struct ist v;
4427 uint32_t vlen;
4428
Christopher Faulete461e342018-12-18 16:43:35 +01004429 if (type == HTX_BLK_EOM) {
4430 len = 0;
4431 break;
4432 }
4433
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004434 vlen = sz;
4435 if (len > 0 && vlen > len)
4436 vlen = len;
4437 if (vlen > count) {
4438 if (type != HTX_BLK_DATA)
4439 break;
4440 vlen = count;
4441 }
4442
4443 switch (type) {
4444 case HTX_BLK_UNUSED:
4445 break;
4446
4447 case HTX_BLK_DATA:
4448 v = htx_get_blk_value(htx, blk);
4449 luaL_addlstring(&appctx->b, v.ptr, vlen);
4450 break;
4451
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004452 case HTX_BLK_TLR:
4453 case HTX_BLK_EOM:
4454 len = 0;
4455 break;
4456
4457 default:
4458 break;
4459 }
4460
4461 co_set_data(req, co_data(req) - vlen);
4462 count -= vlen;
4463 if (len > 0)
4464 len -= vlen;
4465 if (sz == vlen)
4466 blk = htx_remove_blk(htx, blk);
4467 else {
4468 htx_cut_data_blk(htx, blk, vlen);
4469 break;
4470 }
4471 }
4472
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004473 htx_to_buf(htx, &req->buf);
4474
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004475 /* If we are no other data available, yield waiting for new data. */
4476 if (len) {
4477 if (len > 0) {
4478 lua_pushinteger(L, len);
4479 lua_replace(L, 2);
4480 }
4481 si_cant_get(si);
4482 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_recv_yield, TICK_ETERNITY, 0));
4483 }
4484
4485 /* return the result. */
4486 luaL_pushresult(&appctx->b);
4487 return 1;
4488}
4489
4490/* If expected data not yet available, it returns a yield. This function
4491 * consumes the data in the buffer. It returns a string containing the
4492 * data. This string can be empty.
4493 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004494__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004495{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004496 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4497 struct stream_interface *si = appctx->appctx->owner;
4498 int len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004499 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004500 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004501 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004502 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004503 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004504
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004505 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004506 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004507
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004508 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004509 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004510 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004511 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004512 }
4513
4514 /* End of data: commit the total strings and return. */
4515 if (ret < 0) {
4516 luaL_pushresult(&appctx->b);
4517 return 1;
4518 }
4519
4520 /* Ensure that the block 2 length is usable. */
4521 if (ret == 1)
4522 len2 = 0;
4523
4524 /* Copy the fisrt block caping to the length required. */
4525 if (len1 > len)
4526 len1 = len;
4527 luaL_addlstring(&appctx->b, blk1, len1);
4528 len -= len1;
4529
4530 /* Copy the second block. */
4531 if (len2 > len)
4532 len2 = len;
4533 luaL_addlstring(&appctx->b, blk2, len2);
4534 len -= len2;
4535
4536 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004537 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004538 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4539 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4540
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004541 /* If we are no other data available, yield waiting for new data. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004542 if (len > 0) {
4543 lua_pushinteger(L, len);
4544 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004545 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004546 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004547 }
4548
4549 /* return the result. */
4550 luaL_pushresult(&appctx->b);
4551 return 1;
4552}
4553
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004554/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004555__LJMP static int hlua_applet_http_recv(lua_State *L)
4556{
4557 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4558 int len = -1;
4559
4560 /* Check arguments. */
4561 if (lua_gettop(L) > 2)
4562 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4563 if (lua_gettop(L) >= 2) {
4564 len = MAY_LJMP(luaL_checkinteger(L, 2));
4565 lua_pop(L, 1);
4566 }
4567
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004568 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4569 /* HTX version */
4570 lua_pushinteger(L, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004571
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004572 /* Initialise the string catenation. */
4573 luaL_buffinit(L, &appctx->b);
4574
4575 return MAY_LJMP(hlua_applet_htx_recv_yield(L, 0, 0));
4576 }
4577 else {
4578 /* Legacy HTTP version */
4579 /* Check the required length */
4580 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4581 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4582 lua_pushinteger(L, len);
4583
4584 /* Initialise the string catenation. */
4585 luaL_buffinit(L, &appctx->b);
4586
4587 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4588 }
4589}
4590
4591/* Append data in the output side of the buffer. This data is immediately
4592 * sent. The function returns the amount of data written. If the buffer
4593 * cannot contain the data, the function yields. The function returns -1
4594 * if the channel is closed.
4595 */
4596__LJMP static int hlua_applet_htx_send_yield(lua_State *L, int status, lua_KContext ctx)
4597{
4598 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4599 struct stream_interface *si = appctx->appctx->owner;
4600 struct channel *res = si_ic(si);
4601 struct htx *htx = htx_from_buf(&res->buf);
4602 const char *data;
4603 size_t len;
4604 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4605 int max;
4606
Christopher Faulet4e963012019-07-03 11:39:30 +02004607 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004608 if (!max)
4609 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004610
4611 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4612
4613 /* Get the max amount of data which can write as input in the channel. */
4614 if (max > (len - l))
4615 max = len - l;
4616
4617 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004618 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004619 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004620
4621 /* update counters. */
4622 l += max;
4623 lua_pop(L, 1);
4624 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004625
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004626 /* If some data is not send, declares the situation to the
4627 * applet, and returns a yield.
4628 */
4629 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004630 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004631 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004632 si_rx_room_blk(si);
4633 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_send_yield, TICK_ETERNITY, 0));
4634 }
4635
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004636 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004637 return 1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004638}
4639
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004640/* Append data in the output side of the buffer. This data is immediately
4641 * sent. The function returns the amount of data written. If the buffer
4642 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004643 * if the channel is closed.
4644 */
4645__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4646{
4647 size_t len;
4648 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4649 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4650 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4651 struct stream_interface *si = appctx->appctx->owner;
4652 struct channel *chn = si_ic(si);
4653 int max;
4654
4655 /* Get the max amount of data which can write as input in the channel. */
4656 max = channel_recv_max(chn);
4657 if (max > (len - l))
4658 max = len - l;
4659
4660 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004661 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004662
4663 /* update counters. */
4664 l += max;
4665 lua_pop(L, 1);
4666 lua_pushinteger(L, l);
4667
4668 /* If some data is not send, declares the situation to the
4669 * applet, and returns a yield.
4670 */
4671 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004672 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004673 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004674 }
4675
4676 return 1;
4677}
4678
4679/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4680 * yield the LUA process, and resume it without checking the
4681 * input arguments.
4682 */
4683__LJMP static int hlua_applet_http_send(lua_State *L)
4684{
4685 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004686
4687 /* We want to send some data. Headers must be sent. */
4688 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4689 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4690 WILL_LJMP(lua_error(L));
4691 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004692
4693 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4694 /* HTX version */
4695 /* This interger is used for followinf the amount of data sent. */
4696 lua_pushinteger(L, 0);
4697
4698 return MAY_LJMP(hlua_applet_htx_send_yield(L, 0, 0));
4699 }
4700 else {
4701 /* Legacy HTTP version */
4702 size_t len;
4703 char hex[10];
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004704
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004705 MAY_LJMP(luaL_checklstring(L, 2, &len));
4706
4707 /* If transfer encoding chunked is selected, we surround the data
4708 * by chunk data.
4709 */
4710 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4711 snprintf(hex, 9, "%x", (unsigned int)len);
4712 lua_pushfstring(L, "%s\r\n", hex);
4713 lua_insert(L, 2); /* swap the last 2 entries. */
4714 lua_pushstring(L, "\r\n");
4715 lua_concat(L, 3);
4716 }
4717
4718 /* This interger is used for followinf the amount of data sent. */
4719 lua_pushinteger(L, 0);
4720
4721 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4722 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004723}
4724
4725__LJMP static int hlua_applet_http_addheader(lua_State *L)
4726{
4727 const char *name;
4728 int ret;
4729
4730 MAY_LJMP(hlua_checkapplet_http(L, 1));
4731 name = MAY_LJMP(luaL_checkstring(L, 2));
4732 MAY_LJMP(luaL_checkstring(L, 3));
4733
4734 /* Push in the stack the "response" entry. */
4735 ret = lua_getfield(L, 1, "response");
4736 if (ret != LUA_TTABLE) {
4737 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4738 "is expected as an array. %s found", lua_typename(L, ret));
4739 WILL_LJMP(lua_error(L));
4740 }
4741
4742 /* check if the header is already registered if it is not
4743 * the case, register it.
4744 */
4745 ret = lua_getfield(L, -1, name);
4746 if (ret == LUA_TNIL) {
4747
4748 /* Entry not found. */
4749 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4750
4751 /* Insert the new header name in the array in the top of the stack.
4752 * It left the new array in the top of the stack.
4753 */
4754 lua_newtable(L);
4755 lua_pushvalue(L, 2);
4756 lua_pushvalue(L, -2);
4757 lua_settable(L, -4);
4758
4759 } else if (ret != LUA_TTABLE) {
4760
4761 /* corruption error. */
4762 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4763 "is expected as an array. %s found", name, lua_typename(L, ret));
4764 WILL_LJMP(lua_error(L));
4765 }
4766
4767 /* Now the top od thestack is an array of values. We push
4768 * the header value as new entry.
4769 */
4770 lua_pushvalue(L, 3);
4771 ret = lua_rawlen(L, -2);
4772 lua_rawseti(L, -2, ret + 1);
4773 lua_pushboolean(L, 1);
4774 return 1;
4775}
4776
4777__LJMP static int hlua_applet_http_status(lua_State *L)
4778{
4779 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4780 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004781 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004782
4783 if (status < 100 || status > 599) {
4784 lua_pushboolean(L, 0);
4785 return 1;
4786 }
4787
4788 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004789 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004790 lua_pushboolean(L, 1);
4791 return 1;
4792}
4793
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004794
4795__LJMP static int hlua_applet_htx_send_response(lua_State *L)
4796{
4797 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4798 struct stream_interface *si = appctx->appctx->owner;
4799 struct channel *res = si_ic(si);
4800 struct htx *htx;
4801 struct htx_sl *sl;
4802 struct h1m h1m;
4803 const char *status, *reason;
4804 const char *name, *value;
4805 size_t nlen, vlen;
4806 unsigned int flags;
4807
4808 /* Send the message at once. */
4809 htx = htx_from_buf(&res->buf);
4810 h1m_init_res(&h1m);
4811
4812 /* Use the same http version than the request. */
4813 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4814 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4815 if (reason == NULL)
4816 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4817 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4818 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4819 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4820 }
4821 else {
4822 flags = HTX_SL_F_IS_RESP;
4823 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4824 }
4825 if (!sl) {
4826 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4827 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4828 WILL_LJMP(lua_error(L));
4829 }
4830 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4831
4832 /* Get the array associated to the field "response" in the object AppletHTTP. */
4833 lua_pushvalue(L, 0);
4834 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4835 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4836 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4837 WILL_LJMP(lua_error(L));
4838 }
4839
4840 /* Browse the list of headers. */
4841 lua_pushnil(L);
4842 while(lua_next(L, -2) != 0) {
4843 /* We expect a string as -2. */
4844 if (lua_type(L, -2) != LUA_TSTRING) {
4845 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4846 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4847 lua_typename(L, lua_type(L, -2)));
4848 WILL_LJMP(lua_error(L));
4849 }
4850 name = lua_tolstring(L, -2, &nlen);
4851
4852 /* We expect an array as -1. */
4853 if (lua_type(L, -1) != LUA_TTABLE) {
4854 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4855 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4856 name,
4857 lua_typename(L, lua_type(L, -1)));
4858 WILL_LJMP(lua_error(L));
4859 }
4860
4861 /* Browse the table who is on the top of the stack. */
4862 lua_pushnil(L);
4863 while(lua_next(L, -2) != 0) {
4864 int id;
4865
4866 /* We expect a number as -2. */
4867 if (lua_type(L, -2) != LUA_TNUMBER) {
4868 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4869 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4870 name,
4871 lua_typename(L, lua_type(L, -2)));
4872 WILL_LJMP(lua_error(L));
4873 }
4874 id = lua_tointeger(L, -2);
4875
4876 /* We expect a string as -2. */
4877 if (lua_type(L, -1) != LUA_TSTRING) {
4878 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4879 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4880 name, id,
4881 lua_typename(L, lua_type(L, -1)));
4882 WILL_LJMP(lua_error(L));
4883 }
4884 value = lua_tolstring(L, -1, &vlen);
4885
4886 /* Simple Protocol checks. */
4887 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
4888 h1_parse_xfer_enc_header(&h1m, ist2(name, nlen));
4889 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4890 struct ist v = ist2(value, vlen);
4891 int ret;
4892
4893 ret = h1_parse_cont_len_header(&h1m, &v);
4894 if (ret < 0) {
4895 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4896 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4897 name);
4898 WILL_LJMP(lua_error(L));
4899 }
4900 else if (ret == 0)
4901 goto next; /* Skip it */
4902 }
4903
4904 /* Add a new header */
4905 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4906 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4907 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4908 name);
4909 WILL_LJMP(lua_error(L));
4910 }
4911 next:
4912 /* Remove the array from the stack, and get next element with a remaining string. */
4913 lua_pop(L, 1);
4914 }
4915
4916 /* Remove the array from the stack, and get next element with a remaining string. */
4917 lua_pop(L, 1);
4918 }
4919
4920 if (h1m.flags & H1_MF_CHNK)
4921 h1m.flags &= ~H1_MF_CLEN;
4922 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4923 h1m.flags |= H1_MF_XFER_LEN;
4924
4925 /* Uset HTX start-line flags */
4926 if (h1m.flags & H1_MF_XFER_ENC)
4927 flags |= HTX_SL_F_XFER_ENC;
4928 if (h1m.flags & H1_MF_XFER_LEN) {
4929 flags |= HTX_SL_F_XFER_LEN;
4930 if (h1m.flags & H1_MF_CHNK)
4931 flags |= HTX_SL_F_CHNK;
4932 else if (h1m.flags & H1_MF_CLEN)
4933 flags |= HTX_SL_F_CLEN;
4934 if (h1m.body_len == 0)
4935 flags |= HTX_SL_F_BODYLESS;
4936 }
4937 sl->flags |= flags;
4938
4939 /* If we dont have a content-length set, and the HTTP version is 1.1
4940 * and the status code implies the presence of a message body, we must
4941 * announce a transfer encoding chunked. This is required by haproxy
4942 * for the keepalive compliance. If the applet annouces a transfer-encoding
4943 * chunked itslef, don't do anything.
4944 */
4945 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4946 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4947 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4948 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4949 /* Add a new header */
4950 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4951 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4952 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4953 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4954 WILL_LJMP(lua_error(L));
4955 }
4956 }
4957
4958 /* Finalize headers. */
4959 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4960 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4961 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4962 WILL_LJMP(lua_error(L));
4963 }
4964
4965 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4966 b_reset(&res->buf);
4967 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4968 WILL_LJMP(lua_error(L));
4969 }
4970
4971 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004972 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004973
4974 /* Headers sent, set the flag. */
4975 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4976 return 0;
4977
4978}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004979/* We will build the status line and the headers of the HTTP response.
4980 * We will try send at once if its not possible, we give back the hand
4981 * waiting for more room.
4982 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004983__LJMP static int hlua_applet_htx_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4984{
4985 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4986 struct stream_interface *si = appctx->appctx->owner;
4987 struct channel *res = si_ic(si);
4988
4989 if (co_data(res)) {
4990 si_rx_room_blk(si);
4991 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_start_response_yield, TICK_ETERNITY, 0));
4992 }
4993 return MAY_LJMP(hlua_applet_htx_send_response(L));
4994}
4995
4996
4997__LJMP static int hlua_applet_htx_start_response(lua_State *L)
4998{
4999 return MAY_LJMP(hlua_applet_htx_start_response_yield(L, 0, 0));
5000}
5001
5002/* We will build the status line and the headers of the HTTP response.
5003 * We will try send at once if its not possible, we give back the hand
5004 * waiting for more room.
5005 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005006__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
5007{
5008 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5009 struct stream_interface *si = appctx->appctx->owner;
5010 struct channel *chn = si_ic(si);
5011 int ret;
5012 size_t len;
5013 const char *msg;
5014
5015 /* Get the message as the first argument on the stack. */
5016 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
5017
5018 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02005019 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005020
5021 /* if ret == -2 or -3 the channel closed or the message si too
5022 * big for the buffers.
5023 */
5024 if (ret == -2 || ret == -3) {
5025 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5026 WILL_LJMP(lua_error(L));
5027 }
5028
5029 /* If ret is -1, we dont have room in the buffer, so we yield. */
5030 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01005031 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005032 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005033 }
5034
5035 /* Headers sent, set the flag. */
5036 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
5037 return 0;
5038}
5039
5040__LJMP static int hlua_applet_http_start_response(lua_State *L)
5041{
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005042 struct buffer *tmp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005043 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005044 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02005045 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005046 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02005047 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005048 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005049 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005050 int hdr_chunked = 0;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005051 const char *reason;
5052
5053 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
5054 return MAY_LJMP(hlua_applet_htx_start_response(L));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005055
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005056 reason = appctx->appctx->ctx.hlua_apphttp.reason;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005057 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02005058 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005059
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005060 tmp = get_trash_chunk();
5061
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005062 /* Use the same http version than the request. */
5063 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005064 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005065 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005066 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005067
5068 /* Get the array associated to the field "response" in the object AppletHTTP. */
5069 lua_pushvalue(L, 0);
5070 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5071 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
5072 appctx->appctx->rule->arg.hlua_rule->fcn.name);
5073 WILL_LJMP(lua_error(L));
5074 }
5075
5076 /* Browse the list of headers. */
5077 lua_pushnil(L);
5078 while(lua_next(L, -2) != 0) {
5079
5080 /* We expect a string as -2. */
5081 if (lua_type(L, -2) != LUA_TSTRING) {
5082 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
5083 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5084 lua_typename(L, lua_type(L, -2)));
5085 WILL_LJMP(lua_error(L));
5086 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005087 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005088
5089 /* We expect an array as -1. */
5090 if (lua_type(L, -1) != LUA_TTABLE) {
5091 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
5092 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5093 name,
5094 lua_typename(L, lua_type(L, -1)));
5095 WILL_LJMP(lua_error(L));
5096 }
5097
5098 /* Browse the table who is on the top of the stack. */
5099 lua_pushnil(L);
5100 while(lua_next(L, -2) != 0) {
5101
5102 /* We expect a number as -2. */
5103 if (lua_type(L, -2) != LUA_TNUMBER) {
5104 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
5105 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5106 name,
5107 lua_typename(L, lua_type(L, -2)));
5108 WILL_LJMP(lua_error(L));
5109 }
5110 id = lua_tointeger(L, -2);
5111
5112 /* We expect a string as -2. */
5113 if (lua_type(L, -1) != LUA_TSTRING) {
5114 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
5115 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5116 name, id,
5117 lua_typename(L, lua_type(L, -1)));
5118 WILL_LJMP(lua_error(L));
5119 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005120 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005121
5122 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005123 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
5124 memcpy(tmp->area + tmp->data, name, name_len);
5125 tmp->data += name_len;
5126 tmp->area[tmp->data++] = ':';
5127 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02005128
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005129 memcpy(tmp->area + tmp->data, value,
5130 value_len);
5131 tmp->data += value_len;
5132 tmp->area[tmp->data++] = '\r';
5133 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02005134 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005135
5136 /* Protocol checks. */
5137
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005138 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005139 * is done without control. If it contains a bad value,
5140 * the content-length remains negative so that we can
5141 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005142 */
Willy Tarreaua3294632017-08-23 11:24:47 +02005143 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005144 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005145
5146 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02005147 if (name_len == 17 && value_len == 7 &&
5148 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005149 strcasecmp("chunked", value) == 0)
5150 hdr_chunked = 1;
5151
5152 /* Remove the array from the stack, and get next element with a remaining string. */
5153 lua_pop(L, 1);
5154 }
5155
5156 /* Remove the array from the stack, and get next element with a remaining string. */
5157 lua_pop(L, 1);
5158 }
5159
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005160 /* If we dont have a content-length set, and the HTTP version is 1.1
5161 * and the status code implies the presence of a message body, we must
5162 * announce a transfer encoding chunked. This is required by haproxy
5163 * for the keepalive compliance. If the applet annouces a transfer-encoding
5164 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005165 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005166 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005167 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
5168 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
5169 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
5170 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005171 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
5172 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
5173 }
5174
5175 /* Finalize headers. */
5176 chunk_appendf(tmp, "\r\n");
5177
5178 /* Remove the last entry and the array of headers */
5179 lua_pop(L, 2);
5180
5181 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005182 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005183
5184 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
5185}
5186
5187/*
5188 *
5189 *
5190 * Class HTTP
5191 *
5192 *
5193 */
5194
5195/* Returns a struct hlua_txn if the stack entry "ud" is
5196 * a class stream, otherwise it throws an error.
5197 */
5198__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
5199{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005200 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005201}
5202
5203/* This function creates and push in the stack a HTTP object
5204 * according with a current TXN.
5205 */
5206static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5207{
5208 struct hlua_txn *htxn;
5209
5210 /* Check stack size. */
5211 if (!lua_checkstack(L, 3))
5212 return 0;
5213
5214 /* Create the object: obj[0] = userdata.
5215 * Note that the base of the Converters object is the
5216 * same than the TXN object.
5217 */
5218 lua_newtable(L);
5219 htxn = lua_newuserdata(L, sizeof(*htxn));
5220 lua_rawseti(L, -2, 0);
5221
5222 htxn->s = txn->s;
5223 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005224 htxn->dir = txn->dir;
5225 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005226
5227 /* Pop a class stream metatable and affect it to the table. */
5228 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5229 lua_setmetatable(L, -2);
5230
5231 return 1;
5232}
5233
5234/* This function creates ans returns an array of HTTP headers.
5235 * This function does not fails. It is used as wrapper with the
5236 * 2 following functions.
5237 */
5238__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5239{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005240 /* Create the table. */
5241 lua_newtable(L);
5242
5243 if (!htxn->s->txn)
5244 return 1;
5245
Christopher Faulet724a12c2018-12-13 22:12:15 +01005246 if (IS_HTX_STRM(htxn->s)) {
5247 /* HTX version */
5248 struct htx *htx = htxbuf(&msg->chn->buf);
5249 int32_t pos;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005250
Christopher Fauleta3f15502019-05-13 15:27:23 +02005251 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet724a12c2018-12-13 22:12:15 +01005252 struct htx_blk *blk = htx_get_blk(htx, pos);
5253 enum htx_blk_type type = htx_get_blk_type(blk);
5254 struct ist n, v;
5255 int len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005256
Christopher Faulet724a12c2018-12-13 22:12:15 +01005257 if (type == HTX_BLK_HDR) {
5258 n = htx_get_blk_name(htx,blk);
5259 v = htx_get_blk_value(htx, blk);
5260 }
5261 else if (type == HTX_BLK_EOH)
5262 break;
5263 else
5264 continue;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005265
Christopher Faulet724a12c2018-12-13 22:12:15 +01005266 /* Check for existing entry:
5267 * assume that the table is on the top of the stack, and
5268 * push the key in the stack, the function lua_gettable()
5269 * perform the lookup.
5270 */
5271 lua_pushlstring(L, n.ptr, n.len);
5272 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005273
Christopher Faulet724a12c2018-12-13 22:12:15 +01005274 switch (lua_type(L, -1)) {
5275 case LUA_TNIL:
5276 /* Table not found, create it. */
5277 lua_pop(L, 1); /* remove the nil value. */
5278 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5279 lua_newtable(L); /* create and push empty table. */
5280 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5281 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5282 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5283 break;
5284
5285 case LUA_TTABLE:
5286 /* Entry found: push the value in the table. */
5287 len = lua_rawlen(L, -1);
5288 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5289 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5290 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5291 break;
5292
5293 default:
5294 /* Other cases are errors. */
5295 hlua_pusherror(L, "internal error during the parsing of headers.");
5296 WILL_LJMP(lua_error(L));
5297 }
5298 }
5299 }
5300 else {
5301 /* Legacy HTTP version */
5302 const char *cur_ptr, *cur_next, *p;
5303 int old_idx, cur_idx;
5304 struct hdr_idx_elem *cur_hdr;
5305 const char *hn, *hv;
5306 int hnl, hvl;
5307 const char *in;
5308 char *out;
5309 int len;
5310
5311 /* Build array of headers. */
5312 old_idx = 0;
5313 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
5314
5315 while (1) {
5316 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
5317 if (!cur_idx)
5318 break;
5319 old_idx = cur_idx;
5320
5321 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
5322 cur_ptr = cur_next;
5323 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
5324
5325 /* Now we have one full header at cur_ptr of len cur_hdr->len,
5326 * and the next header starts at cur_next. We'll check
5327 * this header in the list as well as against the default
5328 * rule.
5329 */
5330
5331 /* look for ': *'. */
5332 hn = cur_ptr;
5333 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
5334 if (p >= cur_ptr+cur_hdr->len)
5335 continue;
5336 hnl = p - hn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005337 p++;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005338 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
5339 p++;
5340 if (p >= cur_ptr+cur_hdr->len)
5341 continue;
5342 hv = p;
5343 hvl = cur_ptr+cur_hdr->len-p;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005344
Christopher Faulet724a12c2018-12-13 22:12:15 +01005345 /* Lowercase the key. Don't check the size of trash, it have
5346 * the size of one buffer and the input data contains in one
5347 * buffer.
5348 */
5349 out = trash.area;
5350 for (in=hn; in<hn+hnl; in++, out++)
5351 *out = tolower(*in);
5352 *out = '\0';
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005353
Christopher Faulet724a12c2018-12-13 22:12:15 +01005354 /* Check for existing entry:
5355 * assume that the table is on the top of the stack, and
5356 * push the key in the stack, the function lua_gettable()
5357 * perform the lookup.
5358 */
5359 lua_pushlstring(L, trash.area, hnl);
5360 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005361
Christopher Faulet724a12c2018-12-13 22:12:15 +01005362 switch (lua_type(L, -1)) {
5363 case LUA_TNIL:
5364 /* Table not found, create it. */
5365 lua_pop(L, 1); /* remove the nil value. */
5366 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
5367 lua_newtable(L); /* create and push empty table. */
5368 lua_pushlstring(L, hv, hvl); /* push header value. */
5369 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5370 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5371 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005372
Christopher Faulet724a12c2018-12-13 22:12:15 +01005373 case LUA_TTABLE:
5374 /* Entry found: push the value in the table. */
5375 len = lua_rawlen(L, -1);
5376 lua_pushlstring(L, hv, hvl); /* push header value. */
5377 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5378 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5379 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005380
Christopher Faulet724a12c2018-12-13 22:12:15 +01005381 default:
5382 /* Other cases are errors. */
5383 hlua_pusherror(L, "internal error during the parsing of headers.");
5384 WILL_LJMP(lua_error(L));
5385 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005386 }
5387 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005388 return 1;
5389}
5390
5391__LJMP static int hlua_http_req_get_headers(lua_State *L)
5392{
5393 struct hlua_txn *htxn;
5394
5395 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5396 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5397
Christopher Faulet2351ca22019-07-26 16:31:34 +02005398 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005399 WILL_LJMP(lua_error(L));
5400
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005401 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
5402}
5403
5404__LJMP static int hlua_http_res_get_headers(lua_State *L)
5405{
5406 struct hlua_txn *htxn;
5407
5408 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5409 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5410
Christopher Faulet2351ca22019-07-26 16:31:34 +02005411 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005412 WILL_LJMP(lua_error(L));
5413
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005414 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
5415}
5416
5417/* This function replace full header, or just a value in
5418 * the request or in the response. It is a wrapper fir the
5419 * 4 following functions.
5420 */
5421__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
5422 struct http_msg *msg, int action)
5423{
5424 size_t name_len;
5425 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5426 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5427 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Dragan Dosen26743032019-04-30 15:54:36 +02005428 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005429
Dragan Dosen26743032019-04-30 15:54:36 +02005430 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005431 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5432
Christopher Faulet5a8549e2019-06-17 13:36:06 +02005433 if (IS_HTX_STRM(htxn->s)) {
5434 struct htx *htx = htxbuf(&msg->chn->buf);
5435
5436 htx_transform_header_str(htxn->s, msg->chn, htx, ist2(name, name_len), value, re, action);
5437 }
5438 else
5439 http_transform_header_str(htxn->s, msg, name, name_len, value, re, action);
Dragan Dosen26743032019-04-30 15:54:36 +02005440 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005441 return 0;
5442}
5443
5444__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5445{
5446 struct hlua_txn *htxn;
5447
5448 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5449 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5450
Christopher Faulet2351ca22019-07-26 16:31:34 +02005451 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005452 WILL_LJMP(lua_error(L));
5453
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005454 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
5455}
5456
5457__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5458{
5459 struct hlua_txn *htxn;
5460
5461 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5462 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5463
Christopher Faulet2351ca22019-07-26 16:31:34 +02005464 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005465 WILL_LJMP(lua_error(L));
5466
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005467 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
5468}
5469
5470__LJMP static int hlua_http_req_rep_val(lua_State *L)
5471{
5472 struct hlua_txn *htxn;
5473
5474 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5475 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5476
Christopher Faulet2351ca22019-07-26 16:31:34 +02005477 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005478 WILL_LJMP(lua_error(L));
5479
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005480 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
5481}
5482
5483__LJMP static int hlua_http_res_rep_val(lua_State *L)
5484{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005485 struct hlua_txn *htxn;
5486
5487 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5488 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5489
Christopher Faulet2351ca22019-07-26 16:31:34 +02005490 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005491 WILL_LJMP(lua_error(L));
5492
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02005493 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005494}
5495
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005496/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005497 * It is a wrapper for the 2 following functions.
5498 */
5499__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5500{
5501 size_t len;
5502 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005503
Christopher Faulet724a12c2018-12-13 22:12:15 +01005504 if (IS_HTX_STRM(htxn->s)) {
5505 /* HTX version */
5506 struct htx *htx = htxbuf(&msg->chn->buf);
5507 struct http_hdr_ctx ctx;
5508
5509 ctx.blk = NULL;
5510 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5511 http_remove_header(htx, &ctx);
5512 }
5513 else {
5514 /* Legacy HTTP version */
5515 struct hdr_ctx ctx;
5516 struct http_txn *txn = htxn->s->txn;
5517
5518 ctx.idx = 0;
5519 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
5520 http_remove_header2(msg, &txn->hdr_idx, &ctx);
5521 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005522 return 0;
5523}
5524
5525__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5526{
5527 struct hlua_txn *htxn;
5528
5529 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5530 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5531
Christopher Faulet2351ca22019-07-26 16:31:34 +02005532 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005533 WILL_LJMP(lua_error(L));
5534
Willy Tarreaueee5b512015-04-03 23:46:31 +02005535 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005536}
5537
5538__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5539{
5540 struct hlua_txn *htxn;
5541
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005542 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005543 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5544
Christopher Faulet2351ca22019-07-26 16:31:34 +02005545 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005546 WILL_LJMP(lua_error(L));
5547
Willy Tarreaueee5b512015-04-03 23:46:31 +02005548 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005549}
5550
5551/* This function adds an header. It is a wrapper used by
5552 * the 2 following functions.
5553 */
5554__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5555{
5556 size_t name_len;
5557 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5558 size_t value_len;
5559 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
5560 char *p;
5561
Christopher Faulet724a12c2018-12-13 22:12:15 +01005562 if (IS_HTX_STRM(htxn->s)) {
5563 /* HTX version */
5564 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005565
Christopher Faulet724a12c2018-12-13 22:12:15 +01005566 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5567 ist2(value, value_len)));
5568 }
5569 else {
5570 /* Legacy HTTP version */
5571 /* Check length. */
5572 trash.data = value_len + name_len + 2;
5573 if (trash.data > trash.size)
5574 return 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005575
Christopher Faulet724a12c2018-12-13 22:12:15 +01005576 /* Creates the header string. */
5577 p = trash.area;
5578 memcpy(p, name, name_len);
5579 p += name_len;
5580 *p = ':';
5581 p++;
5582 *p = ' ';
5583 p++;
5584 memcpy(p, value, value_len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005585
Christopher Faulet724a12c2018-12-13 22:12:15 +01005586 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
5587 trash.area, trash.data) != 0);
5588 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005589 return 0;
5590}
5591
5592__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5593{
5594 struct hlua_txn *htxn;
5595
5596 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5597 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5598
Christopher Faulet2351ca22019-07-26 16:31:34 +02005599 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005600 WILL_LJMP(lua_error(L));
5601
Willy Tarreaueee5b512015-04-03 23:46:31 +02005602 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005603}
5604
5605__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5606{
5607 struct hlua_txn *htxn;
5608
5609 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5610 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5611
Christopher Faulet2351ca22019-07-26 16:31:34 +02005612 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005613 WILL_LJMP(lua_error(L));
5614
Willy Tarreaueee5b512015-04-03 23:46:31 +02005615 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005616}
5617
5618static int hlua_http_req_set_hdr(lua_State *L)
5619{
5620 struct hlua_txn *htxn;
5621
5622 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5623 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5624
Christopher Faulet2351ca22019-07-26 16:31:34 +02005625 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005626 WILL_LJMP(lua_error(L));
5627
Willy Tarreaueee5b512015-04-03 23:46:31 +02005628 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
5629 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005630}
5631
5632static int hlua_http_res_set_hdr(lua_State *L)
5633{
5634 struct hlua_txn *htxn;
5635
5636 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5637 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5638
Christopher Faulet2351ca22019-07-26 16:31:34 +02005639 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005640 WILL_LJMP(lua_error(L));
5641
Willy Tarreaueee5b512015-04-03 23:46:31 +02005642 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
5643 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005644}
5645
5646/* This function set the method. */
5647static int hlua_http_req_set_meth(lua_State *L)
5648{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005649 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005650 size_t name_len;
5651 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005652
Christopher Faulet2351ca22019-07-26 16:31:34 +02005653 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005654 WILL_LJMP(lua_error(L));
5655
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005656 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005657 return 1;
5658}
5659
5660/* This function set the method. */
5661static int hlua_http_req_set_path(lua_State *L)
5662{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005663 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005664 size_t name_len;
5665 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005666
Christopher Faulet2351ca22019-07-26 16:31:34 +02005667 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005668 WILL_LJMP(lua_error(L));
5669
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005670 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005671 return 1;
5672}
5673
5674/* This function set the query-string. */
5675static int hlua_http_req_set_query(lua_State *L)
5676{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005677 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005678 size_t name_len;
5679 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005680
Christopher Faulet2351ca22019-07-26 16:31:34 +02005681 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005682 WILL_LJMP(lua_error(L));
5683
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005684 /* Check length. */
5685 if (name_len > trash.size - 1) {
5686 lua_pushboolean(L, 0);
5687 return 1;
5688 }
5689
5690 /* Add the mark question as prefix. */
5691 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005692 trash.area[trash.data++] = '?';
5693 memcpy(trash.area + trash.data, name, name_len);
5694 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005695
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005696 lua_pushboolean(L,
5697 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005698 return 1;
5699}
5700
5701/* This function set the uri. */
5702static int hlua_http_req_set_uri(lua_State *L)
5703{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005704 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005705 size_t name_len;
5706 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005707
Christopher Faulet2351ca22019-07-26 16:31:34 +02005708 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005709 WILL_LJMP(lua_error(L));
5710
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005711 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005712 return 1;
5713}
5714
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005715/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005716static int hlua_http_res_set_status(lua_State *L)
5717{
5718 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5719 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005720 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005721
Christopher Faulet2351ca22019-07-26 16:31:34 +02005722 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005723 WILL_LJMP(lua_error(L));
5724
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005725 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005726 return 0;
5727}
5728
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005729/*
5730 *
5731 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005732 * Class TXN
5733 *
5734 *
5735 */
5736
5737/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005738 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005739 */
5740__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5741{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005742 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005743}
5744
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005745__LJMP static int hlua_set_var(lua_State *L)
5746{
5747 struct hlua_txn *htxn;
5748 const char *name;
5749 size_t len;
5750 struct sample smp;
5751
5752 MAY_LJMP(check_args(L, 3, "set_var"));
5753
5754 /* It is useles to retrieve the stream, but this function
5755 * runs only in a stream context.
5756 */
5757 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5758 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5759
5760 /* Converts the third argument in a sample. */
Amaury Denoyelleca492f32020-10-29 17:21:20 +01005761 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005762 hlua_lua2smp(L, 3, &smp);
5763
5764 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005765 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005766 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005767 return 0;
5768}
5769
Christopher Faulet85d79c92016-11-09 16:54:56 +01005770__LJMP static int hlua_unset_var(lua_State *L)
5771{
5772 struct hlua_txn *htxn;
5773 const char *name;
5774 size_t len;
5775 struct sample smp;
5776
5777 MAY_LJMP(check_args(L, 2, "unset_var"));
5778
5779 /* It is useles to retrieve the stream, but this function
5780 * runs only in a stream context.
5781 */
5782 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5783 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5784
5785 /* Unset the variable. */
5786 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5787 vars_unset_by_name(name, len, &smp);
5788 return 0;
5789}
5790
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005791__LJMP static int hlua_get_var(lua_State *L)
5792{
5793 struct hlua_txn *htxn;
5794 const char *name;
5795 size_t len;
5796 struct sample smp;
5797
5798 MAY_LJMP(check_args(L, 2, "get_var"));
5799
5800 /* It is useles to retrieve the stream, but this function
5801 * runs only in a stream context.
5802 */
5803 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5804 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5805
Willy Tarreau7560dd42016-03-10 16:28:58 +01005806 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005807 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005808 lua_pushnil(L);
5809 return 1;
5810 }
5811
5812 return hlua_smp2lua(L, &smp);
5813}
5814
Willy Tarreau59551662015-03-10 14:23:13 +01005815__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005816{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005817 struct hlua *hlua;
5818
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005819 MAY_LJMP(check_args(L, 2, "set_priv"));
5820
Willy Tarreau87b09662015-04-03 00:22:06 +02005821 /* It is useles to retrieve the stream, but this function
5822 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005823 */
5824 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005825 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005826
5827 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005828 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005829
5830 /* Get and store new value. */
5831 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5832 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5833
5834 return 0;
5835}
5836
Willy Tarreau59551662015-03-10 14:23:13 +01005837__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005838{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005839 struct hlua *hlua;
5840
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005841 MAY_LJMP(check_args(L, 1, "get_priv"));
5842
Willy Tarreau87b09662015-04-03 00:22:06 +02005843 /* It is useles to retrieve the stream, but this function
5844 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005845 */
5846 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005847 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005848
5849 /* Push configuration index in the stack. */
5850 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5851
5852 return 1;
5853}
5854
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005855/* Create stack entry containing a class TXN. This function
5856 * return 0 if the stack does not contains free slots,
5857 * otherwise it returns 1.
5858 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005859static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005860{
Willy Tarreaude491382015-04-06 11:04:28 +02005861 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005862
5863 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005864 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005865 return 0;
5866
5867 /* NOTE: The allocation never fails. The failure
5868 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005869 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005870 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005871 /* Create the object: obj[0] = userdata. */
5872 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005873 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005874 lua_rawseti(L, -2, 0);
5875
Willy Tarreaude491382015-04-06 11:04:28 +02005876 htxn->s = s;
5877 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005878 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005879 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005880
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005881 /* Create the "f" field that contains a list of fetches. */
5882 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005883 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005884 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005885 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005886
5887 /* Create the "sf" field that contains a list of stringsafe fetches. */
5888 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005889 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005890 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005891 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005892
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005893 /* Create the "c" field that contains a list of converters. */
5894 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005895 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005896 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005897 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005898
5899 /* Create the "sc" field that contains a list of stringsafe converters. */
5900 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005901 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005902 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005903 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005904
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005905 /* Create the "req" field that contains the request channel object. */
5906 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005907 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005908 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005909 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005910
5911 /* Create the "res" field that contains the response channel object. */
5912 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005913 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005914 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005915 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005916
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005917 /* Creates the HTTP object is the current proxy allows http. */
5918 lua_pushstring(L, "http");
5919 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005920 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005921 return 0;
5922 }
5923 else
5924 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005925 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005926
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005927 /* Pop a class sesison metatable and affect it to the userdata. */
5928 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5929 lua_setmetatable(L, -2);
5930
5931 return 1;
5932}
5933
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005934__LJMP static int hlua_txn_deflog(lua_State *L)
5935{
5936 const char *msg;
5937 struct hlua_txn *htxn;
5938
5939 MAY_LJMP(check_args(L, 2, "deflog"));
5940 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5941 msg = MAY_LJMP(luaL_checkstring(L, 2));
5942
5943 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5944 return 0;
5945}
5946
5947__LJMP static int hlua_txn_log(lua_State *L)
5948{
5949 int level;
5950 const char *msg;
5951 struct hlua_txn *htxn;
5952
5953 MAY_LJMP(check_args(L, 3, "log"));
5954 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5955 level = MAY_LJMP(luaL_checkinteger(L, 2));
5956 msg = MAY_LJMP(luaL_checkstring(L, 3));
5957
5958 if (level < 0 || level >= NB_LOG_LEVELS)
5959 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5960
5961 hlua_sendlog(htxn->s->be, level, msg);
5962 return 0;
5963}
5964
5965__LJMP static int hlua_txn_log_debug(lua_State *L)
5966{
5967 const char *msg;
5968 struct hlua_txn *htxn;
5969
5970 MAY_LJMP(check_args(L, 2, "Debug"));
5971 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5972 msg = MAY_LJMP(luaL_checkstring(L, 2));
5973 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5974 return 0;
5975}
5976
5977__LJMP static int hlua_txn_log_info(lua_State *L)
5978{
5979 const char *msg;
5980 struct hlua_txn *htxn;
5981
5982 MAY_LJMP(check_args(L, 2, "Info"));
5983 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5984 msg = MAY_LJMP(luaL_checkstring(L, 2));
5985 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5986 return 0;
5987}
5988
5989__LJMP static int hlua_txn_log_warning(lua_State *L)
5990{
5991 const char *msg;
5992 struct hlua_txn *htxn;
5993
5994 MAY_LJMP(check_args(L, 2, "Warning"));
5995 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5996 msg = MAY_LJMP(luaL_checkstring(L, 2));
5997 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5998 return 0;
5999}
6000
6001__LJMP static int hlua_txn_log_alert(lua_State *L)
6002{
6003 const char *msg;
6004 struct hlua_txn *htxn;
6005
6006 MAY_LJMP(check_args(L, 2, "Alert"));
6007 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6008 msg = MAY_LJMP(luaL_checkstring(L, 2));
6009 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
6010 return 0;
6011}
6012
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006013__LJMP static int hlua_txn_set_loglevel(lua_State *L)
6014{
6015 struct hlua_txn *htxn;
6016 int ll;
6017
6018 MAY_LJMP(check_args(L, 2, "set_loglevel"));
6019 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6020 ll = MAY_LJMP(luaL_checkinteger(L, 2));
6021
6022 if (ll < 0 || ll > 7)
6023 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
6024
6025 htxn->s->logs.level = ll;
6026 return 0;
6027}
6028
6029__LJMP static int hlua_txn_set_tos(lua_State *L)
6030{
6031 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006032 int tos;
6033
6034 MAY_LJMP(check_args(L, 2, "set_tos"));
6035 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6036 tos = MAY_LJMP(luaL_checkinteger(L, 2));
6037
Willy Tarreau1a18b542018-12-11 16:37:42 +01006038 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006039 return 0;
6040}
6041
6042__LJMP static int hlua_txn_set_mark(lua_State *L)
6043{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006044 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006045 int mark;
6046
6047 MAY_LJMP(check_args(L, 2, "set_mark"));
6048 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6049 mark = MAY_LJMP(luaL_checkinteger(L, 2));
6050
Lukas Tribusb59291a2019-08-11 18:03:45 +02006051 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006052 return 0;
6053}
6054
Patrick Hemmer268a7072018-05-11 12:52:31 -04006055__LJMP static int hlua_txn_set_priority_class(lua_State *L)
6056{
6057 struct hlua_txn *htxn;
6058
6059 MAY_LJMP(check_args(L, 2, "set_priority_class"));
6060 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6061 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
6062 return 0;
6063}
6064
6065__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
6066{
6067 struct hlua_txn *htxn;
6068
6069 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
6070 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6071 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
6072 return 0;
6073}
6074
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006075/* This function is an Lua binding that send pending data
6076 * to the client, and close the stream interface.
6077 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006078__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006079{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006080 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006081 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01006082 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006083
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006084 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006085 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006086 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006087
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006088 /* If the flags NOTERM is set, we cannot terminate the http
6089 * session, so we just end the execution of the current
6090 * lua code.
6091 */
6092 if (htxn->flags & HLUA_TXN_NOTERM) {
6093 WILL_LJMP(hlua_done(L));
6094 return 0;
6095 }
6096
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006097 ic = &htxn->s->req;
6098 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006099
Christopher Faulet72c69272019-07-26 16:40:24 +02006100 if (IS_HTX_STRM(htxn->s)) {
6101 htxn->s->txn->status = 0;
6102 http_reply_and_close(htxn->s, 0, NULL);
6103 ic->analysers &= AN_REQ_FLT_END;
6104 oc->analysers &= AN_RES_FLT_END;
6105 }
Christopher Fauletb58fb792019-07-16 10:52:40 +02006106 else {
6107 if (htxn->s->txn) {
6108 /* HTTP mode, let's stay in sync with the stream */
6109 b_del(&ic->buf, htxn->s->txn->req.sov);
6110 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
6111 htxn->s->txn->req.sov = 0;
6112
6113 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
6114 oc->analysers = AN_RES_HTTP_XFER_BODY;
6115 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
6116 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
Willy Tarreau630ef452015-08-28 10:06:15 +02006117
Willy Tarreau630ef452015-08-28 10:06:15 +02006118 /* Note that if we want to support keep-alive, we need
6119 * to bypass the close/shutr_now calls below, but that
6120 * may only be done if the HTTP request was already
6121 * processed and the connection header is known (ie
6122 * not during TCP rules).
6123 */
Christopher Fauletb58fb792019-07-16 10:52:40 +02006124 }
Willy Tarreau630ef452015-08-28 10:06:15 +02006125
Christopher Fauletb58fb792019-07-16 10:52:40 +02006126 channel_auto_read(ic);
6127 channel_abort(ic);
6128 channel_auto_close(ic);
6129 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006130
Christopher Fauletb58fb792019-07-16 10:52:40 +02006131 oc->wex = tick_add_ifset(now_ms, oc->wto);
6132 channel_auto_read(oc);
6133 channel_auto_close(oc);
6134 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006135
Christopher Fauletb58fb792019-07-16 10:52:40 +02006136 ic->analysers = 0;
6137 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006138
Christopher Faulet72c69272019-07-26 16:40:24 +02006139 if (!(htxn->s->flags & SF_ERR_MASK)) // this is not really an error but it is
6140 htxn->s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
6141
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006142 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006143 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006144 return 0;
6145}
6146
6147__LJMP static int hlua_log(lua_State *L)
6148{
6149 int level;
6150 const char *msg;
6151
6152 MAY_LJMP(check_args(L, 2, "log"));
6153 level = MAY_LJMP(luaL_checkinteger(L, 1));
6154 msg = MAY_LJMP(luaL_checkstring(L, 2));
6155
6156 if (level < 0 || level >= NB_LOG_LEVELS)
6157 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6158
6159 hlua_sendlog(NULL, level, msg);
6160 return 0;
6161}
6162
6163__LJMP static int hlua_log_debug(lua_State *L)
6164{
6165 const char *msg;
6166
6167 MAY_LJMP(check_args(L, 1, "debug"));
6168 msg = MAY_LJMP(luaL_checkstring(L, 1));
6169 hlua_sendlog(NULL, LOG_DEBUG, msg);
6170 return 0;
6171}
6172
6173__LJMP static int hlua_log_info(lua_State *L)
6174{
6175 const char *msg;
6176
6177 MAY_LJMP(check_args(L, 1, "info"));
6178 msg = MAY_LJMP(luaL_checkstring(L, 1));
6179 hlua_sendlog(NULL, LOG_INFO, msg);
6180 return 0;
6181}
6182
6183__LJMP static int hlua_log_warning(lua_State *L)
6184{
6185 const char *msg;
6186
6187 MAY_LJMP(check_args(L, 1, "warning"));
6188 msg = MAY_LJMP(luaL_checkstring(L, 1));
6189 hlua_sendlog(NULL, LOG_WARNING, msg);
6190 return 0;
6191}
6192
6193__LJMP static int hlua_log_alert(lua_State *L)
6194{
6195 const char *msg;
6196
6197 MAY_LJMP(check_args(L, 1, "alert"));
6198 msg = MAY_LJMP(luaL_checkstring(L, 1));
6199 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006200 return 0;
6201}
6202
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006203__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006204{
6205 int wakeup_ms = lua_tointeger(L, -1);
6206 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006207 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006208 return 0;
6209}
6210
6211__LJMP static int hlua_sleep(lua_State *L)
6212{
6213 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006214 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006215
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006216 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006217
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006218 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006219 wakeup_ms = tick_add(now_ms, delay);
6220 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006221
Willy Tarreau9635e032018-10-16 17:52:55 +02006222 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006223 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006224}
6225
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006226__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006227{
6228 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006229 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006230
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006231 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006232
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006233 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006234 wakeup_ms = tick_add(now_ms, delay);
6235 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006236
Willy Tarreau9635e032018-10-16 17:52:55 +02006237 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006238 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006239}
6240
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006241/* This functionis an LUA binding. it permits to give back
6242 * the hand at the HAProxy scheduler. It is used when the
6243 * LUA processing consumes a lot of time.
6244 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006245__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006246{
6247 return 0;
6248}
6249
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006250__LJMP static int hlua_yield(lua_State *L)
6251{
Willy Tarreau9635e032018-10-16 17:52:55 +02006252 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006253 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006254}
6255
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006256/* This function change the nice of the currently executed
6257 * task. It is used set low or high priority at the current
6258 * task.
6259 */
Willy Tarreau59551662015-03-10 14:23:13 +01006260__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006261{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006262 struct hlua *hlua;
6263 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006264
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006265 MAY_LJMP(check_args(L, 1, "set_nice"));
6266 hlua = hlua_gethlua(L);
6267 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006268
6269 /* If he task is not set, I'm in a start mode. */
6270 if (!hlua || !hlua->task)
6271 return 0;
6272
6273 if (nice < -1024)
6274 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006275 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006276 nice = 1024;
6277
6278 hlua->task->nice = nice;
6279 return 0;
6280}
6281
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006282/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006283 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6284 * return an E_AGAIN signal, the emmiter of this signal must set a
6285 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006286 *
6287 * Task wrapper are longjmp safe because the only one Lua code
6288 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006289 */
Willy Tarreau83a5ff42019-08-21 14:14:50 +02006290struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006291{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006292 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006293 enum hlua_exec status;
6294
Christopher Faulet5bc99722018-04-25 10:34:45 +02006295 if (task->thread_mask == MAX_THREADS_MASK)
6296 task_set_affinity(task, tid_bit);
6297
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006298 /* If it is the first call to the task, we must initialize the
6299 * execution timeouts.
6300 */
6301 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006302 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006303
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006304 /* Execute the Lua code. */
6305 status = hlua_ctx_resume(hlua, 1);
6306
6307 switch (status) {
6308 /* finished or yield */
6309 case HLUA_E_OK:
6310 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006311 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006312 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006313 break;
6314
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006315 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006316 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006317 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006318 break;
6319
6320 /* finished with error. */
6321 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006322 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006323 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006324 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006325 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006326 break;
6327
6328 case HLUA_E_ERR:
6329 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006330 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006331 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006332 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006333 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006334 break;
6335 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006336 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006337}
6338
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006339/* This function is an LUA binding that register LUA function to be
6340 * executed after the HAProxy configuration parsing and before the
6341 * HAProxy scheduler starts. This function expect only one LUA
6342 * argument that is a function. This function returns nothing, but
6343 * throws if an error is encountered.
6344 */
6345__LJMP static int hlua_register_init(lua_State *L)
6346{
6347 struct hlua_init_function *init;
6348 int ref;
6349
6350 MAY_LJMP(check_args(L, 1, "register_init"));
6351
6352 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6353
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006354 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006355 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006356 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006357
6358 init->function_ref = ref;
6359 LIST_ADDQ(&hlua_init_functions, &init->l);
6360 return 0;
6361}
6362
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006363/* This functio is an LUA binding. It permits to register a task
6364 * executed in parallel of the main HAroxy activity. The task is
6365 * created and it is set in the HAProxy scheduler. It can be called
6366 * from the "init" section, "post init" or during the runtime.
6367 *
6368 * Lua prototype:
6369 *
6370 * <none> core.register_task(<function>)
6371 */
6372static int hlua_register_task(lua_State *L)
6373{
6374 struct hlua *hlua;
6375 struct task *task;
6376 int ref;
6377
6378 MAY_LJMP(check_args(L, 1, "register_task"));
6379
6380 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6381
Willy Tarreaubafbe012017-11-24 17:34:44 +01006382 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006383 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006384 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Christopher Faulet22d1d012021-03-24 15:03:01 +01006385 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006386
Emeric Brunc60def82017-09-27 14:59:38 +02006387 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006388 if (!task)
6389 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6390
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006391 task->context = hlua;
6392 task->process = hlua_process_task;
6393
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006394 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006395 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006396
6397 /* Restore the function in the stack. */
6398 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6399 hlua->nargs = 0;
6400
6401 /* Schedule task. */
6402 task_schedule(task, now_ms);
6403
6404 return 0;
6405}
6406
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006407/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6408 * doesn't allow "yield" functions because the HAProxy engine cannot
6409 * resume converters.
6410 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006411static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006412{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006413 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006414 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006415 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006416
Willy Tarreaube508f12016-03-10 11:47:01 +01006417 if (!stream)
6418 return 0;
6419
Willy Tarreau87b09662015-04-03 00:22:06 +02006420 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006421 * Lua context can be not initialized. This behavior
6422 * permits to save performances because a systematic
6423 * Lua initialization cause 5% performances loss.
6424 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006425 if (!stream->hlua) {
Christopher Faulet22d1d012021-03-24 15:03:01 +01006426 struct hlua *hlua;
6427
6428 hlua = pool_alloc(pool_head_hlua);
6429 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006430 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6431 return 0;
6432 }
Christopher Faulet22d1d012021-03-24 15:03:01 +01006433 HLUA_INIT(hlua);
6434 stream->hlua = hlua;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006435 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006436 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6437 return 0;
6438 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006439 }
6440
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006441 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006442 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006443
6444 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006445 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6446 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6447 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006448 else
6449 error = "critical error";
6450 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006451 return 0;
6452 }
6453
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006454 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006455 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006456 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006457 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006458 return 0;
6459 }
6460
6461 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006462 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006463
6464 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006465 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006466 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006467 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006468 return 0;
6469 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006470 hlua_smp2lua(stream->hlua->T, smp);
6471 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006472
6473 /* push keywords in the stack. */
6474 if (arg_p) {
6475 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006476 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006477 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006478 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006479 return 0;
6480 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006481 hlua_arg2lua(stream->hlua->T, arg_p);
6482 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006483 }
6484 }
6485
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006486 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006487 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006488
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006489 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006490 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006491 }
6492
6493 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006494 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006495 /* finished. */
6496 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006497 /* If the stack is empty, the function fails. */
6498 if (lua_gettop(stream->hlua->T) <= 0)
6499 return 0;
6500
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006501 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006502 hlua_lua2smp(stream->hlua->T, -1, smp);
6503 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006504 return 1;
6505
6506 /* yield. */
6507 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006508 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006509 return 0;
6510
6511 /* finished with error. */
6512 case HLUA_E_ERRMSG:
6513 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006514 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006515 fcn->name, lua_tostring(stream->hlua->T, -1));
6516 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006517 return 0;
6518
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006519 case HLUA_E_ETMOUT:
6520 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6521 return 0;
6522
6523 case HLUA_E_NOMEM:
6524 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6525 return 0;
6526
6527 case HLUA_E_YIELD:
6528 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6529 return 0;
6530
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006531 case HLUA_E_ERR:
6532 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006533 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006534
6535 default:
6536 return 0;
6537 }
6538}
6539
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006540/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6541 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006542 * resume sample-fetches. This function will be called by the sample
6543 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006544 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006545static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6546 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006547{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006548 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006549 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006550 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006551 const struct buffer msg = { };
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006552 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006553
Willy Tarreaube508f12016-03-10 11:47:01 +01006554 if (!stream)
6555 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006556
Willy Tarreau87b09662015-04-03 00:22:06 +02006557 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006558 * Lua context can be not initialized. This behavior
6559 * permits to save performances because a systematic
6560 * Lua initialization cause 5% performances loss.
6561 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006562 if (!stream->hlua) {
Christopher Faulet22d1d012021-03-24 15:03:01 +01006563 struct hlua *hlua;
6564
6565 hlua = pool_alloc(pool_head_hlua);
6566 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006567 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6568 return 0;
6569 }
Christopher Faulet22d1d012021-03-24 15:03:01 +01006570 hlua->T = NULL;
6571 stream->hlua = hlua;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006572 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006573 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6574 return 0;
6575 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006576 }
6577
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006578 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006579
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006580 if (stream->be->mode == PR_MODE_HTTP) {
6581 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ)
6582 hflags |= ((stream->txn->req.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6583 else
6584 hflags |= ((stream->txn->rsp.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6585 }
6586
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006587 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006588 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006589
6590 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006591 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6592 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6593 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006594 else
6595 error = "critical error";
6596 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006597 return 0;
6598 }
6599
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006600 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006601 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006602 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006603 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006604 return 0;
6605 }
6606
6607 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006608 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006609
6610 /* push arguments in the stack. */
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006611 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006612 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006613 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006614 return 0;
6615 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006616 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006617
6618 /* push keywords in the stack. */
6619 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6620 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006621 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006622 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006623 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006624 return 0;
6625 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006626 hlua_arg2lua(stream->hlua->T, arg_p);
6627 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006628 }
6629
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006630 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006631 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006632
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006633 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006634 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006635 }
6636
6637 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006638 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006639 /* finished. */
6640 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006641 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006642 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006643 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006644 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006645 /* If the stack is empty, the function fails. */
6646 if (lua_gettop(stream->hlua->T) <= 0)
6647 return 0;
6648
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006649 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006650 hlua_lua2smp(stream->hlua->T, -1, smp);
6651 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006652
6653 /* Set the end of execution flag. */
6654 smp->flags &= ~SMP_F_MAY_CHANGE;
6655 return 1;
6656
6657 /* yield. */
6658 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006659 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006660 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006661 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006662 return 0;
6663
6664 /* finished with error. */
6665 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006666 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006667 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006668 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006669 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006670 fcn->name, lua_tostring(stream->hlua->T, -1));
6671 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006672 return 0;
6673
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006674 case HLUA_E_ETMOUT:
6675 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006676 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006677 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6678 return 0;
6679
6680 case HLUA_E_NOMEM:
6681 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006682 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006683 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6684 return 0;
6685
6686 case HLUA_E_YIELD:
6687 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006688 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006689 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6690 return 0;
6691
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006692 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006693 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006694 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006695 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006696 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006697
6698 default:
6699 return 0;
6700 }
6701}
6702
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006703/* This function is an LUA binding used for registering
6704 * "sample-conv" functions. It expects a converter name used
6705 * in the haproxy configuration file, and an LUA function.
6706 */
6707__LJMP static int hlua_register_converters(lua_State *L)
6708{
6709 struct sample_conv_kw_list *sck;
6710 const char *name;
6711 int ref;
6712 int len;
6713 struct hlua_function *fcn;
Thierry Fourniera9230f82020-11-28 20:41:07 +01006714 struct sample_conv *sc;
6715 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006716
6717 MAY_LJMP(check_args(L, 2, "register_converters"));
6718
6719 /* First argument : converter name. */
6720 name = MAY_LJMP(luaL_checkstring(L, 1));
6721
6722 /* Second argument : lua function. */
6723 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6724
Thierry Fourniera9230f82020-11-28 20:41:07 +01006725 /* Check if the converter is already registered */
6726 trash = get_trash_chunk();
6727 chunk_printf(trash, "lua.%s", name);
6728 sc = find_sample_conv(trash->area, trash->data);
6729 if (sc != NULL) {
6730 ha_warning("Trying to register converter 'lua.%s' more than once. "
6731 "This will become a hard error in version 2.5.\n", name);
6732 }
6733
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006734 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006735 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006736 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006737 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006738 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006739 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006740 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006741
6742 /* Fill fcn. */
6743 fcn->name = strdup(name);
6744 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006745 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006746 fcn->function_ref = ref;
6747
6748 /* List head */
6749 sck->list.n = sck->list.p = NULL;
6750
6751 /* converter keyword. */
6752 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006753 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006754 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006755 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006756
6757 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6758 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006759 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 +01006760 sck->kw[0].val_args = NULL;
6761 sck->kw[0].in_type = SMP_T_STR;
6762 sck->kw[0].out_type = SMP_T_STR;
6763 sck->kw[0].private = fcn;
6764
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006765 /* Register this new converter */
6766 sample_register_convs(sck);
6767
6768 return 0;
6769}
6770
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006771/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006772 * "sample-fetch" functions. It expects a converter name used
6773 * in the haproxy configuration file, and an LUA function.
6774 */
6775__LJMP static int hlua_register_fetches(lua_State *L)
6776{
6777 const char *name;
6778 int ref;
6779 int len;
6780 struct sample_fetch_kw_list *sfk;
6781 struct hlua_function *fcn;
Thierry Fourniera9230f82020-11-28 20:41:07 +01006782 struct sample_fetch *sf;
6783 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006784
6785 MAY_LJMP(check_args(L, 2, "register_fetches"));
6786
6787 /* First argument : sample-fetch name. */
6788 name = MAY_LJMP(luaL_checkstring(L, 1));
6789
6790 /* Second argument : lua function. */
6791 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6792
Thierry Fourniera9230f82020-11-28 20:41:07 +01006793 /* Check if the sample-fetch is already registered */
6794 trash = get_trash_chunk();
6795 chunk_printf(trash, "lua.%s", name);
6796 sf = find_sample_fetch(trash->area, trash->data);
6797 if (sf != NULL) {
6798 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
6799 "This will become a hard error in version 2.5.\n", name);
6800 }
6801
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006802 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006803 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006804 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006805 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006806 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006807 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006808 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006809
6810 /* Fill fcn. */
6811 fcn->name = strdup(name);
6812 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006813 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006814 fcn->function_ref = ref;
6815
6816 /* List head */
6817 sfk->list.n = sfk->list.p = NULL;
6818
6819 /* sample-fetch keyword. */
6820 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006821 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006822 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006823 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006824
6825 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6826 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006827 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 +01006828 sfk->kw[0].val_args = NULL;
6829 sfk->kw[0].out_type = SMP_T_STR;
6830 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6831 sfk->kw[0].val = 0;
6832 sfk->kw[0].private = fcn;
6833
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006834 /* Register this new fetch. */
6835 sample_register_fetches(sfk);
6836
6837 return 0;
6838}
6839
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006840/* This function is a wrapper to execute each LUA function declared
6841 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006842 * return ACT_RET_CONT if the processing is finished (with or without
6843 * error) and return ACT_RET_YIELD if the function must be called again
6844 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006845 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006846static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006847 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006848{
6849 char **arg;
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006850 unsigned int hflags = 0;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006851 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006852 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006853 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006854
6855 switch (rule->from) {
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006856 case ACT_F_TCP_REQ_CNT: ; dir = SMP_OPT_DIR_REQ; break;
6857 case ACT_F_TCP_RES_CNT: ; dir = SMP_OPT_DIR_RES; break;
6858 case ACT_F_HTTP_REQ: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_REQ; break;
6859 case ACT_F_HTTP_RES: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006860 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006861 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006862 return ACT_RET_CONT;
6863 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006864
Willy Tarreau87b09662015-04-03 00:22:06 +02006865 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006866 * Lua context can be not initialized. This behavior
6867 * permits to save performances because a systematic
6868 * Lua initialization cause 5% performances loss.
6869 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006870 if (!s->hlua) {
Christopher Faulet22d1d012021-03-24 15:03:01 +01006871 struct hlua *hlua;
6872
6873 hlua = pool_alloc(pool_head_hlua);
6874 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006875 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6876 rule->arg.hlua_rule->fcn.name);
6877 return ACT_RET_CONT;
6878 }
Christopher Faulet22d1d012021-03-24 15:03:01 +01006879 HLUA_INIT(hlua);
6880 s->hlua = hlua;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006881 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006882 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6883 rule->arg.hlua_rule->fcn.name);
6884 return ACT_RET_CONT;
6885 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006886 }
6887
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006888 consistency_set(s, dir, &s->hlua->cons);
6889
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006890 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006891 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006892
6893 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006894 if (!SET_SAFE_LJMP(s->hlua->T)) {
6895 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6896 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006897 else
6898 error = "critical error";
6899 SEND_ERR(px, "Lua function '%s': %s.\n",
6900 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006901 return ACT_RET_CONT;
6902 }
6903
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006904 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006905 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006906 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006907 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006908 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006909 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006910 }
6911
6912 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006913 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006914
Willy Tarreau87b09662015-04-03 00:22:06 +02006915 /* Create and and push object stream in the stack. */
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006916 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006917 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006918 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006919 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006920 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006921 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006922 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006923
6924 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006925 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006926 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006927 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006928 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006929 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006930 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006931 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006932 lua_pushstring(s->hlua->T, *arg);
6933 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006934 }
6935
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006936 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006937 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006938
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006939 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006940 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006941 }
6942
Christopher Faulet719ddc82020-06-02 18:46:07 +02006943 /* Always reset the analyse expiration timeout for the corresponding
6944 * channel in case the lua script yield, to be sure to not keep an
6945 * expired timeout.
6946 */
6947 if (dir == SMP_OPT_DIR_REQ)
6948 s->req.analyse_exp = TICK_ETERNITY;
6949 else
6950 s->res.analyse_exp = TICK_ETERNITY;
6951
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006952 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006953 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006954 /* finished. */
6955 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006956 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006957 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006958 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006959 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006960 if (s->hlua->flags & HLUA_STOP)
Christopher Faulet4629d082019-07-04 11:27:15 +02006961 return ACT_RET_DONE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006962 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006963
6964 /* yield. */
6965 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006966 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006967 if (s->hlua->wake_time != TICK_ETERNITY) {
Christopher Fauletea0b0e22019-08-14 23:19:45 +02006968 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006969 s->req.analyse_exp = s->hlua->wake_time;
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006970 else
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006971 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006972 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006973 /* Some actions can be wake up when a "write" event
6974 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006975 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006976 */
Christopher Fauletb22f6502019-07-26 14:54:52 +02006977 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006978 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006979 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006980 s->req.flags |= CF_WAKE_WRITE;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006981 /* We can quit the function without consistency check
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006982 * because HAProxy is not able to manipulate data, it
6983 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006984 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006985
6986 /* finished with error. */
6987 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006988 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006989 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006990 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006991 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006992 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006993 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006994 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6995 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006996 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006997
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006998 case HLUA_E_ETMOUT:
6999 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01007000 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007001 return ACT_RET_ERR;
7002 }
7003 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
7004 return 0;
7005
7006 case HLUA_E_NOMEM:
7007 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01007008 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007009 return ACT_RET_ERR;
7010 }
7011 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
7012 return 0;
7013
7014 case HLUA_E_YIELD:
7015 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01007016 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007017 return ACT_RET_ERR;
7018 }
7019 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
7020 rule->arg.hlua_rule->fcn.name);
7021 return 0;
7022
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007023 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01007024 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01007025 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02007026 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01007027 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007028 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007029 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007030 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007031
7032 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02007033 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007034 }
7035}
7036
Olivier Houchard9f6af332018-05-25 14:04:04 +02007037struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007038{
Olivier Houchard9f6af332018-05-25 14:04:04 +02007039 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007040
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007041 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02007042 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02007043 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007044}
7045
7046static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7047{
7048 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007049 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007050 struct task *task;
7051 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007052 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007053
Willy Tarreaubafbe012017-11-24 17:34:44 +01007054 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007055 if (!hlua) {
7056 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
7057 ctx->rule->arg.hlua_rule->fcn.name);
7058 return 0;
7059 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007060 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007061 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007062 ctx->ctx.hlua_apptcp.flags = 0;
7063
7064 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007065 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007066 if (!task) {
7067 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
7068 ctx->rule->arg.hlua_rule->fcn.name);
7069 return 0;
7070 }
7071 task->nice = 0;
7072 task->context = ctx;
7073 task->process = hlua_applet_wakeup;
7074 ctx->ctx.hlua_apptcp.task = task;
7075
7076 /* In the execution wrappers linked with a stream, the
7077 * Lua context can be not initialized. This behavior
7078 * permits to save performances because a systematic
7079 * Lua initialization cause 5% performances loss.
7080 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007081 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007082 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
7083 ctx->rule->arg.hlua_rule->fcn.name);
7084 return 0;
7085 }
7086
7087 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007088 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007089
7090 /* The following Lua calls can fail. */
7091 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007092 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7093 error = lua_tostring(hlua->T, -1);
7094 else
7095 error = "critical error";
7096 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7097 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007098 return 0;
7099 }
7100
7101 /* Check stack available size. */
7102 if (!lua_checkstack(hlua->T, 1)) {
7103 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7104 ctx->rule->arg.hlua_rule->fcn.name);
7105 RESET_SAFE_LJMP(hlua->T);
7106 return 0;
7107 }
7108
7109 /* Restore the function in the stack. */
7110 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7111
7112 /* Create and and push object stream in the stack. */
7113 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7114 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7115 ctx->rule->arg.hlua_rule->fcn.name);
7116 RESET_SAFE_LJMP(hlua->T);
7117 return 0;
7118 }
7119 hlua->nargs = 1;
7120
7121 /* push keywords in the stack. */
7122 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7123 if (!lua_checkstack(hlua->T, 1)) {
7124 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7125 ctx->rule->arg.hlua_rule->fcn.name);
7126 RESET_SAFE_LJMP(hlua->T);
7127 return 0;
7128 }
7129 lua_pushstring(hlua->T, *arg);
7130 hlua->nargs++;
7131 }
7132
7133 RESET_SAFE_LJMP(hlua->T);
7134
7135 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007136 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007137 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007138
7139 return 1;
7140}
7141
Willy Tarreau83a5ff42019-08-21 14:14:50 +02007142void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007143{
7144 struct stream_interface *si = ctx->owner;
7145 struct stream *strm = si_strm(si);
7146 struct channel *res = si_ic(si);
7147 struct act_rule *rule = ctx->rule;
7148 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007149 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007150
7151 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007152 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7153 /* eat the whole request */
7154 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007155 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007156 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007157
7158 /* If the stream is disconnect or closed, ldo nothing. */
7159 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7160 return;
7161
7162 /* Execute the function. */
7163 switch (hlua_ctx_resume(hlua, 1)) {
7164 /* finished. */
7165 case HLUA_E_OK:
7166 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7167
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007168 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007169 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007170 res->flags |= CF_READ_NULL;
7171 si_shutr(si);
7172 return;
7173
7174 /* yield. */
7175 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007176 if (hlua->wake_time != TICK_ETERNITY)
7177 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007178 return;
7179
7180 /* finished with error. */
7181 case HLUA_E_ERRMSG:
7182 /* Display log. */
7183 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7184 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7185 lua_pop(hlua->T, 1);
7186 goto error;
7187
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007188 case HLUA_E_ETMOUT:
7189 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
7190 rule->arg.hlua_rule->fcn.name);
7191 goto error;
7192
7193 case HLUA_E_NOMEM:
7194 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
7195 rule->arg.hlua_rule->fcn.name);
7196 goto error;
7197
7198 case HLUA_E_YIELD: /* unexpected */
7199 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
7200 rule->arg.hlua_rule->fcn.name);
7201 goto error;
7202
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007203 case HLUA_E_ERR:
7204 /* Display log. */
7205 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
7206 rule->arg.hlua_rule->fcn.name);
7207 goto error;
7208
7209 default:
7210 goto error;
7211 }
7212
7213error:
7214
7215 /* For all other cases, just close the stream. */
7216 si_shutw(si);
7217 si_shutr(si);
7218 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7219}
7220
7221static void hlua_applet_tcp_release(struct appctx *ctx)
7222{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007223 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007224 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007225 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007226 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007227}
7228
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007229/* The function returns 1 if the initialisation is complete, 0 if
7230 * an errors occurs and -1 if more data are required for initializing
7231 * the applet.
7232 */
7233static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7234{
7235 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007236 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007237 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007238 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007239 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007240 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007241
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007242 txn = strm->txn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007243
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007244 /* We want two things in HTTP mode :
7245 * - enforce server-close mode if we were in keep-alive, so that the
7246 * applet is released after each response ;
7247 * - enable request body transfer to the applet in order to resync
7248 * with the response body.
7249 */
7250 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
7251 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007252
Willy Tarreaubafbe012017-11-24 17:34:44 +01007253 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007254 if (!hlua) {
7255 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7256 ctx->rule->arg.hlua_rule->fcn.name);
7257 return 0;
7258 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007259 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007260 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007261 ctx->ctx.hlua_apphttp.left_bytes = -1;
7262 ctx->ctx.hlua_apphttp.flags = 0;
7263
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007264 if (txn->req.flags & HTTP_MSGF_VER_11)
7265 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7266
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007267 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007268 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007269 if (!task) {
7270 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7271 ctx->rule->arg.hlua_rule->fcn.name);
7272 return 0;
7273 }
7274 task->nice = 0;
7275 task->context = ctx;
7276 task->process = hlua_applet_wakeup;
7277 ctx->ctx.hlua_apphttp.task = task;
7278
7279 /* In the execution wrappers linked with a stream, the
7280 * Lua context can be not initialized. This behavior
7281 * permits to save performances because a systematic
7282 * Lua initialization cause 5% performances loss.
7283 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007284 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007285 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
7286 ctx->rule->arg.hlua_rule->fcn.name);
7287 return 0;
7288 }
7289
7290 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007291 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007292
7293 /* The following Lua calls can fail. */
7294 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007295 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7296 error = lua_tostring(hlua->T, -1);
7297 else
7298 error = "critical error";
7299 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7300 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007301 return 0;
7302 }
7303
7304 /* Check stack available size. */
7305 if (!lua_checkstack(hlua->T, 1)) {
7306 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7307 ctx->rule->arg.hlua_rule->fcn.name);
7308 RESET_SAFE_LJMP(hlua->T);
7309 return 0;
7310 }
7311
7312 /* Restore the function in the stack. */
7313 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7314
7315 /* Create and and push object stream in the stack. */
7316 if (!hlua_applet_http_new(hlua->T, ctx)) {
7317 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7318 ctx->rule->arg.hlua_rule->fcn.name);
7319 RESET_SAFE_LJMP(hlua->T);
7320 return 0;
7321 }
7322 hlua->nargs = 1;
7323
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007324 /* push keywords in the stack. */
7325 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7326 if (!lua_checkstack(hlua->T, 1)) {
7327 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7328 ctx->rule->arg.hlua_rule->fcn.name);
7329 RESET_SAFE_LJMP(hlua->T);
7330 return 0;
7331 }
7332 lua_pushstring(hlua->T, *arg);
7333 hlua->nargs++;
7334 }
7335
7336 RESET_SAFE_LJMP(hlua->T);
7337
7338 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007339 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007340
7341 return 1;
7342}
7343
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007344static void hlua_applet_htx_fct(struct appctx *ctx)
7345{
7346 struct stream_interface *si = ctx->owner;
7347 struct stream *strm = si_strm(si);
7348 struct channel *req = si_oc(si);
7349 struct channel *res = si_ic(si);
7350 struct act_rule *rule = ctx->rule;
7351 struct proxy *px = strm->be;
7352 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7353 struct htx *req_htx, *res_htx;
7354
7355 res_htx = htx_from_buf(&res->buf);
7356
7357 /* If the stream is disconnect or closed, ldo nothing. */
7358 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7359 goto out;
7360
7361 /* Check if the input buffer is avalaible. */
7362 if (!b_size(&res->buf)) {
7363 si_rx_room_blk(si);
7364 goto out;
7365 }
7366 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007367 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007368 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7369
7370 /* Set the currently running flag. */
7371 if (!HLUA_IS_RUNNING(hlua) &&
7372 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7373 struct htx_blk *blk;
7374 size_t count = co_data(req);
7375
7376 if (!count) {
7377 si_cant_get(si);
7378 goto out;
7379 }
7380
7381 /* We need to flush the request header. This left the body for
7382 * the Lua.
7383 */
7384 req_htx = htx_from_buf(&req->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02007385 blk = htx_get_first_blk(req_htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007386 while (count && blk) {
7387 enum htx_blk_type type = htx_get_blk_type(blk);
7388 uint32_t sz = htx_get_blksz(blk);
7389
7390 if (sz > count) {
7391 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007392 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007393 goto out;
7394 }
7395
7396 count -= sz;
7397 co_set_data(req, co_data(req) - sz);
7398 blk = htx_remove_blk(req_htx, blk);
7399
7400 if (type == HTX_BLK_EOH)
7401 break;
7402 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007403 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007404 }
7405
7406 /* Executes The applet if it is not done. */
7407 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7408
7409 /* Execute the function. */
7410 switch (hlua_ctx_resume(hlua, 1)) {
7411 /* finished. */
7412 case HLUA_E_OK:
7413 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7414 break;
7415
7416 /* yield. */
7417 case HLUA_E_AGAIN:
7418 if (hlua->wake_time != TICK_ETERNITY)
7419 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007420 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007421
7422 /* finished with error. */
7423 case HLUA_E_ERRMSG:
7424 /* Display log. */
7425 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7426 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7427 lua_pop(hlua->T, 1);
7428 goto error;
7429
7430 case HLUA_E_ETMOUT:
7431 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7432 rule->arg.hlua_rule->fcn.name);
7433 goto error;
7434
7435 case HLUA_E_NOMEM:
7436 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7437 rule->arg.hlua_rule->fcn.name);
7438 goto error;
7439
7440 case HLUA_E_YIELD: /* unexpected */
7441 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7442 rule->arg.hlua_rule->fcn.name);
7443 goto error;
7444
7445 case HLUA_E_ERR:
7446 /* Display log. */
7447 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7448 rule->arg.hlua_rule->fcn.name);
7449 goto error;
7450
7451 default:
7452 goto error;
7453 }
7454 }
7455
7456 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007457 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7458 goto done;
7459
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007460 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7461 goto error;
7462
Christopher Faulet54b5e212019-06-04 10:08:28 +02007463 /* Don't add TLR because mux-h1 will take care of it */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007464 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7465 si_rx_room_blk(si);
7466 goto out;
7467 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007468 channel_add_input(res, 1);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007469 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7470 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007471 }
7472
7473 done:
7474 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007475 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007476 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007477 si_shutr(si);
7478 }
7479
7480 /* eat the whole request */
7481 if (co_data(req)) {
7482 req_htx = htx_from_buf(&req->buf);
7483 co_htx_skip(req, req_htx, co_data(req));
7484 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007485 }
7486 }
7487
7488 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007489 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007490 return;
7491
7492 error:
7493
7494 /* If we are in HTTP mode, and we are not send any
7495 * data, return a 500 server error in best effort:
7496 * if there is no room available in the buffer,
7497 * just close the connection.
7498 */
7499 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7500 struct buffer *err = &htx_err_chunks[HTTP_ERR_500];
7501
7502 channel_erase(res);
7503 res->buf.data = b_data(err);
7504 memcpy(res->buf.area, b_head(err), b_data(err));
7505 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007506 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007507 }
7508 if (!(strm->flags & SF_ERR_MASK))
7509 strm->flags |= SF_ERR_RESOURCE;
7510 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7511 goto done;
7512}
7513
Willy Tarreau83a5ff42019-08-21 14:14:50 +02007514void hlua_applet_http_fct(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007515{
7516 struct stream_interface *si = ctx->owner;
7517 struct stream *strm = si_strm(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007518 struct channel *req = si_oc(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007519 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007520 struct act_rule *rule = ctx->rule;
7521 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007522 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02007523 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007524 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02007525 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007526 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007527 int ret;
7528
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007529 if (IS_HTX_STRM(strm))
7530 return hlua_applet_htx_fct(ctx);
7531
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007532 /* If the stream is disconnect or closed, ldo nothing. */
7533 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007534 goto out;
7535
7536 /* Check if the input buffer is avalaible. */
7537 if (!b_size(&res->buf)) {
7538 si_rx_room_blk(si);
7539 goto out;
7540 }
7541 /* check that the output is not closed */
7542 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
7543 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007544
7545 /* Set the currently running flag. */
7546 if (!HLUA_IS_RUNNING(hlua) &&
7547 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007548 /* Store the max amount of bytes that we can read. */
7549 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
7550
7551 /* We need to flush the request header. This left the body
7552 * for the Lua.
7553 */
7554
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007555 /* Read the maximum amount of data available. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007556 ret = co_getblk_nc(req, &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007557 if (ret == -1)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007558 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007559
7560 /* No data available, ask for more data. */
7561 if (ret == 1)
7562 len2 = 0;
7563 if (ret == 0)
7564 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007565 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007566 si_cant_get(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007567 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007568 }
7569
7570 /* skip the requests bytes. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007571 co_skip(req, strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007572 }
7573
7574 /* Executes The applet if it is not done. */
7575 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7576
7577 /* Execute the function. */
7578 switch (hlua_ctx_resume(hlua, 1)) {
7579 /* finished. */
7580 case HLUA_E_OK:
7581 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7582 break;
7583
7584 /* yield. */
7585 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007586 if (hlua->wake_time != TICK_ETERNITY)
7587 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007588 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007589
7590 /* finished with error. */
7591 case HLUA_E_ERRMSG:
7592 /* Display log. */
7593 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7594 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7595 lua_pop(hlua->T, 1);
7596 goto error;
7597
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007598 case HLUA_E_ETMOUT:
7599 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7600 rule->arg.hlua_rule->fcn.name);
7601 goto error;
7602
7603 case HLUA_E_NOMEM:
7604 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7605 rule->arg.hlua_rule->fcn.name);
7606 goto error;
7607
7608 case HLUA_E_YIELD: /* unexpected */
7609 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7610 rule->arg.hlua_rule->fcn.name);
7611 goto error;
7612
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007613 case HLUA_E_ERR:
7614 /* Display log. */
7615 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7616 rule->arg.hlua_rule->fcn.name);
7617 goto error;
7618
7619 default:
7620 goto error;
7621 }
7622 }
7623
7624 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007625 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7626 goto done;
7627
Christopher Fauletcc26b132018-12-18 21:20:57 +01007628 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7629 goto error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007630
7631 /* We must send the final chunk. */
7632 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
7633 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
7634
7635 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007636 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007637
7638 /* critical error. */
7639 if (ret == -2 || ret == -3) {
7640 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
7641 rule->arg.hlua_rule->fcn.name);
7642 goto error;
7643 }
7644
7645 /* no enough space error. */
7646 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01007647 si_rx_room_blk(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007648 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007649 }
7650
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007651 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7652 ctx->ctx.hlua_apphttp.flags |= (APPLET_LAST_CHK|APPLET_RSP_SENT);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007653 }
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007654 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007655
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007656 done:
7657 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7658 if (!(res->flags & CF_SHUTR)) {
7659 res->flags |= CF_READ_NULL;
7660 si_shutr(si);
7661 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007662
7663 /* eat the whole request */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007664 if (co_data(req))
7665 co_skip(req, co_data(req));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007666 }
7667
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007668 out:
7669 return;
7670
7671 error:
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007672
7673 /* If we are in HTTP mode, and we are not send any
7674 * data, return a 500 server error in best effort:
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007675 * if there is no room available in the buffer,
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007676 * just close the connection.
7677 */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007678 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7679 channel_erase(res);
7680 ci_putblk(res, error_500, strlen(error_500));
7681 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007682 if (!(strm->flags & SF_ERR_MASK))
7683 strm->flags |= SF_ERR_RESOURCE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007684 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007685 goto done;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007686}
7687
7688static void hlua_applet_http_release(struct appctx *ctx)
7689{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007690 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007691 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007692 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007693 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007694}
7695
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007696/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7697 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007698 *
7699 * This function can fail with an abort() due to an Lua critical error.
7700 * We are in the configuration parsing process of HAProxy, this abort() is
7701 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007702 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007703static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7704 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007705{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007706 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007707 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007708
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007709 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007710 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007711 if (!rule->arg.hlua_rule) {
7712 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007713 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007714 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007715
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007716 /* Memory for arguments. */
7717 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7718 if (!rule->arg.hlua_rule->args) {
7719 memprintf(err, "out of memory error");
7720 return ACT_RET_PRS_ERR;
7721 }
7722
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007723 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007724 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007725
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007726 /* Expect some arguments */
7727 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007728 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007729 memprintf(err, "expect %d arguments", fcn->nargs);
7730 return ACT_RET_PRS_ERR;
7731 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007732 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007733 if (!rule->arg.hlua_rule->args[i]) {
7734 memprintf(err, "out of memory error");
7735 return ACT_RET_PRS_ERR;
7736 }
7737 (*cur_arg)++;
7738 }
7739 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007740
Thierry FOURNIER42148732015-09-02 17:17:33 +02007741 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007742 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007743 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007744}
7745
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007746static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7747 struct act_rule *rule, char **err)
7748{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007749 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007750
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007751 /* HTTP applets are forbidden in tcp-request rules.
7752 * HTTP applet request requires everything initilized by
7753 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7754 * The applet will be immediately initilized, but its before
7755 * the call of this analyzer.
7756 */
7757 if (rule->from != ACT_F_HTTP_REQ) {
7758 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7759 return ACT_RET_PRS_ERR;
7760 }
7761
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007762 /* Memory for the rule. */
7763 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7764 if (!rule->arg.hlua_rule) {
7765 memprintf(err, "out of memory error");
7766 return ACT_RET_PRS_ERR;
7767 }
7768
7769 /* Reference the Lua function and store the reference. */
7770 rule->arg.hlua_rule->fcn = *fcn;
7771
7772 /* TODO: later accept arguments. */
7773 rule->arg.hlua_rule->args = NULL;
7774
7775 /* Add applet pointer in the rule. */
7776 rule->applet.obj_type = OBJ_TYPE_APPLET;
7777 rule->applet.name = fcn->name;
7778 rule->applet.init = hlua_applet_http_init;
7779 rule->applet.fct = hlua_applet_http_fct;
7780 rule->applet.release = hlua_applet_http_release;
7781 rule->applet.timeout = hlua_timeout_applet;
7782
7783 return ACT_RET_PRS_OK;
7784}
7785
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007786/* This function is an LUA binding used for registering
7787 * "sample-conv" functions. It expects a converter name used
7788 * in the haproxy configuration file, and an LUA function.
7789 */
7790__LJMP static int hlua_register_action(lua_State *L)
7791{
7792 struct action_kw_list *akl;
7793 const char *name;
7794 int ref;
7795 int len;
7796 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007797 int nargs;
Thierry Fourniera9230f82020-11-28 20:41:07 +01007798 struct buffer *trash;
7799 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007800
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007801 /* Initialise the number of expected arguments at 0. */
7802 nargs = 0;
7803
7804 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7805 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007806
7807 /* First argument : converter name. */
7808 name = MAY_LJMP(luaL_checkstring(L, 1));
7809
7810 /* Second argument : environment. */
7811 if (lua_type(L, 2) != LUA_TTABLE)
7812 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7813
7814 /* Third argument : lua function. */
7815 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7816
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007817 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007818 if (lua_gettop(L) >= 4)
7819 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7820
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007821 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007822 lua_pushnil(L);
7823 while (lua_next(L, 2) != 0) {
7824 if (lua_type(L, -1) != LUA_TSTRING)
7825 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7826
Thierry Fourniera9230f82020-11-28 20:41:07 +01007827 /* Check if action exists */
7828 trash = get_trash_chunk();
7829 chunk_printf(trash, "lua.%s", name);
7830 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
7831 akw = tcp_req_cont_action(trash->area);
7832 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
7833 akw = tcp_res_cont_action(trash->area);
7834 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
7835 akw = action_http_req_custom(trash->area);
7836 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
7837 akw = action_http_res_custom(trash->area);
7838 } else {
7839 akw = NULL;
7840 }
7841 if (akw != NULL) {
7842 ha_warning("Trying to register action 'lua.%s' more than once. "
7843 "This will become a hard error in version 2.5.\n", name);
7844 }
7845
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007846 /* Check required environment. Only accepted "http" or "tcp". */
7847 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007848 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007849 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007850 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007851 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007852 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007853 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007854
7855 /* Fill fcn. */
7856 fcn->name = strdup(name);
7857 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007858 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007859 fcn->function_ref = ref;
7860
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007861 /* Set the expected number od arguments. */
7862 fcn->nargs = nargs;
7863
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007864 /* List head */
7865 akl->list.n = akl->list.p = NULL;
7866
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007867 /* action keyword. */
7868 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007869 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007870 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007871 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007872
7873 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7874
7875 akl->kw[0].match_pfx = 0;
7876 akl->kw[0].private = fcn;
7877 akl->kw[0].parse = action_register_lua;
7878
7879 /* select the action registering point. */
7880 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7881 tcp_req_cont_keywords_register(akl);
7882 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7883 tcp_res_cont_keywords_register(akl);
7884 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7885 http_req_keywords_register(akl);
7886 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7887 http_res_keywords_register(akl);
7888 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007889 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007890 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7891 "are expected.", lua_tostring(L, -1)));
7892
7893 /* pop the environment string. */
7894 lua_pop(L, 1);
7895 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007896 return ACT_RET_PRS_OK;
7897}
7898
7899static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7900 struct act_rule *rule, char **err)
7901{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007902 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007903
Christopher Fauleteb709802019-04-11 22:04:08 +02007904 if (px->mode == PR_MODE_HTTP && (px->options2 & PR_O2_USE_HTX)) {
Christopher Fauletafd8f102018-11-08 11:34:21 +01007905 memprintf(err, "Lua services cannot be used when the HTX internal representation is enabled");
7906 return ACT_RET_PRS_ERR;
7907 }
7908
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007909 /* Memory for the rule. */
7910 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7911 if (!rule->arg.hlua_rule) {
7912 memprintf(err, "out of memory error");
7913 return ACT_RET_PRS_ERR;
7914 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007915
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007916 /* Reference the Lua function and store the reference. */
7917 rule->arg.hlua_rule->fcn = *fcn;
7918
7919 /* TODO: later accept arguments. */
7920 rule->arg.hlua_rule->args = NULL;
7921
7922 /* Add applet pointer in the rule. */
7923 rule->applet.obj_type = OBJ_TYPE_APPLET;
7924 rule->applet.name = fcn->name;
7925 rule->applet.init = hlua_applet_tcp_init;
7926 rule->applet.fct = hlua_applet_tcp_fct;
7927 rule->applet.release = hlua_applet_tcp_release;
7928 rule->applet.timeout = hlua_timeout_applet;
7929
7930 return 0;
7931}
7932
7933/* This function is an LUA binding used for registering
7934 * "sample-conv" functions. It expects a converter name used
7935 * in the haproxy configuration file, and an LUA function.
7936 */
7937__LJMP static int hlua_register_service(lua_State *L)
7938{
7939 struct action_kw_list *akl;
7940 const char *name;
7941 const char *env;
7942 int ref;
7943 int len;
7944 struct hlua_function *fcn;
Thierry Fourniera9230f82020-11-28 20:41:07 +01007945 struct buffer *trash;
7946 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007947
7948 MAY_LJMP(check_args(L, 3, "register_service"));
7949
7950 /* First argument : converter name. */
7951 name = MAY_LJMP(luaL_checkstring(L, 1));
7952
7953 /* Second argument : environment. */
7954 env = MAY_LJMP(luaL_checkstring(L, 2));
7955
7956 /* Third argument : lua function. */
7957 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7958
Thierry Fourniera9230f82020-11-28 20:41:07 +01007959 /* Check for service already registered */
7960 trash = get_trash_chunk();
7961 chunk_printf(trash, "lua.%s", name);
7962 akw = service_find(trash->area);
7963 if (akw != NULL) {
7964 ha_warning("Trying to register service 'lua.%s' more than once. "
7965 "This will become a hard error in version 2.5.\n", name);
7966 }
7967
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007968 /* Allocate and fill the sample fetch keyword struct. */
7969 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7970 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007971 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007972 fcn = calloc(1, sizeof(*fcn));
7973 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007974 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007975
7976 /* Fill fcn. */
7977 len = strlen("<lua.>") + strlen(name) + 1;
7978 fcn->name = calloc(1, len);
7979 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007980 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007981 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7982 fcn->function_ref = ref;
7983
7984 /* List head */
7985 akl->list.n = akl->list.p = NULL;
7986
7987 /* converter keyword. */
7988 len = strlen("lua.") + strlen(name) + 1;
7989 akl->kw[0].kw = calloc(1, len);
7990 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007991 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007992
7993 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7994
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007995 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007996 if (strcmp(env, "tcp") == 0)
7997 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007998 else if (strcmp(env, "http") == 0)
7999 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008000 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008001 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01008002 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008003
8004 akl->kw[0].match_pfx = 0;
8005 akl->kw[0].private = fcn;
8006
8007 /* End of array. */
8008 memset(&akl->kw[1], 0, sizeof(*akl->kw));
8009
8010 /* Register this new converter */
8011 service_keywords_register(akl);
8012
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008013 return 0;
8014}
8015
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008016/* This function initialises Lua cli handler. It copies the
8017 * arguments in the Lua stack and create channel IO objects.
8018 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02008019static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008020{
8021 struct hlua *hlua;
8022 struct hlua_function *fcn;
8023 int i;
8024 const char *error;
8025
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008026 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008027 appctx->ctx.hlua_cli.fcn = private;
8028
Willy Tarreaubafbe012017-11-24 17:34:44 +01008029 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008030 if (!hlua) {
8031 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008032 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008033 }
8034 HLUA_INIT(hlua);
8035 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008036
8037 /* Create task used by signal to wakeup applets.
8038 * We use the same wakeup fonction than the Lua applet_tcp and
8039 * applet_http. It is absolutely compatible.
8040 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01008041 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008042 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01008043 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008044 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008045 }
8046 appctx->ctx.hlua_cli.task->nice = 0;
8047 appctx->ctx.hlua_cli.task->context = appctx;
8048 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
8049
8050 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01008051 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008052 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008053 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008054 }
8055
8056 /* The following Lua calls can fail. */
8057 if (!SET_SAFE_LJMP(hlua->T)) {
8058 if (lua_type(hlua->T, -1) == LUA_TSTRING)
8059 error = lua_tostring(hlua->T, -1);
8060 else
8061 error = "critical error";
8062 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
8063 goto error;
8064 }
8065
8066 /* Check stack available size. */
8067 if (!lua_checkstack(hlua->T, 2)) {
8068 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
8069 goto error;
8070 }
8071
8072 /* Restore the function in the stack. */
8073 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
8074
8075 /* Once the arguments parsed, the CLI is like an AppletTCP,
8076 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008077 */
8078 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
8079 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
8080 goto error;
8081 }
8082 hlua->nargs = 1;
8083
8084 /* push keywords in the stack. */
8085 for (i = 0; *args[i]; i++) {
8086 /* Check stack available size. */
8087 if (!lua_checkstack(hlua->T, 1)) {
8088 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
8089 goto error;
8090 }
8091 lua_pushstring(hlua->T, args[i]);
8092 hlua->nargs++;
8093 }
8094
8095 /* We must initialize the execution timeouts. */
8096 hlua->max_time = hlua_timeout_session;
8097
8098 /* At this point the execution is safe. */
8099 RESET_SAFE_LJMP(hlua->T);
8100
8101 /* It's ok */
8102 return 0;
8103
8104 /* It's not ok. */
8105error:
8106 RESET_SAFE_LJMP(hlua->T);
8107 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008108 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008109 return 1;
8110}
8111
8112static int hlua_cli_io_handler_fct(struct appctx *appctx)
8113{
8114 struct hlua *hlua;
8115 struct stream_interface *si;
8116 struct hlua_function *fcn;
8117
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008118 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008119 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01008120 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008121
8122 /* If the stream is disconnect or closed, ldo nothing. */
8123 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8124 return 1;
8125
8126 /* Execute the function. */
8127 switch (hlua_ctx_resume(hlua, 1)) {
8128
8129 /* finished. */
8130 case HLUA_E_OK:
8131 return 1;
8132
8133 /* yield. */
8134 case HLUA_E_AGAIN:
8135 /* We want write. */
8136 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008137 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008138 /* Set the timeout. */
8139 if (hlua->wake_time != TICK_ETERNITY)
8140 task_schedule(hlua->task, hlua->wake_time);
8141 return 0;
8142
8143 /* finished with error. */
8144 case HLUA_E_ERRMSG:
8145 /* Display log. */
8146 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
8147 fcn->name, lua_tostring(hlua->T, -1));
8148 lua_pop(hlua->T, 1);
8149 return 1;
8150
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008151 case HLUA_E_ETMOUT:
8152 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8153 fcn->name);
8154 return 1;
8155
8156 case HLUA_E_NOMEM:
8157 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8158 fcn->name);
8159 return 1;
8160
8161 case HLUA_E_YIELD: /* unexpected */
8162 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8163 fcn->name);
8164 return 1;
8165
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008166 case HLUA_E_ERR:
8167 /* Display log. */
8168 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8169 fcn->name);
8170 return 1;
8171
8172 default:
8173 return 1;
8174 }
8175
8176 return 1;
8177}
8178
8179static void hlua_cli_io_release_fct(struct appctx *appctx)
8180{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008181 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008182 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008183}
8184
8185/* This function is an LUA binding used for registering
8186 * new keywords in the cli. It expects a list of keywords
8187 * which are the "path". It is limited to 5 keywords. A
8188 * description of the command, a function to be executed
8189 * for the parsing and a function for io handlers.
8190 */
8191__LJMP static int hlua_register_cli(lua_State *L)
8192{
8193 struct cli_kw_list *cli_kws;
8194 const char *message;
8195 int ref_io;
8196 int len;
8197 struct hlua_function *fcn;
8198 int index;
8199 int i;
Thierry Fourniera9230f82020-11-28 20:41:07 +01008200 struct buffer *trash;
8201 const char *kw[5];
8202 struct cli_kw *cli_kw;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008203
8204 MAY_LJMP(check_args(L, 3, "register_cli"));
8205
8206 /* First argument : an array of maximum 5 keywords. */
8207 if (!lua_istable(L, 1))
8208 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8209
8210 /* Second argument : string with contextual message. */
8211 message = MAY_LJMP(luaL_checkstring(L, 2));
8212
8213 /* Third and fourth argument : lua function. */
8214 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8215
Thierry Fourniera9230f82020-11-28 20:41:07 +01008216 /* Check for CLI service already registered */
8217 trash = get_trash_chunk();
8218 index = 0;
8219 lua_pushnil(L);
8220 memset(kw, 0, sizeof(kw));
8221 while (lua_next(L, 1) != 0) {
8222 if (index >= CLI_PREFIX_KW_NB)
8223 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8224 if (lua_type(L, -1) != LUA_TSTRING)
8225 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8226 kw[index] = lua_tostring(L, -1);
8227 if (index == 0)
8228 chunk_printf(trash, "%s", kw[index]);
8229 else
8230 chunk_appendf(trash, " %s", kw[index]);
8231 index++;
8232 lua_pop(L, 1);
8233 }
8234 cli_kw = cli_find_kw_exact((char **)kw);
8235 if (cli_kw != NULL) {
8236 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
8237 "This will become a hard error in version 2.5.\n", trash->area);
8238 }
8239
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008240 /* Allocate and fill the sample fetch keyword struct. */
8241 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
8242 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008243 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008244 fcn = calloc(1, sizeof(*fcn));
8245 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008246 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008247
8248 /* Fill path. */
8249 index = 0;
8250 lua_pushnil(L);
8251 while(lua_next(L, 1) != 0) {
8252 if (index >= 5)
8253 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8254 if (lua_type(L, -1) != LUA_TSTRING)
8255 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8256 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
8257 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008258 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008259 index++;
8260 lua_pop(L, 1);
8261 }
8262
8263 /* Copy help message. */
8264 cli_kws->kw[0].usage = strdup(message);
8265 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008266 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008267
8268 /* Fill fcn io handler. */
8269 len = strlen("<lua.cli>") + 1;
8270 for (i = 0; i < index; i++)
8271 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8272 fcn->name = calloc(1, len);
8273 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008274 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008275 strncat((char *)fcn->name, "<lua.cli", len);
8276 for (i = 0; i < index; i++) {
8277 strncat((char *)fcn->name, ".", len);
8278 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8279 }
8280 strncat((char *)fcn->name, ">", len);
8281 fcn->function_ref = ref_io;
8282
8283 /* Fill last entries. */
8284 cli_kws->kw[0].private = fcn;
8285 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8286 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8287 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8288
8289 /* Register this new converter */
8290 cli_register_kw(cli_kws);
8291
8292 return 0;
8293}
8294
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008295static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
8296 struct proxy *defpx, const char *file, int line,
8297 char **err, unsigned int *timeout)
8298{
8299 const char *error;
8300
8301 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02008302 if (error == PARSE_TIME_OVER) {
8303 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
8304 args[1], args[0]);
8305 return -1;
8306 }
8307 else if (error == PARSE_TIME_UNDER) {
8308 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
8309 args[1], args[0]);
8310 return -1;
8311 }
8312 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008313 memprintf(err, "%s: invalid timeout", args[0]);
8314 return -1;
8315 }
8316 return 0;
8317}
8318
8319static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
8320 struct proxy *defpx, const char *file, int line,
8321 char **err)
8322{
8323 return hlua_read_timeout(args, section_type, curpx, defpx,
8324 file, line, err, &hlua_timeout_session);
8325}
8326
8327static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
8328 struct proxy *defpx, const char *file, int line,
8329 char **err)
8330{
8331 return hlua_read_timeout(args, section_type, curpx, defpx,
8332 file, line, err, &hlua_timeout_task);
8333}
8334
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008335static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
8336 struct proxy *defpx, const char *file, int line,
8337 char **err)
8338{
8339 return hlua_read_timeout(args, section_type, curpx, defpx,
8340 file, line, err, &hlua_timeout_applet);
8341}
8342
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008343static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
8344 struct proxy *defpx, const char *file, int line,
8345 char **err)
8346{
8347 char *error;
8348
8349 hlua_nb_instruction = strtoll(args[1], &error, 10);
8350 if (*error != '\0') {
8351 memprintf(err, "%s: invalid number", args[0]);
8352 return -1;
8353 }
8354 return 0;
8355}
8356
Willy Tarreau32f61e22015-03-18 17:54:59 +01008357static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
8358 struct proxy *defpx, const char *file, int line,
8359 char **err)
8360{
8361 char *error;
8362
8363 if (*(args[1]) == 0) {
8364 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8365 return -1;
8366 }
8367 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8368 if (*error != '\0') {
8369 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8370 return -1;
8371 }
8372 return 0;
8373}
8374
8375
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008376/* This function is called by the main configuration key "lua-load". It loads and
8377 * execute an lua file during the parsing of the HAProxy configuration file. It is
8378 * the main lua entry point.
8379 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008380 * This function runs with the HAProxy keywords API. It returns -1 if an error
8381 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008382 *
8383 * In some error case, LUA set an error message in top of the stack. This function
8384 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008385 *
8386 * This function can fail with an abort() due to an Lua critical error.
8387 * We are in the configuration parsing process of HAProxy, this abort() is
8388 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008389 */
8390static int hlua_load(char **args, int section_type, struct proxy *curpx,
8391 struct proxy *defpx, const char *file, int line,
8392 char **err)
8393{
8394 int error;
8395
Thierry Fourniere6679502020-11-29 01:06:24 +01008396 if (*(args[1]) == 0) {
8397 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
8398 return -1;
8399 }
8400
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008401 /* Just load and compile the file. */
8402 error = luaL_loadfile(gL.T, args[1]);
8403 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008404 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008405 lua_pop(gL.T, 1);
8406 return -1;
8407 }
8408
8409 /* If no syntax error where detected, execute the code. */
8410 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
8411 switch (error) {
8412 case LUA_OK:
8413 break;
8414 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008415 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008416 lua_pop(gL.T, 1);
8417 return -1;
8418 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008419 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008420 return -1;
8421 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008422 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008423 lua_pop(gL.T, 1);
8424 return -1;
Christopher Faulet20699902020-07-28 10:33:25 +02008425#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008426 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008427 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008428 lua_pop(gL.T, 1);
8429 return -1;
Christopher Faulet20699902020-07-28 10:33:25 +02008430#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008431 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008432 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008433 lua_pop(gL.T, 1);
8434 return -1;
8435 }
8436
8437 return 0;
8438}
8439
8440/* configuration keywords declaration */
8441static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008442 { CFG_GLOBAL, "lua-load", hlua_load },
8443 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8444 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008445 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008446 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008447 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008448 { 0, NULL, NULL },
8449}};
8450
Willy Tarreau0108d902018-11-25 19:14:37 +01008451INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8452
Christopher Fauletafd8f102018-11-08 11:34:21 +01008453
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008454/* This function can fail with an abort() due to an Lua critical error.
8455 * We are in the initialisation process of HAProxy, this abort() is
8456 * tolerated.
8457 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008458int hlua_post_init()
8459{
8460 struct hlua_init_function *init;
8461 const char *msg;
8462 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008463 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008464
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008465 /* Call post initialisation function in safe environement. */
8466 if (!SET_SAFE_LJMP(gL.T)) {
8467 if (lua_type(gL.T, -1) == LUA_TSTRING)
8468 error = lua_tostring(gL.T, -1);
8469 else
8470 error = "critical error";
8471 fprintf(stderr, "Lua post-init: %s.\n", error);
8472 exit(1);
8473 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008474
8475#if USE_OPENSSL
8476 /* Initialize SSL server. */
8477 if (socket_ssl.xprt->prepare_srv) {
8478 int saved_used_backed = global.ssl_used_backend;
8479 // don't affect maxconn automatic computation
8480 socket_ssl.xprt->prepare_srv(&socket_ssl);
8481 global.ssl_used_backend = saved_used_backed;
8482 }
8483#endif
8484
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008485 hlua_fcn_post_init(gL.T);
8486 RESET_SAFE_LJMP(gL.T);
8487
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008488 list_for_each_entry(init, &hlua_init_functions, l) {
8489 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
8490 ret = hlua_ctx_resume(&gL, 0);
8491 switch (ret) {
8492 case HLUA_E_OK:
8493 lua_pop(gL.T, -1);
Thierry Fournier65588c92020-11-28 11:02:58 +01008494 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008495 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008496 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008497 return 0;
8498 case HLUA_E_ERRMSG:
8499 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01008500 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008501 return 0;
8502 case HLUA_E_ERR:
8503 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008504 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008505 return 0;
8506 }
8507 }
8508 return 1;
8509}
8510
Willy Tarreau32f61e22015-03-18 17:54:59 +01008511/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8512 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8513 * is the previously allocated size or the kind of object in case of a new
8514 * allocation. <nsize> is the requested new size.
8515 */
8516static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8517{
8518 struct hlua_mem_allocator *zone = ud;
8519
8520 if (nsize == 0) {
8521 /* it's a free */
8522 if (ptr)
8523 zone->allocated -= osize;
8524 free(ptr);
8525 return NULL;
8526 }
8527
8528 if (!ptr) {
8529 /* it's a new allocation */
8530 if (zone->limit && zone->allocated + nsize > zone->limit)
8531 return NULL;
8532
8533 ptr = malloc(nsize);
8534 if (ptr)
8535 zone->allocated += nsize;
8536 return ptr;
8537 }
8538
8539 /* it's a realloc */
8540 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
8541 return NULL;
8542
8543 ptr = realloc(ptr, nsize);
8544 if (ptr)
8545 zone->allocated += nsize - osize;
8546 return ptr;
8547}
8548
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008549/* Ithis function can fail with an abort() due to an Lua critical error.
8550 * We are in the initialisation process of HAProxy, this abort() is
8551 * tolerated.
8552 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008553void hlua_init(void)
8554{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008555 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008556 int idx;
8557 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008558 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008559 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008560 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008561#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008562 struct srv_kw *kw;
8563 int tmp_error;
8564 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008565 char *args[] = { /* SSL client configuration. */
8566 "ssl",
8567 "verify",
8568 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008569 NULL
8570 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008571#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008572
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008573 /* Init main lua stack. */
8574 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008575 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008576 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008577 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008578 hlua_sethlua(&gL);
8579 gL.Tref = LUA_REFNIL;
8580 gL.task = NULL;
8581
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008582 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008583 * the Lua function can fail with an abort. We are in the initialisation
8584 * process of HAProxy, this abort() is tolerated.
8585 */
8586
Thierry Fournier75933d42016-01-21 09:30:18 +01008587 /* Set safe environment for the initialisation. */
8588 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008589 if (lua_type(gL.T, -1) == LUA_TSTRING)
8590 error_msg = lua_tostring(gL.T, -1);
8591 else
8592 error_msg = "critical error";
8593 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008594 exit(1);
8595 }
8596
Thierry Fourniera5d62582020-11-28 16:08:02 +01008597 /* Initialise lua. */
8598 luaL_openlibs(gL.T);
8599
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008600 /*
8601 *
8602 * Create "core" object.
8603 *
8604 */
8605
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008606 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008607 lua_newtable(gL.T);
8608
8609 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008610 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008611 hlua_class_const_int(gL.T, log_levels[i], i);
8612
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008613 /* Register special functions. */
8614 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008615 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008616 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008617 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008618 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008619 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008620 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008621 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008622 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008623 hlua_class_function(gL.T, "sleep", hlua_sleep);
8624 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008625 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8626 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8627 hlua_class_function(gL.T, "set_map", hlua_set_map);
8628 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008629 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008630 hlua_class_function(gL.T, "log", hlua_log);
8631 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8632 hlua_class_function(gL.T, "Info", hlua_log_info);
8633 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8634 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008635 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008636 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008637
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008638 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008639
8640 /*
8641 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008642 * Register class Map
8643 *
8644 */
8645
8646 /* This table entry is the object "Map" base. */
8647 lua_newtable(gL.T);
8648
8649 /* register pattern types. */
8650 for (i=0; i<PAT_MATCH_NUM; i++)
8651 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008652 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008653 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8654 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008655 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008656
8657 /* register constructor. */
8658 hlua_class_function(gL.T, "new", hlua_map_new);
8659
8660 /* Create and fill the metatable. */
8661 lua_newtable(gL.T);
8662
8663 /* Create and fille the __index entry. */
8664 lua_pushstring(gL.T, "__index");
8665 lua_newtable(gL.T);
8666
8667 /* Register . */
8668 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8669 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8670
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008671 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008672
Thierry Fournier45e78d72016-02-19 18:34:46 +01008673 /* Register previous table in the registry with reference and named entry.
8674 * The function hlua_register_metatable() pops the stack, so we
8675 * previously create a copy of the table.
8676 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008677 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008678 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008679
8680 /* Assign the metatable to the mai Map object. */
8681 lua_setmetatable(gL.T, -2);
8682
8683 /* Set a name to the table. */
8684 lua_setglobal(gL.T, "Map");
8685
8686 /*
8687 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008688 * Register class Channel
8689 *
8690 */
8691
8692 /* Create and fill the metatable. */
8693 lua_newtable(gL.T);
8694
8695 /* Create and fille the __index entry. */
8696 lua_pushstring(gL.T, "__index");
8697 lua_newtable(gL.T);
8698
8699 /* Register . */
8700 hlua_class_function(gL.T, "get", hlua_channel_get);
8701 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8702 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8703 hlua_class_function(gL.T, "set", hlua_channel_set);
8704 hlua_class_function(gL.T, "append", hlua_channel_append);
8705 hlua_class_function(gL.T, "send", hlua_channel_send);
8706 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8707 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8708 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008709 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008710
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008711 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008712
8713 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008714 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008715
8716 /*
8717 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008718 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008719 *
8720 */
8721
8722 /* Create and fill the metatable. */
8723 lua_newtable(gL.T);
8724
8725 /* Create and fille the __index entry. */
8726 lua_pushstring(gL.T, "__index");
8727 lua_newtable(gL.T);
8728
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008729 /* Browse existing fetches and create the associated
8730 * object method.
8731 */
8732 sf = NULL;
8733 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8734
8735 /* Dont register the keywork if the arguments check function are
8736 * not safe during the runtime.
8737 */
8738 if ((sf->val_args != NULL) &&
8739 (sf->val_args != val_payload_lv) &&
8740 (sf->val_args != val_hdr))
8741 continue;
8742
8743 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8744 * by an underscore.
8745 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008746 strncpy(trash.area, sf->kw, trash.size);
8747 trash.area[trash.size - 1] = '\0';
8748 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008749 if (*p == '.' || *p == '-' || *p == '+')
8750 *p = '_';
8751
8752 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008753 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008754 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008755 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008756 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008757 }
8758
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008759 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008760
8761 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008762 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008763
8764 /*
8765 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008766 * Register class Converters
8767 *
8768 */
8769
8770 /* Create and fill the metatable. */
8771 lua_newtable(gL.T);
8772
8773 /* Create and fill the __index entry. */
8774 lua_pushstring(gL.T, "__index");
8775 lua_newtable(gL.T);
8776
8777 /* Browse existing converters and create the associated
8778 * object method.
8779 */
8780 sc = NULL;
8781 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8782 /* Dont register the keywork if the arguments check function are
8783 * not safe during the runtime.
8784 */
8785 if (sc->val_args != NULL)
8786 continue;
8787
8788 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8789 * by an underscore.
8790 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008791 strncpy(trash.area, sc->kw, trash.size);
8792 trash.area[trash.size - 1] = '\0';
8793 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008794 if (*p == '.' || *p == '-' || *p == '+')
8795 *p = '_';
8796
8797 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008798 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008799 lua_pushlightuserdata(gL.T, sc);
8800 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008801 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008802 }
8803
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008804 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008805
8806 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008807 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008808
8809 /*
8810 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008811 * Register class HTTP
8812 *
8813 */
8814
8815 /* Create and fill the metatable. */
8816 lua_newtable(gL.T);
8817
8818 /* Create and fille the __index entry. */
8819 lua_pushstring(gL.T, "__index");
8820 lua_newtable(gL.T);
8821
8822 /* Register Lua functions. */
8823 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8824 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8825 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8826 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8827 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8828 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8829 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8830 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8831 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8832 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8833
8834 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8835 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8836 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8837 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8838 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8839 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008840 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008841
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008842 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008843
8844 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008845 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008846
8847 /*
8848 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008849 * Register class AppletTCP
8850 *
8851 */
8852
8853 /* Create and fill the metatable. */
8854 lua_newtable(gL.T);
8855
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008856 /* Create and fille the __index entry. */
8857 lua_pushstring(gL.T, "__index");
8858 lua_newtable(gL.T);
8859
8860 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008861 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8862 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8863 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8864 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8865 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008866 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8867 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8868 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008869
8870 lua_settable(gL.T, -3);
8871
8872 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008873 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008874
8875 /*
8876 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008877 * Register class AppletHTTP
8878 *
8879 */
8880
8881 /* Create and fill the metatable. */
8882 lua_newtable(gL.T);
8883
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008884 /* Create and fille the __index entry. */
8885 lua_pushstring(gL.T, "__index");
8886 lua_newtable(gL.T);
8887
8888 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008889 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8890 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008891 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8892 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8893 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008894 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8895 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8896 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8897 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8898 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8899 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8900
8901 lua_settable(gL.T, -3);
8902
8903 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008904 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008905
8906 /*
8907 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008908 * Register class TXN
8909 *
8910 */
8911
8912 /* Create and fill the metatable. */
8913 lua_newtable(gL.T);
8914
8915 /* Create and fille the __index entry. */
8916 lua_pushstring(gL.T, "__index");
8917 lua_newtable(gL.T);
8918
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008919 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008920 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8921 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8922 hlua_class_function(gL.T, "set_var", hlua_set_var);
8923 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8924 hlua_class_function(gL.T, "get_var", hlua_get_var);
8925 hlua_class_function(gL.T, "done", hlua_txn_done);
8926 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8927 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8928 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8929 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8930 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8931 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8932 hlua_class_function(gL.T, "log", hlua_txn_log);
8933 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8934 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8935 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8936 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008937
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008938 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008939
8940 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008941 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008942
8943 /*
8944 *
8945 * Register class Socket
8946 *
8947 */
8948
8949 /* Create and fill the metatable. */
8950 lua_newtable(gL.T);
8951
8952 /* Create and fille the __index entry. */
8953 lua_pushstring(gL.T, "__index");
8954 lua_newtable(gL.T);
8955
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008956#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008957 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008958#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008959 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8960 hlua_class_function(gL.T, "send", hlua_socket_send);
8961 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8962 hlua_class_function(gL.T, "close", hlua_socket_close);
8963 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8964 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8965 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8966 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8967
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008968 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008969
8970 /* Register the garbage collector entry. */
8971 lua_pushstring(gL.T, "__gc");
8972 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008973 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008974
8975 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008976 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008977
8978 /* Proxy and server configuration initialisation. */
8979 memset(&socket_proxy, 0, sizeof(socket_proxy));
8980 init_new_proxy(&socket_proxy);
8981 socket_proxy.parent = NULL;
8982 socket_proxy.last_change = now.tv_sec;
8983 socket_proxy.id = "LUA-SOCKET";
8984 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8985 socket_proxy.maxconn = 0;
8986 socket_proxy.accept = NULL;
8987 socket_proxy.options2 |= PR_O2_INDEPSTR;
8988 socket_proxy.srv = NULL;
8989 socket_proxy.conn_retries = 0;
8990 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8991
8992 /* Init TCP server: unchanged parameters */
8993 memset(&socket_tcp, 0, sizeof(socket_tcp));
8994 socket_tcp.next = NULL;
8995 socket_tcp.proxy = &socket_proxy;
8996 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8997 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008998 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008999 socket_tcp.priv_conns = NULL;
9000 socket_tcp.idle_conns = NULL;
9001 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02009002 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009003 socket_tcp.last_change = 0;
9004 socket_tcp.id = "LUA-TCP-CONN";
9005 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
9006 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
9007 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
9008
9009 /* XXX: Copy default parameter from default server,
9010 * but the default server is not initialized.
9011 */
9012 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
9013 socket_tcp.minconn = socket_proxy.defsrv.minconn;
9014 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
9015 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
9016 socket_tcp.onerror = socket_proxy.defsrv.onerror;
9017 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
9018 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
9019 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
9020 socket_tcp.uweight = socket_proxy.defsrv.iweight;
9021 socket_tcp.iweight = socket_proxy.defsrv.iweight;
9022
9023 socket_tcp.check.status = HCHK_STATUS_INI;
9024 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
9025 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
9026 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
9027 socket_tcp.check.server = &socket_tcp;
9028
9029 socket_tcp.agent.status = HCHK_STATUS_INI;
9030 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
9031 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
9032 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
9033 socket_tcp.agent.server = &socket_tcp;
9034
Willy Tarreaua261e9b2016-12-22 20:44:00 +01009035 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009036
9037#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009038 /* Init TCP server: unchanged parameters */
9039 memset(&socket_ssl, 0, sizeof(socket_ssl));
9040 socket_ssl.next = NULL;
9041 socket_ssl.proxy = &socket_proxy;
9042 socket_ssl.obj_type = OBJ_TYPE_SERVER;
9043 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04009044 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01009045 socket_ssl.priv_conns = NULL;
9046 socket_ssl.idle_conns = NULL;
9047 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02009048 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009049 socket_ssl.last_change = 0;
9050 socket_ssl.id = "LUA-SSL-CONN";
9051 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
9052 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
9053 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
9054
9055 /* XXX: Copy default parameter from default server,
9056 * but the default server is not initialized.
9057 */
9058 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
9059 socket_ssl.minconn = socket_proxy.defsrv.minconn;
9060 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
9061 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
9062 socket_ssl.onerror = socket_proxy.defsrv.onerror;
9063 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
9064 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
9065 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
9066 socket_ssl.uweight = socket_proxy.defsrv.iweight;
9067 socket_ssl.iweight = socket_proxy.defsrv.iweight;
9068
9069 socket_ssl.check.status = HCHK_STATUS_INI;
9070 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
9071 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
9072 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
9073 socket_ssl.check.server = &socket_ssl;
9074
9075 socket_ssl.agent.status = HCHK_STATUS_INI;
9076 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
9077 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
9078 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
9079 socket_ssl.agent.server = &socket_ssl;
9080
Thierry FOURNIER36d13742015-03-17 16:48:53 +01009081 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01009082 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009083
Thierry FOURNIER36d13742015-03-17 16:48:53 +01009084 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009085 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
9086 /*
9087 *
9088 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009089 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009090 * features like client certificates and ssl_verify.
9091 *
9092 */
9093 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
9094 if (tmp_error != 0) {
9095 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
9096 abort(); /* This must be never arrives because the command line
9097 not editable by the user. */
9098 }
9099 idx += kw->skip;
9100 }
9101 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009102#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01009103
9104 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01009105}
Willy Tarreaubb57d942016-12-21 19:04:56 +01009106
Willy Tarreau80713382018-11-26 10:19:54 +01009107static void hlua_register_build_options(void)
9108{
Willy Tarreaubb57d942016-12-21 19:04:56 +01009109 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01009110
Willy Tarreaubb57d942016-12-21 19:04:56 +01009111 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
9112 hap_register_build_opts(ptr, 1);
9113}
Willy Tarreau80713382018-11-26 10:19:54 +01009114
9115INITCALL0(STG_REGISTER, hlua_register_build_options);