blob: f1e91f5cc3556a9573ab432922e6bdc0b9450caf [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
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010013#include <ctype.h>
Mark Lakes56cc1252018-03-27 09:48:06 +020014#include <limits.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020015#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010016
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010017#include <lauxlib.h>
18#include <lua.h>
19#include <lualib.h>
20
Thierry FOURNIER463119c2015-03-10 00:35:36 +010021#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
22#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010023#endif
24
Thierry FOURNIER380d0932015-01-23 14:27:52 +010025#include <ebpttree.h>
26
27#include <common/cfgparse.h>
Willy Tarreaub059b892018-10-16 17:57:36 +020028#include <common/compiler.h>
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +020029#include <common/hathreads.h>
Willy Tarreau0108d902018-11-25 19:14:37 +010030#include <common/initcall.h>
31#include <common/xref.h>
Christopher Faulet724a12c2018-12-13 22:12:15 +010032#include <common/h1.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010033
William Lallemand9ed62032016-11-21 17:49:11 +010034#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010035#include <types/hlua.h>
36#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010037#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010038
Thierry FOURNIER55da1652015-01-23 11:36:30 +010039#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020040#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010041#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010042#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010043#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010044#include <proto/stats.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010045#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010046#include <proto/hlua_fcn.h>
Willy Tarreau79e57332018-10-02 16:01:16 +020047#include <proto/http_fetch.h>
Christopher Faulet724a12c2018-12-13 22:12:15 +010048#include <proto/http_htx.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020049#include <proto/http_rules.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020050#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010051#include <proto/obj_type.h>
Patrick Hemmer268a7072018-05-11 12:52:31 -040052#include <proto/queue.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010053#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010054#include <proto/payload.h>
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020055#include <proto/http_ana.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010056#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010057#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020058#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020059#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010060#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010061#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010062#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020063#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010064
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010065/* Lua uses longjmp to perform yield or throwing errors. This
66 * macro is used only for identifying the function that can
67 * not return because a longjmp is executed.
68 * __LJMP marks a prototype of hlua file that can use longjmp.
69 * WILL_LJMP() marks an lua function that will use longjmp.
70 * MAY_LJMP() marks an lua function that may use longjmp.
71 */
72#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020073#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010074#define MAY_LJMP(func) func
75
Thierry FOURNIERbabae282015-09-17 11:36:37 +020076/* This couple of function executes securely some Lua calls outside of
77 * the lua runtime environment. Each Lua call can return a longjmp
78 * if it encounter a memory error.
79 *
80 * Lua documentation extract:
81 *
82 * If an error happens outside any protected environment, Lua calls
83 * a panic function (see lua_atpanic) and then calls abort, thus
84 * exiting the host application. Your panic function can avoid this
85 * exit by never returning (e.g., doing a long jump to your own
86 * recovery point outside Lua).
87 *
88 * The panic function runs as if it were a message handler (see
89 * §2.3); in particular, the error message is at the top of the
90 * stack. However, there is no guarantee about stack space. To push
91 * anything on the stack, the panic function must first check the
92 * available space (see §4.2).
93 *
94 * We must check all the Lua entry point. This includes:
95 * - The include/proto/hlua.h exported functions
96 * - the task wrapper function
97 * - The action wrapper function
98 * - The converters wrapper function
99 * - The sample-fetch wrapper functions
100 *
101 * It is tolerated that the initilisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800102 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200103 *
104 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
105 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
106 * because they must be exists in the program stack when the longjmp
107 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200108 *
109 * Note that the Lua processing is not really thread safe. It provides
110 * heavy system which consists to add our own lock function in the Lua
111 * code and recompile the library. This system will probably not accepted
112 * by maintainers of various distribs.
113 *
114 * Our main excution point of the Lua is the function lua_resume(). A
115 * quick looking on the Lua sources displays a lua_lock() a the start
116 * of function and a lua_unlock() at the end of the function. So I
117 * conclude that the Lua thread safe mode just perform a mutex around
118 * all execution. So I prefer to do this in the HAProxy code, it will be
119 * easier for distro maintainers.
120 *
121 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
122 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
123 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200124 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100125__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200126THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200127static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau9d6bb5a2020-02-06 15:55:41 +0100128static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129
130#define SET_SAFE_LJMP(__L) \
131 ({ \
132 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100133 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134 if (setjmp(safe_ljmp_env) != 0) { \
135 lua_atpanic(__L, hlua_panic_safe); \
136 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100137 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200138 } else { \
139 lua_atpanic(__L, hlua_panic_ljmp); \
140 ret = 1; \
141 } \
142 ret; \
143 })
144
145/* If we are the last function catching Lua errors, we
146 * must reset the panic function.
147 */
148#define RESET_SAFE_LJMP(__L) \
149 do { \
150 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100151 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200152 } while(0)
153
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200154/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200155#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100156/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200157#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200158/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100159#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100160#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200161
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100162/* The main Lua execution context. */
163struct hlua gL;
164
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100165/* This is the memory pool containing struct lua for applets
166 * (including cli).
167 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100168DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100169
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100170/* Used for Socket connection. */
171static struct proxy socket_proxy;
172static struct server socket_tcp;
173#ifdef USE_OPENSSL
174static struct server socket_ssl;
175#endif
176
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100177/* List head of the function called at the initialisation time. */
178struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
179
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100180/* The following variables contains the reference of the different
181 * Lua classes. These references are useful for identify metadata
182 * associated with an object.
183 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100184static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100185static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100186static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100187static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100188static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100189static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200190static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200191static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200192static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100193static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100194
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100195/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200196 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100197 * short timeout. Lua linked with tasks doesn't have a timeout
198 * because a task may remain alive during all the haproxy execution.
199 */
200static unsigned int hlua_timeout_session = 4000; /* session timeout. */
201static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200202static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100203
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100204/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
205 * it is used for preventing infinite loops.
206 *
207 * I test the scheer with an infinite loop containing one incrementation
208 * and one test. I run this loop between 10 seconds, I raise a ceil of
209 * 710M loops from one interrupt each 9000 instructions, so I fix the value
210 * to one interrupt each 10 000 instructions.
211 *
212 * configured | Number of
213 * instructions | loops executed
214 * between two | in milions
215 * forced yields |
216 * ---------------+---------------
217 * 10 | 160
218 * 500 | 670
219 * 1000 | 680
220 * 5000 | 700
221 * 7000 | 700
222 * 8000 | 700
223 * 9000 | 710 <- ceil
224 * 10000 | 710
225 * 100000 | 710
226 * 1000000 | 710
227 *
228 */
229static unsigned int hlua_nb_instruction = 10000;
230
Willy Tarreau32f61e22015-03-18 17:54:59 +0100231/* Descriptor for the memory allocation state. If limit is not null, it will
232 * be enforced on any memory allocation.
233 */
234struct hlua_mem_allocator {
235 size_t allocated;
236 size_t limit;
237};
238
239static struct hlua_mem_allocator hlua_global_allocator;
240
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100241/* These functions converts types between HAProxy internal args or
242 * sample and LUA types. Another function permits to check if the
243 * LUA stack contains arguments according with an required ARG_T
244 * format.
245 */
246static int hlua_arg2lua(lua_State *L, const struct arg *arg);
247static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100248__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100249 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100250static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100251static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100252static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
253
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100254__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200255
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200256#define SEND_ERR(__be, __fmt, __args...) \
257 do { \
258 send_log(__be, LOG_ERR, __fmt, ## __args); \
259 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100260 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200261 } while (0)
262
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100263/* Used to check an Lua function type in the stack. It creates and
264 * returns a reference of the function. This function throws an
265 * error if the rgument is not a "function".
266 */
267__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
268{
269 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100270 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100271 WILL_LJMP(luaL_argerror(L, argno, msg));
272 }
273 lua_pushvalue(L, argno);
274 return luaL_ref(L, LUA_REGISTRYINDEX);
275}
276
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200277/* Return the string that is of the top of the stack. */
278const char *hlua_get_top_error_string(lua_State *L)
279{
280 if (lua_gettop(L) < 1)
281 return "unknown error";
282 if (lua_type(L, -1) != LUA_TSTRING)
283 return "unknown error";
284 return lua_tostring(L, -1);
285}
286
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200287__LJMP static const char *hlua_traceback(lua_State *L)
288{
289 lua_Debug ar;
290 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200291 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200292 int filled = 0;
293
294 while (lua_getstack(L, level++, &ar)) {
295
296 /* Add separator */
297 if (filled)
298 chunk_appendf(msg, ", ");
299 filled = 1;
300
301 /* Fill fields:
302 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
303 * 'l': fills in the field currentline;
304 * 'n': fills in the field name and namewhat;
305 * 't': fills in the field istailcall;
306 */
307 lua_getinfo(L, "Slnt", &ar);
308
309 /* Append code localisation */
310 if (ar.currentline > 0)
311 chunk_appendf(msg, "%s:%d ", ar.short_src, ar.currentline);
312 else
313 chunk_appendf(msg, "%s ", ar.short_src);
314
315 /*
316 * Get function name
317 *
318 * if namewhat is no empty, name is defined.
319 * what contains "Lua" for Lua function, "C" for C function,
320 * or "main" for main code.
321 */
322 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
323 chunk_appendf(msg, "%s '%s'", ar.namewhat, ar.name); /* use it */
324
325 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
326 chunk_appendf(msg, "main chunk");
327
328 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
329 chunk_appendf(msg, "C function line %d", ar.linedefined);
330
331 else /* nothing left... */
332 chunk_appendf(msg, "?");
333
334
335 /* Display tailed call */
336 if (ar.istailcall)
337 chunk_appendf(msg, " ...");
338 }
339
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200340 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200341}
342
343
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100344/* This function check the number of arguments available in the
345 * stack. If the number of arguments available is not the same
346 * then <nb> an error is throwed.
347 */
348__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
349{
350 if (lua_gettop(L) == nb)
351 return;
352 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
353}
354
Mark Lakes22154b42018-01-29 14:38:40 -0800355/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100356 * and the line number where the error is encountered.
357 */
358static int hlua_pusherror(lua_State *L, const char *fmt, ...)
359{
360 va_list argp;
361 va_start(argp, fmt);
362 luaL_where(L, 1);
363 lua_pushvfstring(L, fmt, argp);
364 va_end(argp);
365 lua_concat(L, 2);
366 return 1;
367}
368
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100369/* This functions is used with sample fetch and converters. It
370 * converts the HAProxy configuration argument in a lua stack
371 * values.
372 *
373 * It takes an array of "arg", and each entry of the array is
374 * converted and pushed in the LUA stack.
375 */
376static int hlua_arg2lua(lua_State *L, const struct arg *arg)
377{
378 switch (arg->type) {
379 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100380 case ARGT_TIME:
381 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100382 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100383 break;
384
385 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200386 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100387 break;
388
389 case ARGT_IPV4:
390 case ARGT_IPV6:
391 case ARGT_MSK4:
392 case ARGT_MSK6:
393 case ARGT_FE:
394 case ARGT_BE:
395 case ARGT_TAB:
396 case ARGT_SRV:
397 case ARGT_USR:
398 case ARGT_MAP:
399 default:
400 lua_pushnil(L);
401 break;
402 }
403 return 1;
404}
405
406/* This function take one entrie in an LUA stack at the index "ud",
407 * and try to convert it in an HAProxy argument entry. This is useful
408 * with sample fetch wrappers. The input arguments are gived to the
409 * lua wrapper and converted as arg list by thi function.
410 */
411static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
412{
413 switch (lua_type(L, ud)) {
414
415 case LUA_TNUMBER:
416 case LUA_TBOOLEAN:
417 arg->type = ARGT_SINT;
418 arg->data.sint = lua_tointeger(L, ud);
419 break;
420
421 case LUA_TSTRING:
422 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200423 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200424 /* We don't know the actual size of the underlying allocation, so be conservative. */
425 arg->data.str.size = arg->data.str.data;
426 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100427 break;
428
429 case LUA_TUSERDATA:
430 case LUA_TNIL:
431 case LUA_TTABLE:
432 case LUA_TFUNCTION:
433 case LUA_TTHREAD:
434 case LUA_TLIGHTUSERDATA:
435 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200436 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100437 break;
438 }
439 return 1;
440}
441
442/* the following functions are used to convert a struct sample
443 * in Lua type. This useful to convert the return of the
444 * fetchs or converters.
445 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100446static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100447{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200448 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100449 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100450 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200451 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100452 break;
453
454 case SMP_T_BIN:
455 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200456 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100457 break;
458
459 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200460 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100461 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
462 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
463 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
464 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
465 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
466 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
467 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
468 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
469 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200470 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100471 break;
472 default:
473 lua_pushnil(L);
474 break;
475 }
476 break;
477
478 case SMP_T_IPV4:
479 case SMP_T_IPV6:
480 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200481 if (sample_casts[smp->data.type][SMP_T_STR] &&
482 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200483 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100484 else
485 lua_pushnil(L);
486 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100487 default:
488 lua_pushnil(L);
489 break;
490 }
491 return 1;
492}
493
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100494/* the following functions are used to convert a struct sample
495 * in Lua strings. This is useful to convert the return of the
496 * fetchs or converters.
497 */
498static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
499{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200500 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100501
502 case SMP_T_BIN:
503 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200504 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100505 break;
506
507 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200508 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100509 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
510 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
511 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
512 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
513 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
514 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
515 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
516 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
517 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200518 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100519 break;
520 default:
521 lua_pushstring(L, "");
522 break;
523 }
524 break;
525
526 case SMP_T_SINT:
527 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100528 case SMP_T_IPV4:
529 case SMP_T_IPV6:
530 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200531 if (sample_casts[smp->data.type][SMP_T_STR] &&
532 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200533 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100534 else
535 lua_pushstring(L, "");
536 break;
537 default:
538 lua_pushstring(L, "");
539 break;
540 }
541 return 1;
542}
543
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100544/* the following functions are used to convert an Lua type in a
545 * struct sample. This is useful to provide data from a converter
546 * to the LUA code.
547 */
548static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
549{
550 switch (lua_type(L, ud)) {
551
552 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200553 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200554 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100555 break;
556
557
558 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200559 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200560 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100561 break;
562
563 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200564 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100565 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200566 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200567 /* We don't know the actual size of the underlying allocation, so be conservative. */
568 smp->data.u.str.size = smp->data.u.str.data;
569 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100570 break;
571
572 case LUA_TUSERDATA:
573 case LUA_TNIL:
574 case LUA_TTABLE:
575 case LUA_TFUNCTION:
576 case LUA_TTHREAD:
577 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200578 case LUA_TNONE:
579 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200580 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200581 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100582 break;
583 }
584 return 1;
585}
586
587/* This function check the "argp" builded by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800588 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100589 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100590 *
591 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
592 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100593 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100594__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100595 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100596{
597 int min_arg;
598 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100599 struct proxy *px;
600 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100601
602 idx = 0;
603 min_arg = ARGM(mask);
604 mask >>= ARGM_BITS;
605
606 while (1) {
607
608 /* Check oversize. */
609 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100610 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100611 }
612
613 /* Check for mandatory arguments. */
614 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100615 if (idx < min_arg) {
616
617 /* If miss other argument than the first one, we return an error. */
618 if (idx > 0)
619 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
620
621 /* If first argument have a certain type, some default values
622 * may be used. See the function smp_resolve_args().
623 */
624 switch (mask & ARGT_MASK) {
625
626 case ARGT_FE:
627 if (!(p->cap & PR_CAP_FE))
628 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
629 argp[idx].data.prx = p;
630 argp[idx].type = ARGT_FE;
631 argp[idx+1].type = ARGT_STOP;
632 break;
633
634 case ARGT_BE:
635 if (!(p->cap & PR_CAP_BE))
636 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
637 argp[idx].data.prx = p;
638 argp[idx].type = ARGT_BE;
639 argp[idx+1].type = ARGT_STOP;
640 break;
641
642 case ARGT_TAB:
643 argp[idx].data.prx = p;
644 argp[idx].type = ARGT_TAB;
645 argp[idx+1].type = ARGT_STOP;
646 break;
647
648 default:
649 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
650 break;
651 }
652 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100653 return 0;
654 }
655
656 /* Check for exceed the number of requiered argument. */
657 if ((mask & ARGT_MASK) == ARGT_STOP &&
658 argp[idx].type != ARGT_STOP) {
659 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
660 }
661
662 if ((mask & ARGT_MASK) == ARGT_STOP &&
663 argp[idx].type == ARGT_STOP) {
664 return 0;
665 }
666
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100667 /* Convert some argument types. */
668 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100669 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100670 if (argp[idx].type != ARGT_SINT)
671 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
672 argp[idx].type = ARGT_SINT;
673 break;
674
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100675 case ARGT_TIME:
676 if (argp[idx].type != ARGT_SINT)
677 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200678 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100679 break;
680
681 case ARGT_SIZE:
682 if (argp[idx].type != ARGT_SINT)
683 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200684 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100685 break;
686
687 case ARGT_FE:
688 if (argp[idx].type != ARGT_STR)
689 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200690 memcpy(trash.area, argp[idx].data.str.area,
691 argp[idx].data.str.data);
692 trash.area[argp[idx].data.str.data] = 0;
693 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100694 if (!argp[idx].data.prx)
695 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
696 argp[idx].type = ARGT_FE;
697 break;
698
699 case ARGT_BE:
700 if (argp[idx].type != ARGT_STR)
701 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200702 memcpy(trash.area, argp[idx].data.str.area,
703 argp[idx].data.str.data);
704 trash.area[argp[idx].data.str.data] = 0;
705 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100706 if (!argp[idx].data.prx)
707 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
708 argp[idx].type = ARGT_BE;
709 break;
710
711 case ARGT_TAB:
712 if (argp[idx].type != ARGT_STR)
713 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200714 memcpy(trash.area, argp[idx].data.str.area,
715 argp[idx].data.str.data);
716 trash.area[argp[idx].data.str.data] = 0;
Tim Duesterhus9fe7c632019-09-29 23:03:09 +0200717 argp[idx].data.t = stktable_find_by_name(trash.area);
718 if (!argp[idx].data.t)
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100719 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
720 argp[idx].type = ARGT_TAB;
721 break;
722
723 case ARGT_SRV:
724 if (argp[idx].type != ARGT_STR)
725 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200726 memcpy(trash.area, argp[idx].data.str.area,
727 argp[idx].data.str.data);
728 trash.area[argp[idx].data.str.data] = 0;
729 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100730 if (sname) {
731 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200732 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200733 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100734 if (!px)
735 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
736 }
737 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200738 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100739 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100740 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100741 argp[idx].data.srv = findserver(px, sname);
742 if (!argp[idx].data.srv)
743 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
744 argp[idx].type = ARGT_SRV;
745 break;
746
747 case ARGT_IPV4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200748 memcpy(trash.area, argp[idx].data.str.area,
749 argp[idx].data.str.data);
750 trash.area[argp[idx].data.str.data] = 0;
751 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100752 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
753 argp[idx].type = ARGT_IPV4;
754 break;
755
756 case ARGT_MSK4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200757 memcpy(trash.area, argp[idx].data.str.area,
758 argp[idx].data.str.data);
759 trash.area[argp[idx].data.str.data] = 0;
760 if (!str2mask(trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100761 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
762 argp[idx].type = ARGT_MSK4;
763 break;
764
765 case ARGT_IPV6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200766 memcpy(trash.area, argp[idx].data.str.area,
767 argp[idx].data.str.data);
768 trash.area[argp[idx].data.str.data] = 0;
769 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100770 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
771 argp[idx].type = ARGT_IPV6;
772 break;
773
774 case ARGT_MSK6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200775 memcpy(trash.area, argp[idx].data.str.area,
776 argp[idx].data.str.data);
777 trash.area[argp[idx].data.str.data] = 0;
778 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
Tim Duesterhusb814da62018-01-25 16:24:50 +0100779 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
780 argp[idx].type = ARGT_MSK6;
781 break;
782
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100783 case ARGT_MAP:
784 case ARGT_REG:
785 case ARGT_USR:
786 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100787 break;
788 }
789
790 /* Check for type of argument. */
791 if ((mask & ARGT_MASK) != argp[idx].type) {
792 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
793 arg_type_names[(mask & ARGT_MASK)],
794 arg_type_names[argp[idx].type & ARGT_MASK]);
795 WILL_LJMP(luaL_argerror(L, first + idx, msg));
796 }
797
798 /* Next argument. */
799 mask >>= ARGT_BITS;
800 idx++;
801 }
802}
803
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100804/*
805 * The following functions are used to make correspondance between the the
806 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100807 *
808 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100809 * - hlua_sethlua : create the association between hlua context and lua_state.
810 */
811static inline struct hlua *hlua_gethlua(lua_State *L)
812{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100813 struct hlua **hlua = lua_getextraspace(L);
814 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100815}
816static inline void hlua_sethlua(struct hlua *hlua)
817{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100818 struct hlua **hlua_store = lua_getextraspace(hlua->T);
819 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100820}
821
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100822/* This function is used to send logs. It try to send on screen (stderr)
823 * and on the default syslog server.
824 */
825static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
826{
827 struct tm tm;
828 char *p;
829
830 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200831 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100832 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200833 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200834 /* Break the message if exceed the buffer size. */
835 *(p-4) = ' ';
836 *(p-3) = '.';
837 *(p-2) = '.';
838 *(p-1) = '.';
839 break;
840 }
Willy Tarreau90807112020-02-25 08:16:33 +0100841 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100842 *p = *msg;
843 else
844 *p = '.';
845 }
846 *p = '\0';
847
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200848 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100849 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200850 get_localtime(date.tv_sec, &tm);
851 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100852 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200853 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100854 fflush(stderr);
855 }
856}
857
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100858/* This function just ensure that the yield will be always
859 * returned with a timeout and permit to set some flags
860 */
861__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100862 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100863{
864 struct hlua *hlua = hlua_gethlua(L);
865
866 /* Set the wake timeout. If timeout is required, we set
867 * the expiration time.
868 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200869 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100870
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100871 hlua->flags |= flags;
872
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100873 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +0200874 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100875}
876
Willy Tarreau87b09662015-04-03 00:22:06 +0200877/* This function initialises the Lua environment stored in the stream.
878 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100879 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200880 *
881 * This function is particular. it initialises a new Lua thread. If the
882 * initialisation fails (example: out of memory error), the lua function
883 * throws an error (longjmp).
884 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100885 * In some case (at least one), this function can be called from safe
886 * environement, so we must not initialise it. While the support of
887 * threads appear, the safe environment set a lock to ensure only one
888 * Lua execution at a time. If we initialize safe environment in another
889 * safe environmenet, we have a dead lock.
890 *
891 * set "already_safe" true if the context is initialized form safe
892 * Lua fonction.
893 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800894 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200895 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800896 * MUST NOT manipulate the created thread stack state, because it is not
897 * proctected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100898 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100899int hlua_ctx_init(struct hlua *lua, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100900{
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100901 if (!already_safe) {
902 if (!SET_SAFE_LJMP(gL.T)) {
903 lua->Tref = LUA_REFNIL;
904 return 0;
905 }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200906 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100907 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100908 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +0100909 lua->gc_count = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100910 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100911 lua->T = lua_newthread(gL.T);
912 if (!lua->T) {
913 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100914 if (!already_safe)
915 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100916 return 0;
917 }
918 hlua_sethlua(lua);
919 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
920 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100921 if (!already_safe)
922 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100923 return 1;
924}
925
Willy Tarreau87b09662015-04-03 00:22:06 +0200926/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100927 * is destroyed. The destroy also the memory context. The struct "lua"
928 * is not freed.
929 */
930void hlua_ctx_destroy(struct hlua *lua)
931{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100932 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100933 return;
934
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100935 if (!lua->T)
936 goto end;
937
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100938 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200939 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100940
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200941 if (!SET_SAFE_LJMP(lua->T))
942 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100943 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200944 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200945
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200946 if (!SET_SAFE_LJMP(gL.T))
947 return;
948 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
949 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200950 /* Forces a garbage collecting process. If the Lua program is finished
951 * without error, we run the GC on the thread pointer. Its freed all
952 * the unused memory.
953 * If the thread is finnish with an error or is currently yielded,
954 * it seems that the GC applied on the thread doesn't clean anything,
955 * so e run the GC on the main thread.
956 * NOTE: maybe this action locks all the Lua threads untiml the en of
957 * the garbage collection.
958 */
Willy Tarreauf31af932020-01-14 09:59:38 +0100959 if (lua->gc_count) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200960 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200961 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200962 lua_gc(gL.T, LUA_GCCOLLECT, 0);
963 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200964 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200965
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200966 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100967
968end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100969 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100970}
971
972/* This function is used to restore the Lua context when a coroutine
973 * fails. This function copy the common memory between old coroutine
974 * and the new coroutine. The old coroutine is destroyed, and its
975 * replaced by the new coroutine.
976 * If the flag "keep_msg" is set, the last entry of the old is assumed
977 * as string error message and it is copied in the new stack.
978 */
979static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
980{
981 lua_State *T;
982 int new_ref;
983
984 /* Renew the main LUA stack doesn't have sense. */
985 if (lua == &gL)
986 return 0;
987
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100988 /* New Lua coroutine. */
989 T = lua_newthread(gL.T);
990 if (!T)
991 return 0;
992
993 /* Copy last error message. */
994 if (keep_msg)
995 lua_xmove(lua->T, T, 1);
996
997 /* Copy data between the coroutines. */
998 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
999 lua_xmove(lua->T, T, 1);
1000 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
1001
1002 /* Destroy old data. */
1003 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1004
1005 /* The thread is garbage collected by Lua. */
1006 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1007
1008 /* Fill the struct with the new coroutine values. */
1009 lua->Mref = new_ref;
1010 lua->T = T;
1011 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1012
1013 /* Set context. */
1014 hlua_sethlua(lua);
1015
1016 return 1;
1017}
1018
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001019void hlua_hook(lua_State *L, lua_Debug *ar)
1020{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001021 struct hlua *hlua = hlua_gethlua(L);
1022
1023 /* Lua cannot yield when its returning from a function,
1024 * so, we can fix the interrupt hook to 1 instruction,
1025 * expecting that the function is finnished.
1026 */
1027 if (lua_gethookmask(L) & LUA_MASKRET) {
1028 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1029 return;
1030 }
1031
1032 /* restore the interrupt condition. */
1033 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1034
1035 /* If we interrupt the Lua processing in yieldable state, we yield.
1036 * If the state is not yieldable, trying yield causes an error.
1037 */
1038 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001039 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001040
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001041 /* If we cannot yield, update the clock and check the timeout. */
1042 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001043 hlua->run_time += now_ms - hlua->start_time;
1044 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001045 lua_pushfstring(L, "execution timeout");
1046 WILL_LJMP(lua_error(L));
1047 }
1048
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001049 /* Update the start time. */
1050 hlua->start_time = now_ms;
1051
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001052 /* Try to interrupt the process at the end of the current
1053 * unyieldable function.
1054 */
1055 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001056}
1057
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001058/* This function start or resumes the Lua stack execution. If the flag
1059 * "yield_allowed" if no set and the LUA stack execution returns a yield
1060 * The function return an error.
1061 *
1062 * The function can returns 4 values:
1063 * - HLUA_E_OK : The execution is terminated without any errors.
1064 * - HLUA_E_AGAIN : The execution must continue at the next associated
1065 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001066 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001067 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001068 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001069 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001070 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001071 * LUA code.
1072 */
1073static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1074{
1075 int ret;
1076 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001077 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001078
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001079 /* Initialise run time counter. */
1080 if (!HLUA_IS_RUNNING(lua))
1081 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001082
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001083 /* Lock the whole Lua execution. This lock must be before the
1084 * label "resume_execution".
1085 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001086 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001087
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001088resume_execution:
1089
1090 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1091 * instructions. it is used for preventing infinite loops.
1092 */
1093 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1094
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001095 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001096 HLUA_SET_RUN(lua);
1097 HLUA_CLR_CTRLYIELD(lua);
1098 HLUA_CLR_WAKERESWR(lua);
1099 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001100
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001101 /* Update the start time. */
1102 lua->start_time = now_ms;
1103
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001104 /* Call the function. */
1105 ret = lua_resume(lua->T, gL.T, lua->nargs);
1106 switch (ret) {
1107
1108 case LUA_OK:
1109 ret = HLUA_E_OK;
1110 break;
1111
1112 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001113 /* Check if the execution timeout is expired. It it is the case, we
1114 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001115 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001116 tv_update_date(0, 1);
1117 lua->run_time += now_ms - lua->start_time;
1118 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001119 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001120 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001121 break;
1122 }
1123 /* Process the forced yield. if the general yield is not allowed or
1124 * if no task were associated this the current Lua execution
1125 * coroutine, we resume the execution. Else we want to return in the
1126 * scheduler and we want to be waked up again, to continue the
1127 * current Lua execution. So we schedule our own task.
1128 */
1129 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001130 if (!yield_allowed || !lua->task)
1131 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001132 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001133 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001134 if (!yield_allowed) {
1135 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001136 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001137 break;
1138 }
1139 ret = HLUA_E_AGAIN;
1140 break;
1141
1142 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001143
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001144 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001145 * because the errors ares the only one mean to return immediately
1146 * from and lua execution.
1147 */
1148 if (lua->flags & HLUA_EXIT) {
1149 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001150 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001151 break;
1152 }
1153
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001154 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001155 if (!lua_checkstack(lua->T, 1)) {
1156 ret = HLUA_E_ERR;
1157 break;
1158 }
1159 msg = lua_tostring(lua->T, -1);
1160 lua_settop(lua->T, 0); /* Empty the stack. */
1161 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001162 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001163 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001164 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001165 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001166 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001167 ret = HLUA_E_ERRMSG;
1168 break;
1169
1170 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001171 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001172 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001173 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001174 break;
1175
1176 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001177 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001178 if (!lua_checkstack(lua->T, 1)) {
1179 ret = HLUA_E_ERR;
1180 break;
1181 }
1182 msg = lua_tostring(lua->T, -1);
1183 lua_settop(lua->T, 0); /* Empty the stack. */
1184 lua_pop(lua->T, 1);
1185 if (msg)
1186 lua_pushfstring(lua->T, "message handler error: %s", msg);
1187 else
1188 lua_pushfstring(lua->T, "message handler error");
1189 ret = HLUA_E_ERRMSG;
1190 break;
1191
1192 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001193 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001194 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001195 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001196 break;
1197 }
1198
1199 switch (ret) {
1200 case HLUA_E_AGAIN:
1201 break;
1202
1203 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001204 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001205 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001206 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001207 break;
1208
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001209 case HLUA_E_ETMOUT:
1210 case HLUA_E_NOMEM:
1211 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001212 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001213 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001214 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001215 hlua_ctx_renew(lua, 0);
1216 break;
1217
1218 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001219 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001220 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001221 break;
1222 }
1223
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001224 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001225 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001226
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001227 return ret;
1228}
1229
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001230/* This function exit the current code. */
1231__LJMP static int hlua_done(lua_State *L)
1232{
1233 struct hlua *hlua = hlua_gethlua(L);
1234
1235 hlua->flags |= HLUA_EXIT;
1236 WILL_LJMP(lua_error(L));
1237
1238 return 0;
1239}
1240
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001241/* This function is an LUA binding. It provides a function
1242 * for deleting ACL from a referenced ACL file.
1243 */
1244__LJMP static int hlua_del_acl(lua_State *L)
1245{
1246 const char *name;
1247 const char *key;
1248 struct pat_ref *ref;
1249
1250 MAY_LJMP(check_args(L, 2, "del_acl"));
1251
1252 name = MAY_LJMP(luaL_checkstring(L, 1));
1253 key = MAY_LJMP(luaL_checkstring(L, 2));
1254
1255 ref = pat_ref_lookup(name);
1256 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001257 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001258
1259 pat_ref_delete(ref, key);
1260 return 0;
1261}
1262
1263/* This function is an LUA binding. It provides a function
1264 * for deleting map entry from a referenced map file.
1265 */
1266static int hlua_del_map(lua_State *L)
1267{
1268 const char *name;
1269 const char *key;
1270 struct pat_ref *ref;
1271
1272 MAY_LJMP(check_args(L, 2, "del_map"));
1273
1274 name = MAY_LJMP(luaL_checkstring(L, 1));
1275 key = MAY_LJMP(luaL_checkstring(L, 2));
1276
1277 ref = pat_ref_lookup(name);
1278 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001279 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001280
1281 pat_ref_delete(ref, key);
1282 return 0;
1283}
1284
1285/* This function is an LUA binding. It provides a function
1286 * for adding ACL pattern from a referenced ACL file.
1287 */
1288static int hlua_add_acl(lua_State *L)
1289{
1290 const char *name;
1291 const char *key;
1292 struct pat_ref *ref;
1293
1294 MAY_LJMP(check_args(L, 2, "add_acl"));
1295
1296 name = MAY_LJMP(luaL_checkstring(L, 1));
1297 key = MAY_LJMP(luaL_checkstring(L, 2));
1298
1299 ref = pat_ref_lookup(name);
1300 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001301 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001302
1303 if (pat_ref_find_elt(ref, key) == NULL)
1304 pat_ref_add(ref, key, NULL, NULL);
1305 return 0;
1306}
1307
1308/* This function is an LUA binding. It provides a function
1309 * for setting map pattern and sample from a referenced map
1310 * file.
1311 */
1312static int hlua_set_map(lua_State *L)
1313{
1314 const char *name;
1315 const char *key;
1316 const char *value;
1317 struct pat_ref *ref;
1318
1319 MAY_LJMP(check_args(L, 3, "set_map"));
1320
1321 name = MAY_LJMP(luaL_checkstring(L, 1));
1322 key = MAY_LJMP(luaL_checkstring(L, 2));
1323 value = MAY_LJMP(luaL_checkstring(L, 3));
1324
1325 ref = pat_ref_lookup(name);
1326 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001327 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001328
1329 if (pat_ref_find_elt(ref, key) != NULL)
1330 pat_ref_set(ref, key, value, NULL);
1331 else
1332 pat_ref_add(ref, key, value, NULL);
1333 return 0;
1334}
1335
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001336/* A class is a lot of memory that contain data. This data can be a table,
1337 * an integer or user data. This data is associated with a metatable. This
1338 * metatable have an original version registred in the global context with
1339 * the name of the object (_G[<name>] = <metable> ).
1340 *
1341 * A metable is a table that modify the standard behavior of a standard
1342 * access to the associated data. The entries of this new metatable are
1343 * defined as is:
1344 *
1345 * http://lua-users.org/wiki/MetatableEvents
1346 *
1347 * __index
1348 *
1349 * we access an absent field in a table, the result is nil. This is
1350 * true, but it is not the whole truth. Actually, such access triggers
1351 * the interpreter to look for an __index metamethod: If there is no
1352 * such method, as usually happens, then the access results in nil;
1353 * otherwise, the metamethod will provide the result.
1354 *
1355 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1356 * the key does not appear in the table, but the metatable has an __index
1357 * property:
1358 *
1359 * - if the value is a function, the function is called, passing in the
1360 * table and the key; the return value of that function is returned as
1361 * the result.
1362 *
1363 * - if the value is another table, the value of the key in that table is
1364 * asked for and returned (and if it doesn't exist in that table, but that
1365 * table's metatable has an __index property, then it continues on up)
1366 *
1367 * - Use "rawget(myTable,key)" to skip this metamethod.
1368 *
1369 * http://www.lua.org/pil/13.4.1.html
1370 *
1371 * __newindex
1372 *
1373 * Like __index, but control property assignment.
1374 *
1375 * __mode - Control weak references. A string value with one or both
1376 * of the characters 'k' and 'v' which specifies that the the
1377 * keys and/or values in the table are weak references.
1378 *
1379 * __call - Treat a table like a function. When a table is followed by
1380 * parenthesis such as "myTable( 'foo' )" and the metatable has
1381 * a __call key pointing to a function, that function is invoked
1382 * (passing any specified arguments) and the return value is
1383 * returned.
1384 *
1385 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1386 * called, if the metatable for myTable has a __metatable
1387 * key, the value of that key is returned instead of the
1388 * actual metatable.
1389 *
1390 * __tostring - Control string representation. When the builtin
1391 * "tostring( myTable )" function is called, if the metatable
1392 * for myTable has a __tostring property set to a function,
1393 * that function is invoked (passing myTable to it) and the
1394 * return value is used as the string representation.
1395 *
1396 * __len - Control table length. When the table length is requested using
1397 * the length operator ( '#' ), if the metatable for myTable has
1398 * a __len key pointing to a function, that function is invoked
1399 * (passing myTable to it) and the return value used as the value
1400 * of "#myTable".
1401 *
1402 * __gc - Userdata finalizer code. When userdata is set to be garbage
1403 * collected, if the metatable has a __gc field pointing to a
1404 * function, that function is first invoked, passing the userdata
1405 * to it. The __gc metamethod is not called for tables.
1406 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1407 *
1408 * Special metamethods for redefining standard operators:
1409 * http://www.lua.org/pil/13.1.html
1410 *
1411 * __add "+"
1412 * __sub "-"
1413 * __mul "*"
1414 * __div "/"
1415 * __unm "!"
1416 * __pow "^"
1417 * __concat ".."
1418 *
1419 * Special methods for redfining standar relations
1420 * http://www.lua.org/pil/13.2.html
1421 *
1422 * __eq "=="
1423 * __lt "<"
1424 * __le "<="
1425 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001426
1427/*
1428 *
1429 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001430 * Class Map
1431 *
1432 *
1433 */
1434
1435/* Returns a struct hlua_map if the stack entry "ud" is
1436 * a class session, otherwise it throws an error.
1437 */
1438__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1439{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001440 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001441}
1442
1443/* This function is the map constructor. It don't need
1444 * the class Map object. It creates and return a new Map
1445 * object. It must be called only during "body" or "init"
1446 * context because it process some filesystem accesses.
1447 */
1448__LJMP static int hlua_map_new(struct lua_State *L)
1449{
1450 const char *fn;
1451 int match = PAT_MATCH_STR;
1452 struct sample_conv conv;
1453 const char *file = "";
1454 int line = 0;
1455 lua_Debug ar;
1456 char *err = NULL;
1457 struct arg args[2];
1458
1459 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1460 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1461
1462 fn = MAY_LJMP(luaL_checkstring(L, 1));
1463
1464 if (lua_gettop(L) >= 2) {
1465 match = MAY_LJMP(luaL_checkinteger(L, 2));
1466 if (match < 0 || match >= PAT_MATCH_NUM)
1467 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1468 }
1469
1470 /* Get Lua filename and line number. */
1471 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1472 lua_getinfo(L, "Sl", &ar); /* get info about it */
1473 if (ar.currentline > 0) { /* is there info? */
1474 file = ar.short_src;
1475 line = ar.currentline;
1476 }
1477 }
1478
1479 /* fill fake sample_conv struct. */
1480 conv.kw = ""; /* unused. */
1481 conv.process = NULL; /* unused. */
1482 conv.arg_mask = 0; /* unused. */
1483 conv.val_args = NULL; /* unused. */
1484 conv.out_type = SMP_T_STR;
1485 conv.private = (void *)(long)match;
1486 switch (match) {
1487 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1488 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1489 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1490 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1491 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1492 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1493 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001494 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001495 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1496 default:
1497 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1498 }
1499
1500 /* fill fake args. */
1501 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001502 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001503 args[1].type = ARGT_STOP;
1504
1505 /* load the map. */
1506 if (!sample_load_map(args, &conv, file, line, &err)) {
1507 /* error case: we cant use luaL_error because we must
1508 * free the err variable.
1509 */
1510 luaL_where(L, 1);
1511 lua_pushfstring(L, "'new': %s.", err);
1512 lua_concat(L, 2);
1513 free(err);
1514 WILL_LJMP(lua_error(L));
1515 }
1516
1517 /* create the lua object. */
1518 lua_newtable(L);
1519 lua_pushlightuserdata(L, args[0].data.map);
1520 lua_rawseti(L, -2, 0);
1521
1522 /* Pop a class Map metatable and affect it to the userdata. */
1523 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1524 lua_setmetatable(L, -2);
1525
1526
1527 return 1;
1528}
1529
1530__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1531{
1532 struct map_descriptor *desc;
1533 struct pattern *pat;
1534 struct sample smp;
1535
1536 MAY_LJMP(check_args(L, 2, "lookup"));
1537 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001538 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001539 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001540 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001541 }
1542 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001543 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001544 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001545 smp.data.u.str.area = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.data));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001546 }
1547
1548 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001549 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001550 if (str)
1551 lua_pushstring(L, "");
1552 else
1553 lua_pushnil(L);
1554 return 1;
1555 }
1556
1557 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001558 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001559 return 1;
1560}
1561
1562__LJMP static int hlua_map_lookup(struct lua_State *L)
1563{
1564 return _hlua_map_lookup(L, 0);
1565}
1566
1567__LJMP static int hlua_map_slookup(struct lua_State *L)
1568{
1569 return _hlua_map_lookup(L, 1);
1570}
1571
1572/*
1573 *
1574 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001575 * Class Socket
1576 *
1577 *
1578 */
1579
1580__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1581{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001582 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001583}
1584
1585/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001586 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001587 * received.
1588 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001589static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001591 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001592
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001593 if (appctx->ctx.hlua_cosocket.die) {
1594 si_shutw(si);
1595 si_shutr(si);
1596 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001597 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1598 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001599 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1600 }
1601
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001602 /* If we cant write, wakeup the pending write signals. */
1603 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001604 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001605
1606 /* If we cant read, wakeup the pending read signals. */
1607 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001608 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001609
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001610 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001611 * to be notified whenever the connection completes.
1612 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001613 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001614 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001615 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001616 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001617 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001618 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619
1620 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001621 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001622
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001623 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001624 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001625 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001626
1627 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001628 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001629 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001630
1631 /* Some data were injected in the buffer, notify the stream
1632 * interface.
1633 */
1634 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001635 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001636
1637 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001638 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001639 */
1640 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001641 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001642}
1643
Willy Tarreau87b09662015-04-03 00:22:06 +02001644/* This function is called when the "struct stream" is destroyed.
1645 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001646 * Wake all the pending signals.
1647 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001648static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001649{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001650 struct xref *peer;
1651
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001652 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001653 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1654 if (peer)
1655 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001656
1657 /* Wake all the task waiting for me. */
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);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001660}
1661
1662/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001663 * uses this object. If the stream does not exists, just quit.
1664 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001665 * pending signal can rest in the read and write lists. destroy
1666 * it.
1667 */
1668__LJMP static int hlua_socket_gc(lua_State *L)
1669{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001670 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001671 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001672 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001674 MAY_LJMP(check_args(L, 1, "__gc"));
1675
1676 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001677 peer = xref_get_peer_and_lock(&socket->xref);
1678 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001679 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001680 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001681
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001682 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001683 appctx->ctx.hlua_cosocket.die = 1;
1684 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001685
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001686 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001687 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001688 return 0;
1689}
1690
1691/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001692 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001693 */
sada05ed3302018-05-11 11:48:18 -07001694__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001696 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001697 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001698 struct xref *peer;
Willy Tarreauf31af932020-01-14 09:59:38 +01001699 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001700
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001701 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001702
1703 /* Check if we run on the same thread than the xreator thread.
1704 * We cannot access to the socket if the thread is different.
1705 */
1706 if (socket->tid != tid)
1707 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1708
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001709 peer = xref_get_peer_and_lock(&socket->xref);
1710 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001712
1713 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001714 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001716 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001717 appctx->ctx.hlua_cosocket.die = 1;
1718 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001719
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001720 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001721 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001722 return 0;
1723}
1724
sada05ed3302018-05-11 11:48:18 -07001725/* The close function calls close_helper.
1726 */
1727__LJMP static int hlua_socket_close(lua_State *L)
1728{
1729 MAY_LJMP(check_args(L, 1, "close"));
1730 return hlua_socket_close_helper(L);
1731}
1732
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001733/* This Lua function assumes that the stack contain three parameters.
1734 * 1 - USERDATA containing a struct socket
1735 * 2 - INTEGER with values of the macro defined below
1736 * If the integer is -1, we must read at most one line.
1737 * If the integer is -2, we ust read all the data until the
1738 * end of the stream.
1739 * If the integer is positive value, we must read a number of
1740 * bytes corresponding to this value.
1741 */
1742#define HLSR_READ_LINE (-1)
1743#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001744__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001745{
1746 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1747 int wanted = lua_tointeger(L, 2);
1748 struct hlua *hlua = hlua_gethlua(L);
1749 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001750 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001751 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001752 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001753 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001754 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001755 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001756 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001757 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001758 struct stream_interface *si;
1759 struct stream *s;
1760 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001761 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001762
1763 /* Check if this lua stack is schedulable. */
1764 if (!hlua || !hlua->task)
1765 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1766 "'frontend', 'backend' or 'task'"));
1767
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001768 /* Check if we run on the same thread than the xreator thread.
1769 * We cannot access to the socket if the thread is different.
1770 */
1771 if (socket->tid != tid)
1772 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1773
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001774 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001775 peer = xref_get_peer_and_lock(&socket->xref);
1776 if (!peer)
1777 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001778 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1779 si = appctx->owner;
1780 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001781
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001782 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001783 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001784 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001785 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001786 if (nblk < 0) /* Connection close. */
1787 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001788 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001789 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001790
1791 /* remove final \r\n. */
1792 if (nblk == 1) {
1793 if (blk1[len1-1] == '\n') {
1794 len1--;
1795 skip_at_end++;
1796 if (blk1[len1-1] == '\r') {
1797 len1--;
1798 skip_at_end++;
1799 }
1800 }
1801 }
1802 else {
1803 if (blk2[len2-1] == '\n') {
1804 len2--;
1805 skip_at_end++;
1806 if (blk2[len2-1] == '\r') {
1807 len2--;
1808 skip_at_end++;
1809 }
1810 }
1811 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001812 }
1813
1814 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001815 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001816 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001817 if (nblk < 0) /* Connection close. */
1818 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001819 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001820 goto connection_empty;
1821 }
1822
1823 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001824 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001825 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001826 if (nblk < 0) /* Connection close. */
1827 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001828 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001829 goto connection_empty;
1830
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001831 missing_bytes = wanted - socket->b.n;
1832 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001833 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001834 len1 = missing_bytes;
1835 } if (nblk == 2 && len1 + len2 > missing_bytes)
1836 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001837 }
1838
1839 len = len1;
1840
1841 luaL_addlstring(&socket->b, blk1, len1);
1842 if (nblk == 2) {
1843 len += len2;
1844 luaL_addlstring(&socket->b, blk2, len2);
1845 }
1846
1847 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001848 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001849
1850 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001851 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001852
1853 /* If the pattern reclaim to read all the data
1854 * in the connection, got out.
1855 */
1856 if (wanted == HLSR_READ_ALL)
1857 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001858 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001859 goto connection_empty;
1860
1861 /* Return result. */
1862 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001863 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001864 return 1;
1865
1866connection_closed:
1867
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001868 xref_unlock(&socket->xref, peer);
1869
1870no_peer:
1871
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001872 /* If the buffer containds data. */
1873 if (socket->b.n > 0) {
1874 luaL_pushresult(&socket->b);
1875 return 1;
1876 }
1877 lua_pushnil(L);
1878 lua_pushstring(L, "connection closed.");
1879 return 2;
1880
1881connection_empty:
1882
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001883 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1884 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001885 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001886 }
1887 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001888 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001889 return 0;
1890}
1891
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001892/* This Lua function gets two parameters. The first one can be string
1893 * or a number. If the string is "*l", the user requires one line. If
1894 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895 * If the value is a number, the user require a number of bytes equal
1896 * to the value. The default value is "*l" (a line).
1897 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001898 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899 * integer takes this values:
1900 * -1 : read a line
1901 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001902 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001903 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001904 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001905 * concatenated with the read data.
1906 */
1907__LJMP static int hlua_socket_receive(struct lua_State *L)
1908{
1909 int wanted = HLSR_READ_LINE;
1910 const char *pattern;
1911 int type;
1912 char *error;
1913 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001914 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001915
1916 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1917 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1918
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001919 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001920
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001921 /* Check if we run on the same thread than the xreator thread.
1922 * We cannot access to the socket if the thread is different.
1923 */
1924 if (socket->tid != tid)
1925 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1926
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001927 /* check for pattern. */
1928 if (lua_gettop(L) >= 2) {
1929 type = lua_type(L, 2);
1930 if (type == LUA_TSTRING) {
1931 pattern = lua_tostring(L, 2);
1932 if (strcmp(pattern, "*a") == 0)
1933 wanted = HLSR_READ_ALL;
1934 else if (strcmp(pattern, "*l") == 0)
1935 wanted = HLSR_READ_LINE;
1936 else {
1937 wanted = strtoll(pattern, &error, 10);
1938 if (*error != '\0')
1939 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1940 }
1941 }
1942 else if (type == LUA_TNUMBER) {
1943 wanted = lua_tointeger(L, 2);
1944 if (wanted < 0)
1945 WILL_LJMP(luaL_error(L, "Unsupported size."));
1946 }
1947 }
1948
1949 /* Set pattern. */
1950 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001951
1952 /* Check if we would replace the top by itself. */
1953 if (lua_gettop(L) != 2)
1954 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001956 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957 luaL_buffinit(L, &socket->b);
1958
1959 /* Check prefix. */
1960 if (lua_gettop(L) >= 3) {
1961 if (lua_type(L, 3) != LUA_TSTRING)
1962 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1963 pattern = lua_tolstring(L, 3, &len);
1964 luaL_addlstring(&socket->b, pattern, len);
1965 }
1966
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001967 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001968}
1969
1970/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001971 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001972 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001973static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974{
1975 struct hlua_socket *socket;
1976 struct hlua *hlua = hlua_gethlua(L);
1977 struct appctx *appctx;
1978 size_t buf_len;
1979 const char *buf;
1980 int len;
1981 int send_len;
1982 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001983 struct xref *peer;
1984 struct stream_interface *si;
1985 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001986
1987 /* Check if this lua stack is schedulable. */
1988 if (!hlua || !hlua->task)
1989 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1990 "'frontend', 'backend' or 'task'"));
1991
1992 /* Get object */
1993 socket = MAY_LJMP(hlua_checksocket(L, 1));
1994 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001995 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001996
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001997 /* Check if we run on the same thread than the xreator thread.
1998 * We cannot access to the socket if the thread is different.
1999 */
2000 if (socket->tid != tid)
2001 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2002
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002003 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002004 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002005 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002006 lua_pushinteger(L, -1);
2007 return 1;
2008 }
2009 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2010 si = appctx->owner;
2011 s = si_strm(si);
2012
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002013 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002014 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002015 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002016 lua_pushinteger(L, -1);
2017 return 1;
2018 }
2019
2020 /* Update the input buffer data. */
2021 buf += sent;
2022 send_len = buf_len - sent;
2023
2024 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002025 if (sent >= buf_len) {
2026 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002027 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002028 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002029
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002030 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002031 * the request buffer if its not required.
2032 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002033 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002034 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002035 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002036 }
2037
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002038 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002039 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002040 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002041 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002042 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043
2044 /* send data */
2045 if (len < send_len)
2046 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002047 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002048
2049 /* "Not enough space" (-1), "Buffer too little to contain
2050 * the data" (-2) are not expected because the available length
2051 * is tested.
2052 * Other unknown error are also not expected.
2053 */
2054 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002055 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002056 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002057
sada05ed3302018-05-11 11:48:18 -07002058 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002059 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002060 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002061 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002062 return 1;
2063 }
2064
2065 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002066 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002067
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002068 s->req.rex = TICK_ETERNITY;
2069 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002070
2071 /* Update length sent. */
2072 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002073 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074
2075 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002076 if (sent + len >= buf_len) {
2077 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002079 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080
2081hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002082 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2083 xref_unlock(&socket->xref, peer);
2084 WILL_LJMP(luaL_error(L, "out of memory"));
2085 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002086 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002087 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088 return 0;
2089}
2090
2091/* This function initiate the send of data. It just check the input
2092 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002093 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002094 * "hlua_socket_write_yield" that can yield.
2095 *
2096 * The Lua function gets between 3 and 4 parameters. The first one is
2097 * the associated object. The second is a string buffer. The third is
2098 * a facultative integer that represents where is the buffer position
2099 * of the start of the data that can send. The first byte is the
2100 * position "1". The default value is "1". The fourth argument is a
2101 * facultative integer that represents where is the buffer position
2102 * of the end of the data that can send. The default is the last byte.
2103 */
2104static int hlua_socket_send(struct lua_State *L)
2105{
2106 int i;
2107 int j;
2108 const char *buf;
2109 size_t buf_len;
2110
2111 /* Check number of arguments. */
2112 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2113 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2114
2115 /* Get the string. */
2116 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2117
2118 /* Get and check j. */
2119 if (lua_gettop(L) == 4) {
2120 j = MAY_LJMP(luaL_checkinteger(L, 4));
2121 if (j < 0)
2122 j = buf_len + j + 1;
2123 if (j > buf_len)
2124 j = buf_len + 1;
2125 lua_pop(L, 1);
2126 }
2127 else
2128 j = buf_len;
2129
2130 /* Get and check i. */
2131 if (lua_gettop(L) == 3) {
2132 i = MAY_LJMP(luaL_checkinteger(L, 3));
2133 if (i < 0)
2134 i = buf_len + i + 1;
2135 if (i > buf_len)
2136 i = buf_len + 1;
2137 lua_pop(L, 1);
2138 } else
2139 i = 1;
2140
2141 /* Check bth i and j. */
2142 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002143 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144 return 1;
2145 }
2146 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002147 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148 return 1;
2149 }
2150 if (i == 0)
2151 i = 1;
2152 if (j == 0)
2153 j = 1;
2154
2155 /* Pop the string. */
2156 lua_pop(L, 1);
2157
2158 /* Update the buffer length. */
2159 buf += i - 1;
2160 buf_len = j - i + 1;
2161 lua_pushlstring(L, buf, buf_len);
2162
2163 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002164 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002166 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167}
2168
Willy Tarreau22b0a682015-06-17 19:43:49 +02002169#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002170__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2171{
2172 static char buffer[SOCKET_INFO_MAX_LEN];
2173 int ret;
2174 int len;
2175 char *p;
2176
2177 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2178 if (ret <= 0) {
2179 lua_pushnil(L);
2180 return 1;
2181 }
2182
2183 if (ret == AF_UNIX) {
2184 lua_pushstring(L, buffer+1);
2185 return 1;
2186 }
2187 else if (ret == AF_INET6) {
2188 buffer[0] = '[';
2189 len = strlen(buffer);
2190 buffer[len] = ']';
2191 len++;
2192 buffer[len] = ':';
2193 len++;
2194 p = buffer;
2195 }
2196 else if (ret == AF_INET) {
2197 p = buffer + 1;
2198 len = strlen(p);
2199 p[len] = ':';
2200 len++;
2201 }
2202 else {
2203 lua_pushnil(L);
2204 return 1;
2205 }
2206
2207 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2208 lua_pushnil(L);
2209 return 1;
2210 }
2211
2212 lua_pushstring(L, p);
2213 return 1;
2214}
2215
2216/* Returns information about the peer of the connection. */
2217__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2218{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002219 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002220 struct xref *peer;
2221 struct appctx *appctx;
2222 struct stream_interface *si;
2223 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002224 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002225
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 MAY_LJMP(check_args(L, 1, "getpeername"));
2227
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002228 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002230 /* Check if we run on the same thread than the xreator thread.
2231 * We cannot access to the socket if the thread is different.
2232 */
2233 if (socket->tid != tid)
2234 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2235
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002236 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002237 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002238 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239 lua_pushnil(L);
2240 return 1;
2241 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002242 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2243 si = appctx->owner;
2244 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002246 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002247 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002248 lua_pushnil(L);
2249 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002250 }
2251
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002252 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002253 xref_unlock(&socket->xref, peer);
2254 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255}
2256
2257/* Returns information about my connection side. */
2258static int hlua_socket_getsockname(struct lua_State *L)
2259{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002260 struct hlua_socket *socket;
2261 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002262 struct appctx *appctx;
2263 struct xref *peer;
2264 struct stream_interface *si;
2265 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002266 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002267
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002268 MAY_LJMP(check_args(L, 1, "getsockname"));
2269
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002270 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002272 /* Check if we run on the same thread than the xreator thread.
2273 * We cannot access to the socket if the thread is different.
2274 */
2275 if (socket->tid != tid)
2276 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2277
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002278 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002279 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002280 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281 lua_pushnil(L);
2282 return 1;
2283 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002284 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2285 si = appctx->owner;
2286 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002288 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002289 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002290 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291 lua_pushnil(L);
2292 return 1;
2293 }
2294
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002295 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002296 xref_unlock(&socket->xref, peer);
2297 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298}
2299
2300/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002301static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302 .obj_type = OBJ_TYPE_APPLET,
2303 .name = "<LUA_TCP>",
2304 .fct = hlua_socket_handler,
2305 .release = hlua_socket_release,
2306};
2307
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002308__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309{
2310 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2311 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002312 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002314 struct stream_interface *si;
2315 struct stream *s;
2316
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002317 /* Check if we run on the same thread than the xreator thread.
2318 * We cannot access to the socket if the thread is different.
2319 */
2320 if (socket->tid != tid)
2321 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2322
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002323 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002324 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002325 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002326 lua_pushnil(L);
2327 lua_pushstring(L, "Can't connect");
2328 return 2;
2329 }
2330 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2331 si = appctx->owner;
2332 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002334 /* Check if we run on the same thread than the xreator thread.
2335 * We cannot access to the socket if the thread is different.
2336 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002337 if (socket->tid != tid) {
2338 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002339 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002340 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002341
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002343 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002344 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345 lua_pushnil(L);
2346 lua_pushstring(L, "Can't connect");
2347 return 2;
2348 }
2349
Willy Tarreaue09101e2018-10-16 17:37:12 +02002350 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351
2352 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002353 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002354 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002355 lua_pushinteger(L, 1);
2356 return 1;
2357 }
2358
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002359 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2360 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002362 }
2363 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002364 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365 return 0;
2366}
2367
2368/* This function fail or initite the connection. */
2369__LJMP static int hlua_socket_connect(struct lua_State *L)
2370{
2371 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002372 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002374 struct hlua *hlua;
2375 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002376 int low, high;
2377 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002378 struct xref *peer;
2379 struct stream_interface *si;
2380 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002381
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002382 if (lua_gettop(L) < 2)
2383 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384
2385 /* Get args. */
2386 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002387
2388 /* Check if we run on the same thread than the xreator thread.
2389 * We cannot access to the socket if the thread is different.
2390 */
2391 if (socket->tid != tid)
2392 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2393
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002395 if (lua_gettop(L) >= 3) {
2396 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002397 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002398
Tim Duesterhus6edab862018-01-06 19:04:45 +01002399 /* Force the ip to end with a colon, to support IPv6 addresses
2400 * that are not enclosed within square brackets.
2401 */
2402 if (port > 0) {
2403 luaL_buffinit(L, &b);
2404 luaL_addstring(&b, ip);
2405 luaL_addchar(&b, ':');
2406 luaL_pushresult(&b);
2407 ip = lua_tolstring(L, lua_gettop(L), NULL);
2408 }
2409 }
2410
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002411 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002412 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002413 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002414 lua_pushnil(L);
2415 return 1;
2416 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417
2418 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002419 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002420 if (!addr) {
2421 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002422 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002423 }
2424 if (low != high) {
2425 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002426 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002427 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002428
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002429 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002430 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002431 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002432 if (port == -1) {
2433 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002434 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002435 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002436 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2437 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002438 if (port == -1) {
2439 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002440 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002441 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002442 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002443 }
2444 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002445
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002446 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2447 si = appctx->owner;
2448 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002449
2450 if (!sockaddr_alloc(&s->target_addr)) {
2451 xref_unlock(&socket->xref, peer);
2452 WILL_LJMP(luaL_error(L, "connect: internal error"));
2453 }
2454 *s->target_addr = *addr;
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002455 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002456
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002457 hlua = hlua_gethlua(L);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002458
2459 /* inform the stream that we want to be notified whenever the
2460 * connection completes.
2461 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002462 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002463 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002464 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002465
Willy Tarreauf31af932020-01-14 09:59:38 +01002466 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002467
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002468 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2469 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002470 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002471 }
2472 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002473
2474 task_wakeup(s->task, TASK_WOKEN_INIT);
2475 /* Return yield waiting for connection. */
2476
Willy Tarreau9635e032018-10-16 17:52:55 +02002477 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002478
2479 return 0;
2480}
2481
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002482#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002483__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2484{
2485 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002486 struct xref *peer;
2487 struct appctx *appctx;
2488 struct stream_interface *si;
2489 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002490
2491 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2492 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002493
2494 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002495 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002496 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002497 lua_pushnil(L);
2498 return 1;
2499 }
2500 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2501 si = appctx->owner;
2502 s = si_strm(si);
2503
2504 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002505 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506 return MAY_LJMP(hlua_socket_connect(L));
2507}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002508#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509
2510__LJMP static int hlua_socket_setoption(struct lua_State *L)
2511{
2512 return 0;
2513}
2514
2515__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2516{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002517 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002518 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002519 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002520 struct xref *peer;
2521 struct appctx *appctx;
2522 struct stream_interface *si;
2523 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002524
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 MAY_LJMP(check_args(L, 2, "settimeout"));
2526
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002527 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002528
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002529 /* convert the timeout to millis */
2530 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002531
Thierry Fournier17a921b2018-03-08 09:59:02 +01002532 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002533 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002534 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2535
Mark Lakes56cc1252018-03-27 09:48:06 +02002536 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002537 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002538
2539 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002540 if (tmout == 0)
2541 tmout++; /* very small timeouts are adjusted to a minium of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002542
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002543 /* Check if we run on the same thread than the xreator thread.
2544 * We cannot access to the socket if the thread is different.
2545 */
2546 if (socket->tid != tid)
2547 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2548
Mark Lakes56cc1252018-03-27 09:48:06 +02002549 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002550 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002551 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002552 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2553 WILL_LJMP(lua_error(L));
2554 return 0;
2555 }
2556 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2557 si = appctx->owner;
2558 s = si_strm(si);
2559
Cyril Bonté7bb63452018-08-17 23:51:02 +02002560 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002561 s->req.rto = tmout;
2562 s->req.wto = tmout;
2563 s->res.rto = tmout;
2564 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002565 s->req.rex = tick_add_ifset(now_ms, tmout);
2566 s->req.wex = tick_add_ifset(now_ms, tmout);
2567 s->res.rex = tick_add_ifset(now_ms, tmout);
2568 s->res.wex = tick_add_ifset(now_ms, tmout);
2569
2570 s->task->expire = tick_add_ifset(now_ms, tmout);
2571 task_queue(s->task);
2572
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002573 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002574
Thierry Fourniere9636f12018-03-08 09:54:32 +01002575 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002576 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002577}
2578
2579__LJMP static int hlua_socket_new(lua_State *L)
2580{
2581 struct hlua_socket *socket;
2582 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002583 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002584 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585
2586 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002587 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002588 hlua_pusherror(L, "socket: full stack");
2589 goto out_fail_conf;
2590 }
2591
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002592 /* Create the object: obj[0] = userdata. */
2593 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002595 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002596 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002597 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002598
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002599 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002600 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002601 hlua_pusherror(L, "socket: uninitialized pools.");
2602 goto out_fail_conf;
2603 }
2604
Willy Tarreau87b09662015-04-03 00:22:06 +02002605 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002606 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2607 lua_setmetatable(L, -2);
2608
Willy Tarreaud420a972015-04-06 00:39:18 +02002609 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002610 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002611 if (!appctx) {
2612 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002613 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002614 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002615
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002616 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002617 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002618 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2619 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002620
Willy Tarreaud420a972015-04-06 00:39:18 +02002621 /* Now create a session, task and stream for this applet */
2622 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2623 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002624 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002625 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002626 }
2627
Willy Tarreau87787ac2017-08-28 16:22:54 +02002628 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002629 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002630 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002631 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632 }
2633
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002634 /* Initialise cross reference between stream and Lua socket object. */
2635 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002636
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002637 /* Configure "right" stream interface. this "si" is used to connect
2638 * and retrieve data from the server. The connection is initialized
2639 * with the "struct server".
2640 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002641 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002642
2643 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002644 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002645 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002646
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647 return 1;
2648
Willy Tarreaud420a972015-04-06 00:39:18 +02002649 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002650 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002651 out_fail_sess:
2652 appctx_free(appctx);
2653 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002654 WILL_LJMP(lua_error(L));
2655 return 0;
2656}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002657
2658/*
2659 *
2660 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002661 * Class Channel
2662 *
2663 *
2664 */
2665
2666/* Returns the struct hlua_channel join to the class channel in the
2667 * stack entry "ud" or throws an argument error.
2668 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002669__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002670{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002671 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672}
2673
Willy Tarreau47860ed2015-03-10 14:07:50 +01002674/* Pushes the channel onto the top of the stack. If the stask does not have a
2675 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002676 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002677static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002679 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002680 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681 return 0;
2682
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002683 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002684 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002685 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002686
2687 /* Pop a class sesison metatable and affect it to the userdata. */
2688 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2689 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002690 return 1;
2691}
2692
2693/* Duplicate all the data present in the input channel and put it
2694 * in a string LUA variables. Returns -1 and push a nil value in
2695 * the stack if the channel is closed and all the data are consumed,
2696 * returns 0 if no data are available, otherwise it returns the length
2697 * of the builded string.
2698 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002699static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700{
2701 char *blk1;
2702 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002703 size_t len1;
2704 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002705 int ret;
2706 luaL_Buffer b;
2707
Willy Tarreau06d80a92017-10-19 14:32:15 +02002708 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002709 if (unlikely(ret == 0))
2710 return 0;
2711
2712 if (unlikely(ret < 0)) {
2713 lua_pushnil(L);
2714 return -1;
2715 }
2716
2717 luaL_buffinit(L, &b);
2718 luaL_addlstring(&b, blk1, len1);
2719 if (unlikely(ret == 2))
2720 luaL_addlstring(&b, blk2, len2);
2721 luaL_pushresult(&b);
2722
2723 if (unlikely(ret == 2))
2724 return len1 + len2;
2725 return len1;
2726}
2727
2728/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2729 * a yield. This function keep the data in the buffer.
2730 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002731__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002732{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002733 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002734
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002735 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2736
Christopher Faulet3f829a42018-12-13 21:56:45 +01002737 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2738 WILL_LJMP(lua_error(L));
2739
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002741 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002742 return 1;
2743}
2744
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002745/* Check arguments for the function "hlua_channel_dup_yield". */
2746__LJMP static int hlua_channel_dup(lua_State *L)
2747{
2748 MAY_LJMP(check_args(L, 1, "dup"));
2749 MAY_LJMP(hlua_checkchannel(L, 1));
2750 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2751}
2752
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002753/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2754 * a yield. This function consumes the data in the buffer. It returns
2755 * a string containing the data or a nil pointer if no data are available
2756 * and the channel is closed.
2757 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002758__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002759{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002760 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002761 int ret;
2762
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002763 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002764
Christopher Faulet3f829a42018-12-13 21:56:45 +01002765 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2766 WILL_LJMP(lua_error(L));
2767
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002768 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002769 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002770 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002771
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772 if (unlikely(ret == -1))
2773 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002774
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002775 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002776 return 1;
2777}
2778
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002779/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002780__LJMP static int hlua_channel_get(lua_State *L)
2781{
2782 MAY_LJMP(check_args(L, 1, "get"));
2783 MAY_LJMP(hlua_checkchannel(L, 1));
2784 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2785}
2786
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787/* This functions consumes and returns one line. If the channel is closed,
2788 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002789 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002790 * value.
2791 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002792__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002793{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794 char *blk1;
2795 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002796 size_t len1;
2797 size_t len2;
2798 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002799 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002800 int ret;
2801 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002802
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002803 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2804
Christopher Faulet3f829a42018-12-13 21:56:45 +01002805 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2806 WILL_LJMP(lua_error(L));
2807
Willy Tarreau06d80a92017-10-19 14:32:15 +02002808 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002809 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002810 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002811
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002812 if (ret == -1) {
2813 lua_pushnil(L);
2814 return 1;
2815 }
2816
2817 luaL_buffinit(L, &b);
2818 luaL_addlstring(&b, blk1, len1);
2819 len = len1;
2820 if (unlikely(ret == 2)) {
2821 luaL_addlstring(&b, blk2, len2);
2822 len += len2;
2823 }
2824 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002825 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826 return 1;
2827}
2828
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002829/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002830__LJMP static int hlua_channel_getline(lua_State *L)
2831{
2832 MAY_LJMP(check_args(L, 1, "getline"));
2833 MAY_LJMP(hlua_checkchannel(L, 1));
2834 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2835}
2836
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002837/* This function takes a string as input, and append it at the
2838 * input side of channel. If the data is too big, but a space
2839 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002840 * yields. If the data is bigger than the buffer, or if the
2841 * channel is closed, it returns -1. Otherwise, it returns the
2842 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002843 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002844__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002845{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002846 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002847 size_t len;
2848 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2849 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2850 int ret;
2851 int max;
2852
Christopher Faulet3f829a42018-12-13 21:56:45 +01002853 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2854 WILL_LJMP(lua_error(L));
2855
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002856 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002857 * the request buffer if its not required.
2858 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002859 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002860 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002861 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002862 }
2863
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002864 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865 if (max > len - l)
2866 max = len - l;
2867
Willy Tarreau06d80a92017-10-19 14:32:15 +02002868 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002869 if (ret == -2 || ret == -3) {
2870 lua_pushinteger(L, -1);
2871 return 1;
2872 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002873 if (ret == -1) {
2874 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02002875 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002876 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877 l += ret;
2878 lua_pop(L, 1);
2879 lua_pushinteger(L, l);
2880
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002881 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002882 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002883 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002884 * in this case, we cannot add more data, so we cannot yield,
2885 * we return the amount of copyied data.
2886 */
2887 return 1;
2888 }
2889 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02002890 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002891 return 1;
2892}
2893
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002894/* Just a wrapper of "hlua_channel_append_yield". It returns the length
2895 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002896 * buffer size is too little for the data.
2897 */
2898__LJMP static int hlua_channel_append(lua_State *L)
2899{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002900 size_t len;
2901
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002902 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002903 MAY_LJMP(hlua_checkchannel(L, 1));
2904 MAY_LJMP(luaL_checklstring(L, 2, &len));
2905 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002906 lua_pushinteger(L, 0);
2907
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002908 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002909}
2910
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002911/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002912 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002913 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002914 * or -1 if the channel is closed or if the buffer size is too
2915 * little for the data.
2916 */
2917__LJMP static int hlua_channel_set(lua_State *L)
2918{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002919 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002920
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002921 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002922 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002923 lua_pushinteger(L, 0);
2924
Christopher Faulet3f829a42018-12-13 21:56:45 +01002925 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2926 WILL_LJMP(lua_error(L));
2927
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002928 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002929
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002930 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002931}
2932
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002933/* Append data in the output side of the buffer. This data is immediately
2934 * sent. The function returns the amount of data written. If the buffer
2935 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002936 * if the channel is closed.
2937 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002938__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002939{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002940 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002941 size_t len;
2942 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2943 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2944 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002945 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002946
Christopher Faulet3f829a42018-12-13 21:56:45 +01002947 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2948 WILL_LJMP(lua_error(L));
2949
Willy Tarreau47860ed2015-03-10 14:07:50 +01002950 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002951 lua_pushinteger(L, -1);
2952 return 1;
2953 }
2954
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002955 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002956 * the request buffer if its not required.
2957 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002958 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002959 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002960 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002961 }
2962
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002963 /* The written data will be immediately sent, so we can check
2964 * the available space without taking in account the reserve.
2965 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002966 * data, because the buffer will be flushed.
2967 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002968 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002969
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002970 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002971 * in this case, we cannot add more data, so we cannot yield,
2972 * we return the amount of copyied data.
2973 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02002974 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002975 return 1;
2976
2977 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002978 if (max > len - l)
2979 max = len - l;
2980
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002981 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002982 * detects a non contiguous buffer and realign it.
2983 */
Willy Tarreau3f679992018-06-15 15:06:42 +02002984 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002985 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002986
2987 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002988 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002989
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002990 /* buffer replace considers that the input part is filled.
2991 * so, I must forward these new data in the output part.
2992 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02002993 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002994
2995 l += max;
2996 lua_pop(L, 1);
2997 lua_pushinteger(L, l);
2998
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002999 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003000 * in this case, we cannot add more data, so we cannot yield,
3001 * we return the amount of copyied data.
3002 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003003 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003004 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003005 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003006
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003007 if (l < len) {
3008 /* If we are waiting for space in the response buffer, we
3009 * must set the flag WAKERESWR. This flag required the task
3010 * wake up if any activity is detected on the response buffer.
3011 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003012 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003013 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003014 else
3015 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003016 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003017 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003018
3019 return 1;
3020}
3021
3022/* Just a wraper of "_hlua_channel_send". This wrapper permits
3023 * yield the LUA process, and resume it without checking the
3024 * input arguments.
3025 */
3026__LJMP static int hlua_channel_send(lua_State *L)
3027{
3028 MAY_LJMP(check_args(L, 2, "send"));
3029 lua_pushinteger(L, 0);
3030
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003031 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003032}
3033
3034/* This function forward and amount of butes. The data pass from
3035 * the input side of the buffer to the output side, and can be
3036 * forwarded. This function never fails.
3037 *
3038 * The Lua function takes an amount of bytes to be forwarded in
3039 * imput. It returns the number of bytes forwarded.
3040 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003041__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003042{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003043 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003044 int len;
3045 int l;
3046 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003047 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048
3049 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003050
3051 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3052 WILL_LJMP(lua_error(L));
3053
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003054 len = MAY_LJMP(luaL_checkinteger(L, 2));
3055 l = MAY_LJMP(luaL_checkinteger(L, -1));
3056
3057 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003058 if (max > ci_data(chn))
3059 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003060 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003061 l += max;
3062
3063 lua_pop(L, 1);
3064 lua_pushinteger(L, l);
3065
3066 /* Check if it miss bytes to forward. */
3067 if (l < len) {
3068 /* The the input channel or the output channel are closed, we
3069 * must return the amount of data forwarded.
3070 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003071 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003072 return 1;
3073
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003074 /* If we are waiting for space data in the response buffer, we
3075 * must set the flag WAKERESWR. This flag required the task
3076 * wake up if any activity is detected on the response buffer.
3077 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003078 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003079 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003080 else
3081 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003082
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003083 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003084 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085 }
3086
3087 return 1;
3088}
3089
3090/* Just check the input and prepare the stack for the previous
3091 * function "hlua_channel_forward_yield"
3092 */
3093__LJMP static int hlua_channel_forward(lua_State *L)
3094{
3095 MAY_LJMP(check_args(L, 2, "forward"));
3096 MAY_LJMP(hlua_checkchannel(L, 1));
3097 MAY_LJMP(luaL_checkinteger(L, 2));
3098
3099 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003100 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003101}
3102
3103/* Just returns the number of bytes available in the input
3104 * side of the buffer. This function never fails.
3105 */
3106__LJMP static int hlua_channel_get_in_len(lua_State *L)
3107{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003108 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003109
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003110 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003111 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003112 if (IS_HTX_STRM(chn_strm(chn))) {
3113 struct htx *htx = htxbuf(&chn->buf);
3114 lua_pushinteger(L, htx->data - co_data(chn));
3115 }
3116 else
3117 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003118 return 1;
3119}
3120
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003121/* Returns true if the channel is full. */
3122__LJMP static int hlua_channel_is_full(lua_State *L)
3123{
3124 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003125
3126 MAY_LJMP(check_args(L, 1, "is_full"));
3127 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003128 /* ignore the reserve, we are not on a producer side (ie in an
3129 * applet).
3130 */
3131 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003132 return 1;
3133}
3134
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003135/* Returns true if the channel is the response channel. */
3136__LJMP static int hlua_channel_is_resp(lua_State *L)
3137{
3138 struct channel *chn;
3139
3140 MAY_LJMP(check_args(L, 1, "is_resp"));
3141 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3142
3143 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3144 return 1;
3145}
3146
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003147/* Just returns the number of bytes available in the output
3148 * side of the buffer. This function never fails.
3149 */
3150__LJMP static int hlua_channel_get_out_len(lua_State *L)
3151{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003152 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003153
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003154 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003155 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003156 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003157 return 1;
3158}
3159
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003160/*
3161 *
3162 *
3163 * Class Fetches
3164 *
3165 *
3166 */
3167
3168/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003169 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003170 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003171__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003172{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003173 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003174}
3175
3176/* This function creates and push in the stack a fetch object according
3177 * with a current TXN.
3178 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003179static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003180{
Willy Tarreau7073c472015-04-06 11:15:40 +02003181 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003182
3183 /* Check stack size. */
3184 if (!lua_checkstack(L, 3))
3185 return 0;
3186
3187 /* Create the object: obj[0] = userdata.
3188 * Note that the base of the Fetches object is the
3189 * transaction object.
3190 */
3191 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003192 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003193 lua_rawseti(L, -2, 0);
3194
Willy Tarreau7073c472015-04-06 11:15:40 +02003195 hsmp->s = txn->s;
3196 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003197 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003198 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003199
3200 /* Pop a class sesison metatable and affect it to the userdata. */
3201 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3202 lua_setmetatable(L, -2);
3203
3204 return 1;
3205}
3206
3207/* This function is an LUA binding. It is called with each sample-fetch.
3208 * It uses closure argument to store the associated sample-fetch. It
3209 * returns only one argument or throws an error. An error is thrown
3210 * only if an error is encountered during the argument parsing. If
3211 * the "sample-fetch" function fails, nil is returned.
3212 */
3213__LJMP static int hlua_run_sample_fetch(lua_State *L)
3214{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003215 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003216 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003217 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003218 int i;
3219 struct sample smp;
3220
3221 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003222 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003223
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003224 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003225 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003226
Thierry FOURNIERca988662015-12-20 18:43:03 +01003227 /* Check execution authorization. */
3228 if (f->use & SMP_USE_HTTP_ANY &&
3229 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3230 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3231 "is not available in Lua services", f->kw);
3232 WILL_LJMP(lua_error(L));
3233 }
3234
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003235 /* Get extra arguments. */
3236 for (i = 0; i < lua_gettop(L) - 1; i++) {
3237 if (i >= ARGM_NBARGS)
3238 break;
3239 hlua_lua2arg(L, i + 2, &args[i]);
3240 }
3241 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003242 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003243
3244 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003245 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003246
3247 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003248 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003249 lua_pushfstring(L, "error in arguments");
3250 WILL_LJMP(lua_error(L));
3251 }
3252
3253 /* Initialise the sample. */
3254 memset(&smp, 0, sizeof(smp));
3255
3256 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003257 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003258 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003259 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003260 lua_pushstring(L, "");
3261 else
3262 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003263 return 1;
3264 }
3265
3266 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003267 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003268 hlua_smp2lua_str(L, &smp);
3269 else
3270 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003271 return 1;
3272}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003273
3274/*
3275 *
3276 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003277 * Class Converters
3278 *
3279 *
3280 */
3281
3282/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003283 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003284 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003285__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003286{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003287 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003288}
3289
3290/* This function creates and push in the stack a Converters object
3291 * according with a current TXN.
3292 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003293static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003294{
Willy Tarreau7073c472015-04-06 11:15:40 +02003295 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003296
3297 /* Check stack size. */
3298 if (!lua_checkstack(L, 3))
3299 return 0;
3300
3301 /* Create the object: obj[0] = userdata.
3302 * Note that the base of the Converters object is the
3303 * same than the TXN object.
3304 */
3305 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003306 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003307 lua_rawseti(L, -2, 0);
3308
Willy Tarreau7073c472015-04-06 11:15:40 +02003309 hsmp->s = txn->s;
3310 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003311 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003312 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003313
Willy Tarreau87b09662015-04-03 00:22:06 +02003314 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003315 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3316 lua_setmetatable(L, -2);
3317
3318 return 1;
3319}
3320
3321/* This function is an LUA binding. It is called with each converter.
3322 * It uses closure argument to store the associated converter. It
3323 * returns only one argument or throws an error. An error is thrown
3324 * only if an error is encountered during the argument parsing. If
3325 * the converter function function fails, nil is returned.
3326 */
3327__LJMP static int hlua_run_sample_conv(lua_State *L)
3328{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003329 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003330 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003331 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003332 int i;
3333 struct sample smp;
3334
3335 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003336 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003337
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003338 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003339 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003340
3341 /* Get extra arguments. */
3342 for (i = 0; i < lua_gettop(L) - 2; i++) {
3343 if (i >= ARGM_NBARGS)
3344 break;
3345 hlua_lua2arg(L, i + 3, &args[i]);
3346 }
3347 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003348 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003349
3350 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003351 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003352
3353 /* Run the special args checker. */
3354 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3355 hlua_pusherror(L, "error in arguments");
3356 WILL_LJMP(lua_error(L));
3357 }
3358
3359 /* Initialise the sample. */
3360 if (!hlua_lua2smp(L, 2, &smp)) {
3361 hlua_pusherror(L, "error in the input argument");
3362 WILL_LJMP(lua_error(L));
3363 }
3364
Willy Tarreau1777ea62016-03-10 16:15:46 +01003365 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3366
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003367 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003368 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003369 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003370 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003371 WILL_LJMP(lua_error(L));
3372 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003373 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3374 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003375 hlua_pusherror(L, "error during the input argument casting");
3376 WILL_LJMP(lua_error(L));
3377 }
3378
3379 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003380 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003381 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003382 lua_pushstring(L, "");
3383 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003384 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003385 return 1;
3386 }
3387
3388 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003389 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003390 hlua_smp2lua_str(L, &smp);
3391 else
3392 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003393 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003394}
3395
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003396/*
3397 *
3398 *
3399 * Class AppletTCP
3400 *
3401 *
3402 */
3403
3404/* Returns a struct hlua_txn if the stack entry "ud" is
3405 * a class stream, otherwise it throws an error.
3406 */
3407__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3408{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003409 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003410}
3411
3412/* This function creates and push in the stack an Applet object
3413 * according with a current TXN.
3414 */
3415static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3416{
3417 struct hlua_appctx *appctx;
3418 struct stream_interface *si = ctx->owner;
3419 struct stream *s = si_strm(si);
3420 struct proxy *p = s->be;
3421
3422 /* Check stack size. */
3423 if (!lua_checkstack(L, 3))
3424 return 0;
3425
3426 /* Create the object: obj[0] = userdata.
3427 * Note that the base of the Converters object is the
3428 * same than the TXN object.
3429 */
3430 lua_newtable(L);
3431 appctx = lua_newuserdata(L, sizeof(*appctx));
3432 lua_rawseti(L, -2, 0);
3433 appctx->appctx = ctx;
3434 appctx->htxn.s = s;
3435 appctx->htxn.p = p;
3436
3437 /* Create the "f" field that contains a list of fetches. */
3438 lua_pushstring(L, "f");
3439 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3440 return 0;
3441 lua_settable(L, -3);
3442
3443 /* Create the "sf" field that contains a list of stringsafe fetches. */
3444 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003445 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003446 return 0;
3447 lua_settable(L, -3);
3448
3449 /* Create the "c" field that contains a list of converters. */
3450 lua_pushstring(L, "c");
3451 if (!hlua_converters_new(L, &appctx->htxn, 0))
3452 return 0;
3453 lua_settable(L, -3);
3454
3455 /* Create the "sc" field that contains a list of stringsafe converters. */
3456 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003457 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003458 return 0;
3459 lua_settable(L, -3);
3460
3461 /* Pop a class stream metatable and affect it to the table. */
3462 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3463 lua_setmetatable(L, -2);
3464
3465 return 1;
3466}
3467
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003468__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3469{
3470 struct hlua_appctx *appctx;
3471 struct stream *s;
3472 const char *name;
3473 size_t len;
3474 struct sample smp;
3475
3476 MAY_LJMP(check_args(L, 3, "set_var"));
3477
3478 /* It is useles to retrieve the stream, but this function
3479 * runs only in a stream context.
3480 */
3481 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3482 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3483 s = appctx->htxn.s;
3484
3485 /* Converts the third argument in a sample. */
3486 hlua_lua2smp(L, 3, &smp);
3487
3488 /* Store the sample in a variable. */
3489 smp_set_owner(&smp, s->be, s->sess, s, 0);
3490 vars_set_by_name(name, len, &smp);
3491 return 0;
3492}
3493
3494__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3495{
3496 struct hlua_appctx *appctx;
3497 struct stream *s;
3498 const char *name;
3499 size_t len;
3500 struct sample smp;
3501
3502 MAY_LJMP(check_args(L, 2, "unset_var"));
3503
3504 /* It is useles to retrieve the stream, but this function
3505 * runs only in a stream context.
3506 */
3507 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3508 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3509 s = appctx->htxn.s;
3510
3511 /* Unset the variable. */
3512 smp_set_owner(&smp, s->be, s->sess, s, 0);
3513 vars_unset_by_name(name, len, &smp);
3514 return 0;
3515}
3516
3517__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3518{
3519 struct hlua_appctx *appctx;
3520 struct stream *s;
3521 const char *name;
3522 size_t len;
3523 struct sample smp;
3524
3525 MAY_LJMP(check_args(L, 2, "get_var"));
3526
3527 /* It is useles to retrieve the stream, but this function
3528 * runs only in a stream context.
3529 */
3530 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3531 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3532 s = appctx->htxn.s;
3533
3534 smp_set_owner(&smp, s->be, s->sess, s, 0);
3535 if (!vars_get_by_name(name, len, &smp)) {
3536 lua_pushnil(L);
3537 return 1;
3538 }
3539
3540 return hlua_smp2lua(L, &smp);
3541}
3542
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003543__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3544{
3545 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3546 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003547 struct hlua *hlua;
3548
3549 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003550 if (!s->hlua)
3551 return 0;
3552 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003553
3554 MAY_LJMP(check_args(L, 2, "set_priv"));
3555
3556 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003557 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003558
3559 /* Get and store new value. */
3560 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3561 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3562
3563 return 0;
3564}
3565
3566__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3567{
3568 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3569 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003570 struct hlua *hlua;
3571
3572 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003573 if (!s->hlua) {
3574 lua_pushnil(L);
3575 return 1;
3576 }
3577 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003578
3579 /* Push configuration index in the stack. */
3580 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3581
3582 return 1;
3583}
3584
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003585/* If expected data not yet available, it returns a yield. This function
3586 * consumes the data in the buffer. It returns a string containing the
3587 * data. This string can be empty.
3588 */
3589__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3590{
3591 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3592 struct stream_interface *si = appctx->appctx->owner;
3593 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003594 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003595 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003596 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003597 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003598
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003599 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003600 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003601
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003602 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003603 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003604 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003605 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003606 }
3607
3608 /* End of data: commit the total strings and return. */
3609 if (ret < 0) {
3610 luaL_pushresult(&appctx->b);
3611 return 1;
3612 }
3613
3614 /* Ensure that the block 2 length is usable. */
3615 if (ret == 1)
3616 len2 = 0;
3617
3618 /* dont check the max length read and dont check. */
3619 luaL_addlstring(&appctx->b, blk1, len1);
3620 luaL_addlstring(&appctx->b, blk2, len2);
3621
3622 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003623 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003624 luaL_pushresult(&appctx->b);
3625 return 1;
3626}
3627
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003628/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003629__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3630{
3631 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3632
3633 /* Initialise the string catenation. */
3634 luaL_buffinit(L, &appctx->b);
3635
3636 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3637}
3638
3639/* If expected data not yet available, it returns a yield. This function
3640 * consumes the data in the buffer. It returns a string containing the
3641 * data. This string can be empty.
3642 */
3643__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3644{
3645 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3646 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003647 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003648 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003649 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003650 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003651 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003652 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003653
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003654 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003655 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003656
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003657 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003658 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003659 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003660 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003661 }
3662
3663 /* End of data: commit the total strings and return. */
3664 if (ret < 0) {
3665 luaL_pushresult(&appctx->b);
3666 return 1;
3667 }
3668
3669 /* Ensure that the block 2 length is usable. */
3670 if (ret == 1)
3671 len2 = 0;
3672
3673 if (len == -1) {
3674
3675 /* If len == -1, catenate all the data avalaile and
3676 * yield because we want to get all the data until
3677 * the end of data stream.
3678 */
3679 luaL_addlstring(&appctx->b, blk1, len1);
3680 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003681 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003682 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003683 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003684
3685 } else {
3686
3687 /* Copy the fisrt block caping to the length required. */
3688 if (len1 > len)
3689 len1 = len;
3690 luaL_addlstring(&appctx->b, blk1, len1);
3691 len -= len1;
3692
3693 /* Copy the second block. */
3694 if (len2 > len)
3695 len2 = len;
3696 luaL_addlstring(&appctx->b, blk2, len2);
3697 len -= len2;
3698
3699 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003700 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003701
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003702 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003703 if (len > 0) {
3704 lua_pushinteger(L, len);
3705 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003706 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003707 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003708 }
3709
3710 /* return the result. */
3711 luaL_pushresult(&appctx->b);
3712 return 1;
3713 }
3714
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003715 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003716 hlua_pusherror(L, "Lua: internal error");
3717 WILL_LJMP(lua_error(L));
3718 return 0;
3719}
3720
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003721/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003722__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3723{
3724 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3725 int len = -1;
3726
3727 if (lua_gettop(L) > 2)
3728 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3729 if (lua_gettop(L) >= 2) {
3730 len = MAY_LJMP(luaL_checkinteger(L, 2));
3731 lua_pop(L, 1);
3732 }
3733
3734 /* Confirm or set the required length */
3735 lua_pushinteger(L, len);
3736
3737 /* Initialise the string catenation. */
3738 luaL_buffinit(L, &appctx->b);
3739
3740 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3741}
3742
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003743/* Append data in the output side of the buffer. This data is immediately
3744 * sent. The function returns the amount of data written. If the buffer
3745 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003746 * if the channel is closed.
3747 */
3748__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3749{
3750 size_t len;
3751 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3752 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3753 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3754 struct stream_interface *si = appctx->appctx->owner;
3755 struct channel *chn = si_ic(si);
3756 int max;
3757
3758 /* Get the max amount of data which can write as input in the channel. */
3759 max = channel_recv_max(chn);
3760 if (max > (len - l))
3761 max = len - l;
3762
3763 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003764 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003765
3766 /* update counters. */
3767 l += max;
3768 lua_pop(L, 1);
3769 lua_pushinteger(L, l);
3770
3771 /* If some data is not send, declares the situation to the
3772 * applet, and returns a yield.
3773 */
3774 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003775 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003776 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003777 }
3778
3779 return 1;
3780}
3781
3782/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3783 * yield the LUA process, and resume it without checking the
3784 * input arguments.
3785 */
3786__LJMP static int hlua_applet_tcp_send(lua_State *L)
3787{
3788 MAY_LJMP(check_args(L, 2, "send"));
3789 lua_pushinteger(L, 0);
3790
3791 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3792}
3793
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003794/*
3795 *
3796 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003797 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003798 *
3799 *
3800 */
3801
3802/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003803 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003804 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003805__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003806{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003807 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003808}
3809
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003810/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003811 * according with a current TXN.
3812 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003813static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003814{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003815 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003816 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003817 struct stream_interface *si = ctx->owner;
3818 struct stream *s = si_strm(si);
3819 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02003820 struct htx *htx;
3821 struct htx_blk *blk;
3822 struct htx_sl *sl;
3823 struct ist path;
3824 unsigned long long len = 0;
3825 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003826
3827 /* Check stack size. */
3828 if (!lua_checkstack(L, 3))
3829 return 0;
3830
3831 /* Create the object: obj[0] = userdata.
3832 * Note that the base of the Converters object is the
3833 * same than the TXN object.
3834 */
3835 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003836 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003837 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003838 appctx->appctx = ctx;
3839 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003840 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003841 appctx->htxn.s = s;
3842 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003843
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003844 /* Create the "f" field that contains a list of fetches. */
3845 lua_pushstring(L, "f");
3846 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3847 return 0;
3848 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003849
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003850 /* Create the "sf" field that contains a list of stringsafe fetches. */
3851 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003852 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003853 return 0;
3854 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003855
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003856 /* Create the "c" field that contains a list of converters. */
3857 lua_pushstring(L, "c");
3858 if (!hlua_converters_new(L, &appctx->htxn, 0))
3859 return 0;
3860 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003861
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003862 /* Create the "sc" field that contains a list of stringsafe converters. */
3863 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003864 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003865 return 0;
3866 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003867
Christopher Fauleta2097962019-07-15 16:25:33 +02003868 htx = htxbuf(&s->req.buf);
3869 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01003870 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02003871 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003872
Christopher Fauleta2097962019-07-15 16:25:33 +02003873 /* Stores the request method. */
3874 lua_pushstring(L, "method");
3875 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
3876 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003877
Christopher Fauleta2097962019-07-15 16:25:33 +02003878 /* Stores the http version. */
3879 lua_pushstring(L, "version");
3880 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
3881 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003882
Christopher Fauleta2097962019-07-15 16:25:33 +02003883 /* creates an array of headers. hlua_http_get_headers() crates and push
3884 * the array on the top of the stack.
3885 */
3886 lua_pushstring(L, "headers");
3887 htxn.s = s;
3888 htxn.p = px;
3889 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01003890 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02003891 return 0;
3892 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003893
Christopher Fauleta2097962019-07-15 16:25:33 +02003894 path = http_get_path(htx_sl_req_uri(sl));
Tim Duesterhused526372020-03-05 17:56:33 +01003895 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02003896 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003897
Christopher Fauleta2097962019-07-15 16:25:33 +02003898 p = path.ptr;
3899 end = path.ptr + path.len;
3900 q = p;
3901 while (q < end && *q != '?')
3902 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003903
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003904 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02003905 lua_pushstring(L, "path");
3906 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003907 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003908
Christopher Fauleta2097962019-07-15 16:25:33 +02003909 /* Stores the query string. */
3910 lua_pushstring(L, "qs");
3911 if (*q == '?')
3912 q++;
3913 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003914 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02003915 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003916
Christopher Fauleta2097962019-07-15 16:25:33 +02003917 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3918 struct htx_blk *blk = htx_get_blk(htx, pos);
3919 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003920
Christopher Fauleta2097962019-07-15 16:25:33 +02003921 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
3922 break;
3923 if (type == HTX_BLK_DATA)
3924 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003925 }
Christopher Fauleta2097962019-07-15 16:25:33 +02003926 if (htx->extra != ULLONG_MAX)
3927 len += htx->extra;
3928
3929 /* Stores the request path. */
3930 lua_pushstring(L, "length");
3931 lua_pushinteger(L, len);
3932 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003933
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003934 /* Create an empty array of HTTP request headers. */
3935 lua_pushstring(L, "response");
3936 lua_newtable(L);
3937 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003938
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003939 /* Pop a class stream metatable and affect it to the table. */
3940 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3941 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003942
3943 return 1;
3944}
3945
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003946__LJMP static int hlua_applet_http_set_var(lua_State *L)
3947{
3948 struct hlua_appctx *appctx;
3949 struct stream *s;
3950 const char *name;
3951 size_t len;
3952 struct sample smp;
3953
3954 MAY_LJMP(check_args(L, 3, "set_var"));
3955
3956 /* It is useles to retrieve the stream, but this function
3957 * runs only in a stream context.
3958 */
3959 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3960 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3961 s = appctx->htxn.s;
3962
3963 /* Converts the third argument in a sample. */
3964 hlua_lua2smp(L, 3, &smp);
3965
3966 /* Store the sample in a variable. */
3967 smp_set_owner(&smp, s->be, s->sess, s, 0);
3968 vars_set_by_name(name, len, &smp);
3969 return 0;
3970}
3971
3972__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3973{
3974 struct hlua_appctx *appctx;
3975 struct stream *s;
3976 const char *name;
3977 size_t len;
3978 struct sample smp;
3979
3980 MAY_LJMP(check_args(L, 2, "unset_var"));
3981
3982 /* It is useles to retrieve the stream, but this function
3983 * runs only in a stream context.
3984 */
3985 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3986 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3987 s = appctx->htxn.s;
3988
3989 /* Unset the variable. */
3990 smp_set_owner(&smp, s->be, s->sess, s, 0);
3991 vars_unset_by_name(name, len, &smp);
3992 return 0;
3993}
3994
3995__LJMP static int hlua_applet_http_get_var(lua_State *L)
3996{
3997 struct hlua_appctx *appctx;
3998 struct stream *s;
3999 const char *name;
4000 size_t len;
4001 struct sample smp;
4002
4003 MAY_LJMP(check_args(L, 2, "get_var"));
4004
4005 /* It is useles to retrieve the stream, but this function
4006 * runs only in a stream context.
4007 */
4008 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4009 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4010 s = appctx->htxn.s;
4011
4012 smp_set_owner(&smp, s->be, s->sess, s, 0);
4013 if (!vars_get_by_name(name, len, &smp)) {
4014 lua_pushnil(L);
4015 return 1;
4016 }
4017
4018 return hlua_smp2lua(L, &smp);
4019}
4020
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004021__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4022{
4023 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4024 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004025 struct hlua *hlua;
4026
4027 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004028 if (!s->hlua)
4029 return 0;
4030 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004031
4032 MAY_LJMP(check_args(L, 2, "set_priv"));
4033
4034 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004035 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004036
4037 /* Get and store new value. */
4038 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4039 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4040
4041 return 0;
4042}
4043
4044__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4045{
4046 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4047 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004048 struct hlua *hlua;
4049
4050 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004051 if (!s->hlua) {
4052 lua_pushnil(L);
4053 return 1;
4054 }
4055 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004056
4057 /* Push configuration index in the stack. */
4058 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4059
4060 return 1;
4061}
4062
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004063/* If expected data not yet available, it returns a yield. This function
4064 * consumes the data in the buffer. It returns a string containing the
4065 * data. This string can be empty.
4066 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004067__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004068{
4069 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4070 struct stream_interface *si = appctx->appctx->owner;
4071 struct channel *req = si_oc(si);
4072 struct htx *htx;
4073 struct htx_blk *blk;
4074 size_t count;
4075 int stop = 0;
4076
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004077 htx = htx_from_buf(&req->buf);
4078 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004079 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004080
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004081 while (count && !stop && blk) {
4082 enum htx_blk_type type = htx_get_blk_type(blk);
4083 uint32_t sz = htx_get_blksz(blk);
4084 struct ist v;
4085 uint32_t vlen;
4086 char *nl;
4087
Christopher Faulete461e342018-12-18 16:43:35 +01004088 if (type == HTX_BLK_EOM) {
4089 stop = 1;
4090 break;
4091 }
4092
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004093 vlen = sz;
4094 if (vlen > count) {
4095 if (type != HTX_BLK_DATA)
4096 break;
4097 vlen = count;
4098 }
4099
4100 switch (type) {
4101 case HTX_BLK_UNUSED:
4102 break;
4103
4104 case HTX_BLK_DATA:
4105 v = htx_get_blk_value(htx, blk);
4106 v.len = vlen;
4107 nl = istchr(v, '\n');
4108 if (nl != NULL) {
4109 stop = 1;
4110 vlen = nl - v.ptr + 1;
4111 }
4112 luaL_addlstring(&appctx->b, v.ptr, vlen);
4113 break;
4114
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004115 case HTX_BLK_TLR:
4116 case HTX_BLK_EOM:
4117 stop = 1;
4118 break;
4119
4120 default:
4121 break;
4122 }
4123
4124 co_set_data(req, co_data(req) - vlen);
4125 count -= vlen;
4126 if (sz == vlen)
4127 blk = htx_remove_blk(htx, blk);
4128 else {
4129 htx_cut_data_blk(htx, blk, vlen);
4130 break;
4131 }
4132 }
4133
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004134 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004135 if (!stop) {
4136 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004137 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004138 }
4139
4140 /* return the result. */
4141 luaL_pushresult(&appctx->b);
4142 return 1;
4143}
4144
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004145
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004146/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004147__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004148{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004149 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004150
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004151 /* Initialise the string catenation. */
4152 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004153
Christopher Fauleta2097962019-07-15 16:25:33 +02004154 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004155}
4156
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004157/* If expected data not yet available, it returns a yield. This function
4158 * consumes the data in the buffer. It returns a string containing the
4159 * data. This string can be empty.
4160 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004161__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004162{
4163 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4164 struct stream_interface *si = appctx->appctx->owner;
4165 struct channel *req = si_oc(si);
4166 struct htx *htx;
4167 struct htx_blk *blk;
4168 size_t count;
4169 int len;
4170
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004171 htx = htx_from_buf(&req->buf);
4172 len = MAY_LJMP(luaL_checkinteger(L, 2));
4173 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004174 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004175 while (count && len && blk) {
4176 enum htx_blk_type type = htx_get_blk_type(blk);
4177 uint32_t sz = htx_get_blksz(blk);
4178 struct ist v;
4179 uint32_t vlen;
4180
Christopher Faulete461e342018-12-18 16:43:35 +01004181 if (type == HTX_BLK_EOM) {
4182 len = 0;
4183 break;
4184 }
4185
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004186 vlen = sz;
4187 if (len > 0 && vlen > len)
4188 vlen = len;
4189 if (vlen > count) {
4190 if (type != HTX_BLK_DATA)
4191 break;
4192 vlen = count;
4193 }
4194
4195 switch (type) {
4196 case HTX_BLK_UNUSED:
4197 break;
4198
4199 case HTX_BLK_DATA:
4200 v = htx_get_blk_value(htx, blk);
4201 luaL_addlstring(&appctx->b, v.ptr, vlen);
4202 break;
4203
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004204 case HTX_BLK_TLR:
4205 case HTX_BLK_EOM:
4206 len = 0;
4207 break;
4208
4209 default:
4210 break;
4211 }
4212
4213 co_set_data(req, co_data(req) - vlen);
4214 count -= vlen;
4215 if (len > 0)
4216 len -= vlen;
4217 if (sz == vlen)
4218 blk = htx_remove_blk(htx, blk);
4219 else {
4220 htx_cut_data_blk(htx, blk, vlen);
4221 break;
4222 }
4223 }
4224
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004225 htx_to_buf(htx, &req->buf);
4226
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004227 /* If we are no other data available, yield waiting for new data. */
4228 if (len) {
4229 if (len > 0) {
4230 lua_pushinteger(L, len);
4231 lua_replace(L, 2);
4232 }
4233 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004234 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004235 }
4236
4237 /* return the result. */
4238 luaL_pushresult(&appctx->b);
4239 return 1;
4240}
4241
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004242/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004243__LJMP static int hlua_applet_http_recv(lua_State *L)
4244{
4245 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4246 int len = -1;
4247
4248 /* Check arguments. */
4249 if (lua_gettop(L) > 2)
4250 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4251 if (lua_gettop(L) >= 2) {
4252 len = MAY_LJMP(luaL_checkinteger(L, 2));
4253 lua_pop(L, 1);
4254 }
4255
Christopher Fauleta2097962019-07-15 16:25:33 +02004256 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004257
Christopher Fauleta2097962019-07-15 16:25:33 +02004258 /* Initialise the string catenation. */
4259 luaL_buffinit(L, &appctx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004260
Christopher Fauleta2097962019-07-15 16:25:33 +02004261 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004262}
4263
4264/* Append data in the output side of the buffer. This data is immediately
4265 * sent. The function returns the amount of data written. If the buffer
4266 * cannot contain the data, the function yields. The function returns -1
4267 * if the channel is closed.
4268 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004269__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004270{
4271 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4272 struct stream_interface *si = appctx->appctx->owner;
4273 struct channel *res = si_ic(si);
4274 struct htx *htx = htx_from_buf(&res->buf);
4275 const char *data;
4276 size_t len;
4277 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4278 int max;
4279
Christopher Faulet9060fc02019-07-03 11:39:30 +02004280 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004281 if (!max)
4282 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004283
4284 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4285
4286 /* Get the max amount of data which can write as input in the channel. */
4287 if (max > (len - l))
4288 max = len - l;
4289
4290 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004291 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004292 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004293
4294 /* update counters. */
4295 l += max;
4296 lua_pop(L, 1);
4297 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004298
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004299 /* If some data is not send, declares the situation to the
4300 * applet, and returns a yield.
4301 */
4302 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004303 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004304 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004305 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004306 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004307 }
4308
Christopher Fauleta2097962019-07-15 16:25:33 +02004309 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004310 return 1;
4311}
4312
4313/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4314 * yield the LUA process, and resume it without checking the
4315 * input arguments.
4316 */
4317__LJMP static int hlua_applet_http_send(lua_State *L)
4318{
4319 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004320
4321 /* We want to send some data. Headers must be sent. */
4322 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4323 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4324 WILL_LJMP(lua_error(L));
4325 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004326
Christopher Fauleta2097962019-07-15 16:25:33 +02004327 /* This interger is used for followinf the amount of data sent. */
4328 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004329
Christopher Fauleta2097962019-07-15 16:25:33 +02004330 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004331}
4332
4333__LJMP static int hlua_applet_http_addheader(lua_State *L)
4334{
4335 const char *name;
4336 int ret;
4337
4338 MAY_LJMP(hlua_checkapplet_http(L, 1));
4339 name = MAY_LJMP(luaL_checkstring(L, 2));
4340 MAY_LJMP(luaL_checkstring(L, 3));
4341
4342 /* Push in the stack the "response" entry. */
4343 ret = lua_getfield(L, 1, "response");
4344 if (ret != LUA_TTABLE) {
4345 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4346 "is expected as an array. %s found", lua_typename(L, ret));
4347 WILL_LJMP(lua_error(L));
4348 }
4349
4350 /* check if the header is already registered if it is not
4351 * the case, register it.
4352 */
4353 ret = lua_getfield(L, -1, name);
4354 if (ret == LUA_TNIL) {
4355
4356 /* Entry not found. */
4357 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4358
4359 /* Insert the new header name in the array in the top of the stack.
4360 * It left the new array in the top of the stack.
4361 */
4362 lua_newtable(L);
4363 lua_pushvalue(L, 2);
4364 lua_pushvalue(L, -2);
4365 lua_settable(L, -4);
4366
4367 } else if (ret != LUA_TTABLE) {
4368
4369 /* corruption error. */
4370 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4371 "is expected as an array. %s found", name, lua_typename(L, ret));
4372 WILL_LJMP(lua_error(L));
4373 }
4374
4375 /* Now the top od thestack is an array of values. We push
4376 * the header value as new entry.
4377 */
4378 lua_pushvalue(L, 3);
4379 ret = lua_rawlen(L, -2);
4380 lua_rawseti(L, -2, ret + 1);
4381 lua_pushboolean(L, 1);
4382 return 1;
4383}
4384
4385__LJMP static int hlua_applet_http_status(lua_State *L)
4386{
4387 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4388 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004389 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004390
4391 if (status < 100 || status > 599) {
4392 lua_pushboolean(L, 0);
4393 return 1;
4394 }
4395
4396 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004397 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004398 lua_pushboolean(L, 1);
4399 return 1;
4400}
4401
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004402
Christopher Fauleta2097962019-07-15 16:25:33 +02004403__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004404{
4405 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4406 struct stream_interface *si = appctx->appctx->owner;
4407 struct channel *res = si_ic(si);
4408 struct htx *htx;
4409 struct htx_sl *sl;
4410 struct h1m h1m;
4411 const char *status, *reason;
4412 const char *name, *value;
4413 size_t nlen, vlen;
4414 unsigned int flags;
4415
4416 /* Send the message at once. */
4417 htx = htx_from_buf(&res->buf);
4418 h1m_init_res(&h1m);
4419
4420 /* Use the same http version than the request. */
4421 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4422 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4423 if (reason == NULL)
4424 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4425 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4426 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4427 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4428 }
4429 else {
4430 flags = HTX_SL_F_IS_RESP;
4431 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4432 }
4433 if (!sl) {
4434 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4435 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4436 WILL_LJMP(lua_error(L));
4437 }
4438 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4439
4440 /* Get the array associated to the field "response" in the object AppletHTTP. */
4441 lua_pushvalue(L, 0);
4442 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4443 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4444 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4445 WILL_LJMP(lua_error(L));
4446 }
4447
4448 /* Browse the list of headers. */
4449 lua_pushnil(L);
4450 while(lua_next(L, -2) != 0) {
4451 /* We expect a string as -2. */
4452 if (lua_type(L, -2) != LUA_TSTRING) {
4453 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4454 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4455 lua_typename(L, lua_type(L, -2)));
4456 WILL_LJMP(lua_error(L));
4457 }
4458 name = lua_tolstring(L, -2, &nlen);
4459
4460 /* We expect an array as -1. */
4461 if (lua_type(L, -1) != LUA_TTABLE) {
4462 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4463 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4464 name,
4465 lua_typename(L, lua_type(L, -1)));
4466 WILL_LJMP(lua_error(L));
4467 }
4468
4469 /* Browse the table who is on the top of the stack. */
4470 lua_pushnil(L);
4471 while(lua_next(L, -2) != 0) {
4472 int id;
4473
4474 /* We expect a number as -2. */
4475 if (lua_type(L, -2) != LUA_TNUMBER) {
4476 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4477 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4478 name,
4479 lua_typename(L, lua_type(L, -2)));
4480 WILL_LJMP(lua_error(L));
4481 }
4482 id = lua_tointeger(L, -2);
4483
4484 /* We expect a string as -2. */
4485 if (lua_type(L, -1) != LUA_TSTRING) {
4486 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4487 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4488 name, id,
4489 lua_typename(L, lua_type(L, -1)));
4490 WILL_LJMP(lua_error(L));
4491 }
4492 value = lua_tolstring(L, -1, &vlen);
4493
4494 /* Simple Protocol checks. */
4495 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01004496 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004497 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4498 struct ist v = ist2(value, vlen);
4499 int ret;
4500
4501 ret = h1_parse_cont_len_header(&h1m, &v);
4502 if (ret < 0) {
4503 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4504 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4505 name);
4506 WILL_LJMP(lua_error(L));
4507 }
4508 else if (ret == 0)
4509 goto next; /* Skip it */
4510 }
4511
4512 /* Add a new header */
4513 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4514 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4515 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4516 name);
4517 WILL_LJMP(lua_error(L));
4518 }
4519 next:
4520 /* Remove the array from the stack, and get next element with a remaining string. */
4521 lua_pop(L, 1);
4522 }
4523
4524 /* Remove the array from the stack, and get next element with a remaining string. */
4525 lua_pop(L, 1);
4526 }
4527
4528 if (h1m.flags & H1_MF_CHNK)
4529 h1m.flags &= ~H1_MF_CLEN;
4530 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4531 h1m.flags |= H1_MF_XFER_LEN;
4532
4533 /* Uset HTX start-line flags */
4534 if (h1m.flags & H1_MF_XFER_ENC)
4535 flags |= HTX_SL_F_XFER_ENC;
4536 if (h1m.flags & H1_MF_XFER_LEN) {
4537 flags |= HTX_SL_F_XFER_LEN;
4538 if (h1m.flags & H1_MF_CHNK)
4539 flags |= HTX_SL_F_CHNK;
4540 else if (h1m.flags & H1_MF_CLEN)
4541 flags |= HTX_SL_F_CLEN;
4542 if (h1m.body_len == 0)
4543 flags |= HTX_SL_F_BODYLESS;
4544 }
4545 sl->flags |= flags;
4546
4547 /* If we dont have a content-length set, and the HTTP version is 1.1
4548 * and the status code implies the presence of a message body, we must
4549 * announce a transfer encoding chunked. This is required by haproxy
4550 * for the keepalive compliance. If the applet annouces a transfer-encoding
4551 * chunked itslef, don't do anything.
4552 */
4553 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4554 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4555 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4556 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4557 /* Add a new header */
4558 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4559 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4560 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4561 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4562 WILL_LJMP(lua_error(L));
4563 }
4564 }
4565
4566 /* Finalize headers. */
4567 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4568 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4569 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4570 WILL_LJMP(lua_error(L));
4571 }
4572
4573 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4574 b_reset(&res->buf);
4575 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4576 WILL_LJMP(lua_error(L));
4577 }
4578
4579 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004580 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004581
4582 /* Headers sent, set the flag. */
4583 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4584 return 0;
4585
4586}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004587/* We will build the status line and the headers of the HTTP response.
4588 * We will try send at once if its not possible, we give back the hand
4589 * waiting for more room.
4590 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004591__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004592{
4593 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4594 struct stream_interface *si = appctx->appctx->owner;
4595 struct channel *res = si_ic(si);
4596
4597 if (co_data(res)) {
4598 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004599 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004600 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004601 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004602}
4603
4604
Christopher Fauleta2097962019-07-15 16:25:33 +02004605__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004606{
Christopher Fauleta2097962019-07-15 16:25:33 +02004607 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004608}
4609
Christopher Fauleta2097962019-07-15 16:25:33 +02004610/*
4611 *
4612 *
4613 * Class HTTP
4614 *
4615 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004616 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004617
4618/* Returns a struct hlua_txn if the stack entry "ud" is
4619 * a class stream, otherwise it throws an error.
4620 */
4621__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004622{
Christopher Fauleta2097962019-07-15 16:25:33 +02004623 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4624}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004625
Christopher Fauleta2097962019-07-15 16:25:33 +02004626/* This function creates and push in the stack a HTTP object
4627 * according with a current TXN.
4628 */
4629static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4630{
4631 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004632
Christopher Fauleta2097962019-07-15 16:25:33 +02004633 /* Check stack size. */
4634 if (!lua_checkstack(L, 3))
4635 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004636
Christopher Fauleta2097962019-07-15 16:25:33 +02004637 /* Create the object: obj[0] = userdata.
4638 * Note that the base of the Converters object is the
4639 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004640 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004641 lua_newtable(L);
4642 htxn = lua_newuserdata(L, sizeof(*htxn));
4643 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004644
4645 htxn->s = txn->s;
4646 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02004647 htxn->dir = txn->dir;
4648 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004649
4650 /* Pop a class stream metatable and affect it to the table. */
4651 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4652 lua_setmetatable(L, -2);
4653
4654 return 1;
4655}
4656
4657/* This function creates ans returns an array of HTTP headers.
4658 * This function does not fails. It is used as wrapper with the
4659 * 2 following functions.
4660 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004661__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004662{
Christopher Fauleta2097962019-07-15 16:25:33 +02004663 struct htx *htx;
4664 int32_t pos;
4665
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004666 /* Create the table. */
4667 lua_newtable(L);
4668
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004669
Christopher Fauleta2097962019-07-15 16:25:33 +02004670 htx = htxbuf(&msg->chn->buf);
4671 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4672 struct htx_blk *blk = htx_get_blk(htx, pos);
4673 enum htx_blk_type type = htx_get_blk_type(blk);
4674 struct ist n, v;
4675 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004676
Christopher Fauleta2097962019-07-15 16:25:33 +02004677 if (type == HTX_BLK_HDR) {
4678 n = htx_get_blk_name(htx,blk);
4679 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004680 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004681 else if (type == HTX_BLK_EOH)
4682 break;
4683 else
4684 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004685
Christopher Fauleta2097962019-07-15 16:25:33 +02004686 /* Check for existing entry:
4687 * assume that the table is on the top of the stack, and
4688 * push the key in the stack, the function lua_gettable()
4689 * perform the lookup.
4690 */
4691 lua_pushlstring(L, n.ptr, n.len);
4692 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004693
Christopher Fauleta2097962019-07-15 16:25:33 +02004694 switch (lua_type(L, -1)) {
4695 case LUA_TNIL:
4696 /* Table not found, create it. */
4697 lua_pop(L, 1); /* remove the nil value. */
4698 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
4699 lua_newtable(L); /* create and push empty table. */
4700 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
4701 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4702 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01004703 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004704
Christopher Fauleta2097962019-07-15 16:25:33 +02004705 case LUA_TTABLE:
4706 /* Entry found: push the value in the table. */
4707 len = lua_rawlen(L, -1);
4708 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
4709 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4710 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4711 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004712
Christopher Fauleta2097962019-07-15 16:25:33 +02004713 default:
4714 /* Other cases are errors. */
4715 hlua_pusherror(L, "internal error during the parsing of headers.");
4716 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004717 }
4718 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004719 return 1;
4720}
4721
4722__LJMP static int hlua_http_req_get_headers(lua_State *L)
4723{
4724 struct hlua_txn *htxn;
4725
4726 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4727 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4728
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004729 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004730 WILL_LJMP(lua_error(L));
4731
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004732 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004733}
4734
4735__LJMP static int hlua_http_res_get_headers(lua_State *L)
4736{
4737 struct hlua_txn *htxn;
4738
4739 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4740 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4741
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004742 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004743 WILL_LJMP(lua_error(L));
4744
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004745 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004746}
4747
4748/* This function replace full header, or just a value in
4749 * the request or in the response. It is a wrapper fir the
4750 * 4 following functions.
4751 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004752__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004753{
4754 size_t name_len;
4755 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4756 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4757 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02004758 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02004759 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004760
Dragan Dosen26743032019-04-30 15:54:36 +02004761 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004762 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4763
Christopher Fauleta2097962019-07-15 16:25:33 +02004764 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004765 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02004766 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004767 return 0;
4768}
4769
4770__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4771{
4772 struct hlua_txn *htxn;
4773
4774 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4775 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4776
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004777 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004778 WILL_LJMP(lua_error(L));
4779
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004780 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004781}
4782
4783__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4784{
4785 struct hlua_txn *htxn;
4786
4787 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4788 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4789
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004790 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004791 WILL_LJMP(lua_error(L));
4792
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004793 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004794}
4795
4796__LJMP static int hlua_http_req_rep_val(lua_State *L)
4797{
4798 struct hlua_txn *htxn;
4799
4800 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4801 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4802
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004803 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004804 WILL_LJMP(lua_error(L));
4805
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004806 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004807}
4808
4809__LJMP static int hlua_http_res_rep_val(lua_State *L)
4810{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004811 struct hlua_txn *htxn;
4812
4813 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4814 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4815
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004816 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004817 WILL_LJMP(lua_error(L));
4818
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004819 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004820}
4821
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004822/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004823 * It is a wrapper for the 2 following functions.
4824 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004825__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004826{
4827 size_t len;
4828 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02004829 struct htx *htx = htxbuf(&msg->chn->buf);
4830 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004831
Christopher Fauleta2097962019-07-15 16:25:33 +02004832 ctx.blk = NULL;
4833 while (http_find_header(htx, ist2(name, len), &ctx, 1))
4834 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004835 return 0;
4836}
4837
4838__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4839{
4840 struct hlua_txn *htxn;
4841
4842 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4843 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4844
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004845 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004846 WILL_LJMP(lua_error(L));
4847
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004848 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004849}
4850
4851__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4852{
4853 struct hlua_txn *htxn;
4854
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004855 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004856 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4857
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004858 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004859 WILL_LJMP(lua_error(L));
4860
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004861 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004862}
4863
4864/* This function adds an header. It is a wrapper used by
4865 * the 2 following functions.
4866 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004867__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004868{
4869 size_t name_len;
4870 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4871 size_t value_len;
4872 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02004873 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004874
Christopher Fauleta2097962019-07-15 16:25:33 +02004875 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
4876 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004877 return 0;
4878}
4879
4880__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4881{
4882 struct hlua_txn *htxn;
4883
4884 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4885 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4886
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004887 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004888 WILL_LJMP(lua_error(L));
4889
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004890 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004891}
4892
4893__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4894{
4895 struct hlua_txn *htxn;
4896
4897 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4898 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4899
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004900 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004901 WILL_LJMP(lua_error(L));
4902
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004903 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004904}
4905
4906static int hlua_http_req_set_hdr(lua_State *L)
4907{
4908 struct hlua_txn *htxn;
4909
4910 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4911 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4912
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004913 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004914 WILL_LJMP(lua_error(L));
4915
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004916 hlua_http_del_hdr(L, &htxn->s->txn->req);
4917 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004918}
4919
4920static int hlua_http_res_set_hdr(lua_State *L)
4921{
4922 struct hlua_txn *htxn;
4923
4924 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4925 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4926
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004927 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004928 WILL_LJMP(lua_error(L));
4929
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004930 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
4931 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004932}
4933
4934/* This function set the method. */
4935static int hlua_http_req_set_meth(lua_State *L)
4936{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004937 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004938 size_t name_len;
4939 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004940
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004941 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004942 WILL_LJMP(lua_error(L));
4943
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004944 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004945 return 1;
4946}
4947
4948/* This function set the method. */
4949static int hlua_http_req_set_path(lua_State *L)
4950{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004951 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004952 size_t name_len;
4953 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004954
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004955 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004956 WILL_LJMP(lua_error(L));
4957
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004958 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004959 return 1;
4960}
4961
4962/* This function set the query-string. */
4963static int hlua_http_req_set_query(lua_State *L)
4964{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004965 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004966 size_t name_len;
4967 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004968
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004969 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004970 WILL_LJMP(lua_error(L));
4971
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004972 /* Check length. */
4973 if (name_len > trash.size - 1) {
4974 lua_pushboolean(L, 0);
4975 return 1;
4976 }
4977
4978 /* Add the mark question as prefix. */
4979 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004980 trash.area[trash.data++] = '?';
4981 memcpy(trash.area + trash.data, name, name_len);
4982 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004983
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004984 lua_pushboolean(L,
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004985 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004986 return 1;
4987}
4988
4989/* This function set the uri. */
4990static int hlua_http_req_set_uri(lua_State *L)
4991{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004992 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004993 size_t name_len;
4994 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004995
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004996 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004997 WILL_LJMP(lua_error(L));
4998
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004999 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005000 return 1;
5001}
5002
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005003/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005004static int hlua_http_res_set_status(lua_State *L)
5005{
5006 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5007 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Faulet96bff762019-12-17 13:46:18 +01005008 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5009 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005010
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005011 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005012 WILL_LJMP(lua_error(L));
5013
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005014 http_res_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005015 return 0;
5016}
5017
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005018/*
5019 *
5020 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005021 * Class TXN
5022 *
5023 *
5024 */
5025
5026/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005027 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005028 */
5029__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5030{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005031 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005032}
5033
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005034__LJMP static int hlua_set_var(lua_State *L)
5035{
5036 struct hlua_txn *htxn;
5037 const char *name;
5038 size_t len;
5039 struct sample smp;
5040
5041 MAY_LJMP(check_args(L, 3, "set_var"));
5042
5043 /* It is useles to retrieve the stream, but this function
5044 * runs only in a stream context.
5045 */
5046 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5047 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5048
5049 /* Converts the third argument in a sample. */
5050 hlua_lua2smp(L, 3, &smp);
5051
5052 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005053 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005054 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005055 return 0;
5056}
5057
Christopher Faulet85d79c92016-11-09 16:54:56 +01005058__LJMP static int hlua_unset_var(lua_State *L)
5059{
5060 struct hlua_txn *htxn;
5061 const char *name;
5062 size_t len;
5063 struct sample smp;
5064
5065 MAY_LJMP(check_args(L, 2, "unset_var"));
5066
5067 /* It is useles to retrieve the stream, but this function
5068 * runs only in a stream context.
5069 */
5070 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5071 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5072
5073 /* Unset the variable. */
5074 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5075 vars_unset_by_name(name, len, &smp);
5076 return 0;
5077}
5078
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005079__LJMP static int hlua_get_var(lua_State *L)
5080{
5081 struct hlua_txn *htxn;
5082 const char *name;
5083 size_t len;
5084 struct sample smp;
5085
5086 MAY_LJMP(check_args(L, 2, "get_var"));
5087
5088 /* It is useles to retrieve the stream, but this function
5089 * runs only in a stream context.
5090 */
5091 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5092 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5093
Willy Tarreau7560dd42016-03-10 16:28:58 +01005094 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005095 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005096 lua_pushnil(L);
5097 return 1;
5098 }
5099
5100 return hlua_smp2lua(L, &smp);
5101}
5102
Willy Tarreau59551662015-03-10 14:23:13 +01005103__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005104{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005105 struct hlua *hlua;
5106
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005107 MAY_LJMP(check_args(L, 2, "set_priv"));
5108
Willy Tarreau87b09662015-04-03 00:22:06 +02005109 /* It is useles to retrieve the stream, but this function
5110 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005111 */
5112 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005113 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005114
5115 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005116 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005117
5118 /* Get and store new value. */
5119 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5120 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5121
5122 return 0;
5123}
5124
Willy Tarreau59551662015-03-10 14:23:13 +01005125__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005126{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005127 struct hlua *hlua;
5128
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005129 MAY_LJMP(check_args(L, 1, "get_priv"));
5130
Willy Tarreau87b09662015-04-03 00:22:06 +02005131 /* It is useles to retrieve the stream, but this function
5132 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005133 */
5134 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005135 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005136
5137 /* Push configuration index in the stack. */
5138 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5139
5140 return 1;
5141}
5142
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005143/* Create stack entry containing a class TXN. This function
5144 * return 0 if the stack does not contains free slots,
5145 * otherwise it returns 1.
5146 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005147static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005148{
Willy Tarreaude491382015-04-06 11:04:28 +02005149 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005150
5151 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005152 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005153 return 0;
5154
5155 /* NOTE: The allocation never fails. The failure
5156 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005157 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005158 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005159 /* Create the object: obj[0] = userdata. */
5160 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005161 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005162 lua_rawseti(L, -2, 0);
5163
Willy Tarreaude491382015-04-06 11:04:28 +02005164 htxn->s = s;
5165 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005166 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005167 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005168
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005169 /* Create the "f" field that contains a list of fetches. */
5170 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005171 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005172 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005173 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005174
5175 /* Create the "sf" field that contains a list of stringsafe fetches. */
5176 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005177 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005178 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005179 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005180
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005181 /* Create the "c" field that contains a list of converters. */
5182 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005183 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005184 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005185 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005186
5187 /* Create the "sc" field that contains a list of stringsafe converters. */
5188 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005189 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005190 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005191 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005192
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005193 /* Create the "req" field that contains the request channel object. */
5194 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005195 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005196 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005197 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005198
5199 /* Create the "res" field that contains the response channel object. */
5200 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005201 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005202 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005203 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005204
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005205 /* Creates the HTTP object is the current proxy allows http. */
5206 lua_pushstring(L, "http");
5207 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005208 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005209 return 0;
5210 }
5211 else
5212 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005213 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005214
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005215 /* Pop a class sesison metatable and affect it to the userdata. */
5216 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5217 lua_setmetatable(L, -2);
5218
5219 return 1;
5220}
5221
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005222__LJMP static int hlua_txn_deflog(lua_State *L)
5223{
5224 const char *msg;
5225 struct hlua_txn *htxn;
5226
5227 MAY_LJMP(check_args(L, 2, "deflog"));
5228 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5229 msg = MAY_LJMP(luaL_checkstring(L, 2));
5230
5231 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5232 return 0;
5233}
5234
5235__LJMP static int hlua_txn_log(lua_State *L)
5236{
5237 int level;
5238 const char *msg;
5239 struct hlua_txn *htxn;
5240
5241 MAY_LJMP(check_args(L, 3, "log"));
5242 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5243 level = MAY_LJMP(luaL_checkinteger(L, 2));
5244 msg = MAY_LJMP(luaL_checkstring(L, 3));
5245
5246 if (level < 0 || level >= NB_LOG_LEVELS)
5247 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5248
5249 hlua_sendlog(htxn->s->be, level, msg);
5250 return 0;
5251}
5252
5253__LJMP static int hlua_txn_log_debug(lua_State *L)
5254{
5255 const char *msg;
5256 struct hlua_txn *htxn;
5257
5258 MAY_LJMP(check_args(L, 2, "Debug"));
5259 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5260 msg = MAY_LJMP(luaL_checkstring(L, 2));
5261 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5262 return 0;
5263}
5264
5265__LJMP static int hlua_txn_log_info(lua_State *L)
5266{
5267 const char *msg;
5268 struct hlua_txn *htxn;
5269
5270 MAY_LJMP(check_args(L, 2, "Info"));
5271 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5272 msg = MAY_LJMP(luaL_checkstring(L, 2));
5273 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5274 return 0;
5275}
5276
5277__LJMP static int hlua_txn_log_warning(lua_State *L)
5278{
5279 const char *msg;
5280 struct hlua_txn *htxn;
5281
5282 MAY_LJMP(check_args(L, 2, "Warning"));
5283 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5284 msg = MAY_LJMP(luaL_checkstring(L, 2));
5285 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5286 return 0;
5287}
5288
5289__LJMP static int hlua_txn_log_alert(lua_State *L)
5290{
5291 const char *msg;
5292 struct hlua_txn *htxn;
5293
5294 MAY_LJMP(check_args(L, 2, "Alert"));
5295 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5296 msg = MAY_LJMP(luaL_checkstring(L, 2));
5297 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5298 return 0;
5299}
5300
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005301__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5302{
5303 struct hlua_txn *htxn;
5304 int ll;
5305
5306 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5307 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5308 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5309
5310 if (ll < 0 || ll > 7)
5311 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5312
5313 htxn->s->logs.level = ll;
5314 return 0;
5315}
5316
5317__LJMP static int hlua_txn_set_tos(lua_State *L)
5318{
5319 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005320 int tos;
5321
5322 MAY_LJMP(check_args(L, 2, "set_tos"));
5323 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5324 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5325
Willy Tarreau1a18b542018-12-11 16:37:42 +01005326 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005327 return 0;
5328}
5329
5330__LJMP static int hlua_txn_set_mark(lua_State *L)
5331{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005332 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005333 int mark;
5334
5335 MAY_LJMP(check_args(L, 2, "set_mark"));
5336 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5337 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5338
Lukas Tribus579e3e32019-08-11 18:03:45 +02005339 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005340 return 0;
5341}
5342
Patrick Hemmer268a7072018-05-11 12:52:31 -04005343__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5344{
5345 struct hlua_txn *htxn;
5346
5347 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5348 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5349 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5350 return 0;
5351}
5352
5353__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5354{
5355 struct hlua_txn *htxn;
5356
5357 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5358 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5359 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5360 return 0;
5361}
5362
Christopher Faulet700d9e82020-01-31 12:21:52 +01005363/* Forward the Reply object to the client. This function converts the reply in
5364 * HTX an push it to into the response channel. It is response to foward the
5365 * message and terminate the transaction. It returns 1 on success and 0 on
5366 * error. The Reply must be on top of the stack.
5367 */
5368__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
5369{
5370 struct htx *htx;
5371 struct htx_sl *sl;
5372 struct h1m h1m;
5373 const char *status, *reason, *body;
5374 size_t status_len, reason_len, body_len;
5375 int ret, code, flags;
5376
5377 code = 200;
5378 status = "200";
5379 status_len = 3;
5380 ret = lua_getfield(L, -1, "status");
5381 if (ret == LUA_TNUMBER) {
5382 code = lua_tointeger(L, -1);
5383 status = lua_tolstring(L, -1, &status_len);
5384 }
5385 lua_pop(L, 1);
5386
5387 reason = http_get_reason(code);
5388 reason_len = strlen(reason);
5389 ret = lua_getfield(L, -1, "reason");
5390 if (ret == LUA_TSTRING)
5391 reason = lua_tolstring(L, -1, &reason_len);
5392 lua_pop(L, 1);
5393
5394 body = NULL;
5395 body_len = 0;
5396 ret = lua_getfield(L, -1, "body");
5397 if (ret == LUA_TSTRING)
5398 body = lua_tolstring(L, -1, &body_len);
5399 lua_pop(L, 1);
5400
5401 /* Prepare the response before inserting the headers */
5402 h1m_init_res(&h1m);
5403 htx = htx_from_buf(&s->res.buf);
5404 channel_htx_truncate(&s->res, htx);
5405 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
5406 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5407 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
5408 ist2(status, status_len), ist2(reason, reason_len));
5409 }
5410 else {
5411 flags = HTX_SL_F_IS_RESP;
5412 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
5413 ist2(status, status_len), ist2(reason, reason_len));
5414 }
5415 if (!sl)
5416 goto fail;
5417 sl->info.res.status = code;
5418
5419 /* Push in the stack the "headers" entry. */
5420 ret = lua_getfield(L, -1, "headers");
5421 if (ret != LUA_TTABLE)
5422 goto skip_headers;
5423
5424 lua_pushnil(L);
5425 while (lua_next(L, -2) != 0) {
5426 struct ist name, value;
5427 const char *n, *v;
5428 size_t nlen, vlen;
5429
5430 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
5431 /* Skip element if the key is not a string or if the value is not a table */
5432 goto next_hdr;
5433 }
5434
5435 n = lua_tolstring(L, -2, &nlen);
5436 name = ist2(n, nlen);
5437 if (isteqi(name, ist("content-length"))) {
5438 /* Always skip content-length header. It will be added
5439 * later with the correct len
5440 */
5441 goto next_hdr;
5442 }
5443
5444 /* Loop on header's values */
5445 lua_pushnil(L);
5446 while (lua_next(L, -2)) {
5447 if (!lua_isstring(L, -1)) {
5448 /* Skip the value if it is not a string */
5449 goto next_value;
5450 }
5451
5452 v = lua_tolstring(L, -1, &vlen);
5453 value = ist2(v, vlen);
5454
5455 if (isteqi(name, ist("transfer-encoding")))
5456 h1_parse_xfer_enc_header(&h1m, value);
5457 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
5458 goto fail;
5459
5460 next_value:
5461 lua_pop(L, 1);
5462 }
5463
5464 next_hdr:
5465 lua_pop(L, 1);
5466 }
5467 skip_headers:
5468 lua_pop(L, 1);
5469
5470 /* Update h1m flags: CLEN is set if CHNK is not present */
5471 if (!(h1m.flags & H1_MF_CHNK)) {
5472 const char *clen = ultoa(body_len);
5473
5474 h1m.flags |= H1_MF_CLEN;
5475 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
5476 goto fail;
5477 }
5478 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5479 h1m.flags |= H1_MF_XFER_LEN;
5480
5481 /* Update HTX start-line flags */
5482 if (h1m.flags & H1_MF_XFER_ENC)
5483 flags |= HTX_SL_F_XFER_ENC;
5484 if (h1m.flags & H1_MF_XFER_LEN) {
5485 flags |= HTX_SL_F_XFER_LEN;
5486 if (h1m.flags & H1_MF_CHNK)
5487 flags |= HTX_SL_F_CHNK;
5488 else if (h1m.flags & H1_MF_CLEN)
5489 flags |= HTX_SL_F_CLEN;
5490 if (h1m.body_len == 0)
5491 flags |= HTX_SL_F_BODYLESS;
5492 }
5493 sl->flags |= flags;
5494
5495
5496 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
5497 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))) ||
5498 !htx_add_endof(htx, HTX_BLK_EOM))
5499 goto fail;
5500
5501 /* Now, forward the response and terminate the transaction */
5502 s->txn->status = code;
5503 htx_to_buf(htx, &s->res.buf);
5504 if (!http_forward_proxy_resp(s, 1))
5505 goto fail;
5506
5507 return 1;
5508
5509 fail:
5510 channel_htx_truncate(&s->res, htx);
5511 return 0;
5512}
5513
5514/* Terminate a transaction if called from a lua action. For TCP streams,
5515 * processing is just aborted. Nothing is returned to the client and all
5516 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
5517 * is forwarded to the client before terminating the transaction. On success,
5518 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
5519 * with ACT_RET_ERR code. If this function is not called from a lua action, it
5520 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005521 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005522__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005523{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005524 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01005525 struct stream *s;
5526 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005527
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005528 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005529
Christopher Faulet700d9e82020-01-31 12:21:52 +01005530 /* If the flags NOTERM is set, we cannot terminate the session, so we
5531 * just end the execution of the current lua code. */
5532 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005533 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005534
Christopher Faulet700d9e82020-01-31 12:21:52 +01005535 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005536 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01005537 struct channel *req = &s->req;
5538 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005539
Christopher Faulet700d9e82020-01-31 12:21:52 +01005540 channel_auto_read(req);
5541 channel_abort(req);
5542 channel_auto_close(req);
5543 channel_erase(req);
5544
5545 res->wex = tick_add_ifset(now_ms, res->wto);
5546 channel_auto_read(res);
5547 channel_auto_close(res);
5548 channel_shutr_now(res);
5549
5550 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
5551 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005552 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005553
Christopher Faulet700d9e82020-01-31 12:21:52 +01005554 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
5555 /* No reply or invalid reply */
5556 s->txn->status = 0;
5557 http_reply_and_close(s, 0, NULL);
5558 }
5559 else {
5560 /* Remove extra args to have the reply on top of the stack */
5561 if (lua_gettop(L) > 2)
5562 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005563
Christopher Faulet700d9e82020-01-31 12:21:52 +01005564 if (!hlua_txn_forward_reply(L, s)) {
5565 if (!(s->flags & SF_ERR_MASK))
5566 s->flags |= SF_ERR_PRXCOND;
5567 lua_pushinteger(L, ACT_RET_ERR);
5568 WILL_LJMP(hlua_done(L));
5569 return 0; /* Never reached */
5570 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02005571 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005572
Christopher Faulet700d9e82020-01-31 12:21:52 +01005573 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
5574 if (htxn->dir == SMP_OPT_DIR_REQ) {
5575 /* let's log the request time */
5576 s->logs.tv_request = now;
5577 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
5578 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
5579 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005580
Christopher Faulet700d9e82020-01-31 12:21:52 +01005581 done:
5582 if (!(s->flags & SF_ERR_MASK))
5583 s->flags |= SF_ERR_LOCAL;
5584 if (!(s->flags & SF_FINST_MASK))
5585 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005586
Christopher Faulet4ad73102020-03-05 11:07:31 +01005587 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005588 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005589 return 0;
5590}
5591
Christopher Faulet700d9e82020-01-31 12:21:52 +01005592/*
5593 *
5594 *
5595 * Class REPLY
5596 *
5597 *
5598 */
5599
5600/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
5601 * free slots, the function fails and returns 0;
5602 */
5603static int hlua_txn_reply_new(lua_State *L)
5604{
5605 struct hlua_txn *htxn;
5606 const char *reason, *body = NULL;
5607 int ret, status;
5608
5609 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005610 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01005611 hlua_pusherror(L, "txn object is not an HTTP transaction.");
5612 WILL_LJMP(lua_error(L));
5613 }
5614
5615 /* Default value */
5616 status = 200;
5617 reason = http_get_reason(status);
5618
5619 if (lua_istable(L, 2)) {
5620 /* load status and reason from the table argument at index 2 */
5621 ret = lua_getfield(L, 2, "status");
5622 if (ret == LUA_TNIL)
5623 goto reason;
5624 else if (ret != LUA_TNUMBER) {
5625 /* invalid status: ignore the reason */
5626 goto body;
5627 }
5628 status = lua_tointeger(L, -1);
5629
5630 reason:
5631 lua_pop(L, 1); /* restore the stack: remove status */
5632 ret = lua_getfield(L, 2, "reason");
5633 if (ret == LUA_TSTRING)
5634 reason = lua_tostring(L, -1);
5635
5636 body:
5637 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
5638 ret = lua_getfield(L, 2, "body");
5639 if (ret == LUA_TSTRING)
5640 body = lua_tostring(L, -1);
5641 lua_pop(L, 1); /* restore the stack: remove body */
5642 }
5643
5644 /* Create the Reply table */
5645 lua_newtable(L);
5646
5647 /* Add status element */
5648 lua_pushstring(L, "status");
5649 lua_pushinteger(L, status);
5650 lua_settable(L, -3);
5651
5652 /* Add reason element */
5653 reason = http_get_reason(status);
5654 lua_pushstring(L, "reason");
5655 lua_pushstring(L, reason);
5656 lua_settable(L, -3);
5657
5658 /* Add body element, nil if undefined */
5659 lua_pushstring(L, "body");
5660 if (body)
5661 lua_pushstring(L, body);
5662 else
5663 lua_pushnil(L);
5664 lua_settable(L, -3);
5665
5666 /* Add headers element */
5667 lua_pushstring(L, "headers");
5668 lua_newtable(L);
5669
5670 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
5671 if (lua_istable(L, 2)) {
5672 /* load headers from the table argument at index 2. If it is a table, copy it. */
5673 ret = lua_getfield(L, 2, "headers");
5674 if (ret == LUA_TTABLE) {
5675 /* stack: [ ... <headers:table>, <table> ] */
5676 lua_pushnil(L);
5677 while (lua_next(L, -2) != 0) {
5678 /* stack: [ ... <headers:table>, <table>, k, v] */
5679 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
5680 /* invalid value type, skip it */
5681 lua_pop(L, 1);
5682 continue;
5683 }
5684
5685
5686 /* Duplicate the key and swap it with the value. */
5687 lua_pushvalue(L, -2);
5688 lua_insert(L, -2);
5689 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
5690
5691 lua_newtable(L);
5692 lua_insert(L, -2);
5693 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
5694
5695 if (lua_isstring(L, -1)) {
5696 /* push the value in the inner table */
5697 lua_rawseti(L, -2, 1);
5698 }
5699 else { /* table */
5700 lua_pushnil(L);
5701 while (lua_next(L, -2) != 0) {
5702 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
5703 if (!lua_isstring(L, -1)) {
5704 /* invalid value type, skip it*/
5705 lua_pop(L, 1);
5706 continue;
5707 }
5708 /* push the value in the inner table */
5709 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
5710 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
5711 }
5712 lua_pop(L, 1);
5713 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
5714 }
5715
5716 /* push (k,v) on the stack in the headers table:
5717 * stack: [ ... <headers:table>, <table>, k, k, v ]
5718 */
5719 lua_settable(L, -5);
5720 /* stack: [ ... <headers:table>, <table>, k ] */
5721 }
5722 }
5723 lua_pop(L, 1);
5724 }
5725 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
5726 lua_settable(L, -3);
5727 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
5728
5729 /* Pop a class sesison metatable and affect it to the userdata. */
5730 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
5731 lua_setmetatable(L, -2);
5732 return 1;
5733}
5734
5735/* Set the reply status code, and optionally the reason. If no reason is
5736 * provided, the default one corresponding to the status code is used.
5737 */
5738__LJMP static int hlua_txn_reply_set_status(lua_State *L)
5739{
5740 int status = MAY_LJMP(luaL_checkinteger(L, 2));
5741 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5742
5743 /* First argument (self) must be a table */
5744 luaL_checktype(L, 1, LUA_TTABLE);
5745
5746 if (status < 100 || status > 599) {
5747 lua_pushboolean(L, 0);
5748 return 1;
5749 }
5750 if (!reason)
5751 reason = http_get_reason(status);
5752
5753 lua_pushinteger(L, status);
5754 lua_setfield(L, 1, "status");
5755
5756 lua_pushstring(L, reason);
5757 lua_setfield(L, 1, "reason");
5758
5759 lua_pushboolean(L, 1);
5760 return 1;
5761}
5762
5763/* Add a header into the reply object. Each header name is associated to an
5764 * array of values in the "headers" table. If the header name is not found, a
5765 * new entry is created.
5766 */
5767__LJMP static int hlua_txn_reply_add_header(lua_State *L)
5768{
5769 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
5770 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
5771 int ret;
5772
5773 /* First argument (self) must be a table */
5774 luaL_checktype(L, 1, LUA_TTABLE);
5775
5776 /* Push in the stack the "headers" entry. */
5777 ret = lua_getfield(L, 1, "headers");
5778 if (ret != LUA_TTABLE) {
5779 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
5780 WILL_LJMP(lua_error(L));
5781 }
5782
5783 /* check if the header is already registered. If not, register it. */
5784 ret = lua_getfield(L, -1, name);
5785 if (ret == LUA_TNIL) {
5786 /* Entry not found. */
5787 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
5788
5789 /* Insert the new header name in the array in the top of the stack.
5790 * It left the new array in the top of the stack.
5791 */
5792 lua_newtable(L);
5793 lua_pushstring(L, name);
5794 lua_pushvalue(L, -2);
5795 lua_settable(L, -4);
5796 }
5797 else if (ret != LUA_TTABLE) {
5798 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
5799 WILL_LJMP(lua_error(L));
5800 }
5801
5802 /* Now the top od thestack is an array of values. We push
5803 * the header value as new entry.
5804 */
5805 lua_pushstring(L, value);
5806 ret = lua_rawlen(L, -2);
5807 lua_rawseti(L, -2, ret + 1);
5808
5809 lua_pushboolean(L, 1);
5810 return 1;
5811}
5812
5813/* Remove all occurrences of a given header name. */
5814__LJMP static int hlua_txn_reply_del_header(lua_State *L)
5815{
5816 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
5817 int ret;
5818
5819 /* First argument (self) must be a table */
5820 luaL_checktype(L, 1, LUA_TTABLE);
5821
5822 /* Push in the stack the "headers" entry. */
5823 ret = lua_getfield(L, 1, "headers");
5824 if (ret != LUA_TTABLE) {
5825 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
5826 WILL_LJMP(lua_error(L));
5827 }
5828
5829 lua_pushstring(L, name);
5830 lua_pushnil(L);
5831 lua_settable(L, -3);
5832
5833 lua_pushboolean(L, 1);
5834 return 1;
5835}
5836
5837/* Set the reply's body. Overwrite any existing entry. */
5838__LJMP static int hlua_txn_reply_set_body(lua_State *L)
5839{
5840 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
5841
5842 /* First argument (self) must be a table */
5843 luaL_checktype(L, 1, LUA_TTABLE);
5844
5845 lua_pushstring(L, payload);
5846 lua_setfield(L, 1, "body");
5847
5848 lua_pushboolean(L, 1);
5849 return 1;
5850}
5851
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005852__LJMP static int hlua_log(lua_State *L)
5853{
5854 int level;
5855 const char *msg;
5856
5857 MAY_LJMP(check_args(L, 2, "log"));
5858 level = MAY_LJMP(luaL_checkinteger(L, 1));
5859 msg = MAY_LJMP(luaL_checkstring(L, 2));
5860
5861 if (level < 0 || level >= NB_LOG_LEVELS)
5862 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5863
5864 hlua_sendlog(NULL, level, msg);
5865 return 0;
5866}
5867
5868__LJMP static int hlua_log_debug(lua_State *L)
5869{
5870 const char *msg;
5871
5872 MAY_LJMP(check_args(L, 1, "debug"));
5873 msg = MAY_LJMP(luaL_checkstring(L, 1));
5874 hlua_sendlog(NULL, LOG_DEBUG, msg);
5875 return 0;
5876}
5877
5878__LJMP static int hlua_log_info(lua_State *L)
5879{
5880 const char *msg;
5881
5882 MAY_LJMP(check_args(L, 1, "info"));
5883 msg = MAY_LJMP(luaL_checkstring(L, 1));
5884 hlua_sendlog(NULL, LOG_INFO, msg);
5885 return 0;
5886}
5887
5888__LJMP static int hlua_log_warning(lua_State *L)
5889{
5890 const char *msg;
5891
5892 MAY_LJMP(check_args(L, 1, "warning"));
5893 msg = MAY_LJMP(luaL_checkstring(L, 1));
5894 hlua_sendlog(NULL, LOG_WARNING, msg);
5895 return 0;
5896}
5897
5898__LJMP static int hlua_log_alert(lua_State *L)
5899{
5900 const char *msg;
5901
5902 MAY_LJMP(check_args(L, 1, "alert"));
5903 msg = MAY_LJMP(luaL_checkstring(L, 1));
5904 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005905 return 0;
5906}
5907
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005908__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005909{
5910 int wakeup_ms = lua_tointeger(L, -1);
5911 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02005912 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005913 return 0;
5914}
5915
5916__LJMP static int hlua_sleep(lua_State *L)
5917{
5918 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005919 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005920
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005921 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005922
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005923 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005924 wakeup_ms = tick_add(now_ms, delay);
5925 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005926
Willy Tarreau9635e032018-10-16 17:52:55 +02005927 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005928 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005929}
5930
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005931__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005932{
5933 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005934 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005935
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005936 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005937
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005938 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005939 wakeup_ms = tick_add(now_ms, delay);
5940 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005941
Willy Tarreau9635e032018-10-16 17:52:55 +02005942 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005943 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005944}
5945
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005946/* This functionis an LUA binding. it permits to give back
5947 * the hand at the HAProxy scheduler. It is used when the
5948 * LUA processing consumes a lot of time.
5949 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005950__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005951{
5952 return 0;
5953}
5954
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005955__LJMP static int hlua_yield(lua_State *L)
5956{
Willy Tarreau9635e032018-10-16 17:52:55 +02005957 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005958 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005959}
5960
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005961/* This function change the nice of the currently executed
5962 * task. It is used set low or high priority at the current
5963 * task.
5964 */
Willy Tarreau59551662015-03-10 14:23:13 +01005965__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005966{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005967 struct hlua *hlua;
5968 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005969
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005970 MAY_LJMP(check_args(L, 1, "set_nice"));
5971 hlua = hlua_gethlua(L);
5972 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005973
5974 /* If he task is not set, I'm in a start mode. */
5975 if (!hlua || !hlua->task)
5976 return 0;
5977
5978 if (nice < -1024)
5979 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005980 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005981 nice = 1024;
5982
5983 hlua->task->nice = nice;
5984 return 0;
5985}
5986
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005987/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005988 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5989 * return an E_AGAIN signal, the emmiter of this signal must set a
5990 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005991 *
5992 * Task wrapper are longjmp safe because the only one Lua code
5993 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005994 */
Willy Tarreau60409db2019-08-21 14:14:50 +02005995struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005996{
Olivier Houchard9f6af332018-05-25 14:04:04 +02005997 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005998 enum hlua_exec status;
5999
Christopher Faulet5bc99722018-04-25 10:34:45 +02006000 if (task->thread_mask == MAX_THREADS_MASK)
6001 task_set_affinity(task, tid_bit);
6002
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006003 /* If it is the first call to the task, we must initialize the
6004 * execution timeouts.
6005 */
6006 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006007 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006008
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006009 /* Execute the Lua code. */
6010 status = hlua_ctx_resume(hlua, 1);
6011
6012 switch (status) {
6013 /* finished or yield */
6014 case HLUA_E_OK:
6015 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006016 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006017 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006018 break;
6019
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006020 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006021 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006022 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006023 break;
6024
6025 /* finished with error. */
6026 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006027 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006028 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006029 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006030 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006031 break;
6032
6033 case HLUA_E_ERR:
6034 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006035 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006036 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006037 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006038 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006039 break;
6040 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006041 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006042}
6043
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006044/* This function is an LUA binding that register LUA function to be
6045 * executed after the HAProxy configuration parsing and before the
6046 * HAProxy scheduler starts. This function expect only one LUA
6047 * argument that is a function. This function returns nothing, but
6048 * throws if an error is encountered.
6049 */
6050__LJMP static int hlua_register_init(lua_State *L)
6051{
6052 struct hlua_init_function *init;
6053 int ref;
6054
6055 MAY_LJMP(check_args(L, 1, "register_init"));
6056
6057 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6058
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006059 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006060 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006061 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006062
6063 init->function_ref = ref;
6064 LIST_ADDQ(&hlua_init_functions, &init->l);
6065 return 0;
6066}
6067
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006068/* This functio is an LUA binding. It permits to register a task
6069 * executed in parallel of the main HAroxy activity. The task is
6070 * created and it is set in the HAProxy scheduler. It can be called
6071 * from the "init" section, "post init" or during the runtime.
6072 *
6073 * Lua prototype:
6074 *
6075 * <none> core.register_task(<function>)
6076 */
6077static int hlua_register_task(lua_State *L)
6078{
6079 struct hlua *hlua;
6080 struct task *task;
6081 int ref;
6082
6083 MAY_LJMP(check_args(L, 1, "register_task"));
6084
6085 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6086
Willy Tarreaubafbe012017-11-24 17:34:44 +01006087 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006088 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006089 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006090
Emeric Brunc60def82017-09-27 14:59:38 +02006091 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006092 if (!task)
6093 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6094
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006095 task->context = hlua;
6096 task->process = hlua_process_task;
6097
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006098 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006099 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006100
6101 /* Restore the function in the stack. */
6102 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6103 hlua->nargs = 0;
6104
6105 /* Schedule task. */
6106 task_schedule(task, now_ms);
6107
6108 return 0;
6109}
6110
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006111/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6112 * doesn't allow "yield" functions because the HAProxy engine cannot
6113 * resume converters.
6114 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006115static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006116{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006117 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006118 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006119 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006120
Willy Tarreaube508f12016-03-10 11:47:01 +01006121 if (!stream)
6122 return 0;
6123
Willy Tarreau87b09662015-04-03 00:22:06 +02006124 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006125 * Lua context can be not initialized. This behavior
6126 * permits to save performances because a systematic
6127 * Lua initialization cause 5% performances loss.
6128 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006129 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006130 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006131 if (!stream->hlua) {
6132 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6133 return 0;
6134 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006135 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006136 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6137 return 0;
6138 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006139 }
6140
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006141 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006142 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006143
6144 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006145 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6146 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6147 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006148 else
6149 error = "critical error";
6150 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006151 return 0;
6152 }
6153
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006154 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006155 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006156 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006157 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006158 return 0;
6159 }
6160
6161 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006162 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006163
6164 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006165 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006166 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006167 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006168 return 0;
6169 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006170 hlua_smp2lua(stream->hlua->T, smp);
6171 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006172
6173 /* push keywords in the stack. */
6174 if (arg_p) {
6175 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006176 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006177 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006178 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006179 return 0;
6180 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006181 hlua_arg2lua(stream->hlua->T, arg_p);
6182 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006183 }
6184 }
6185
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006186 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006187 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006188
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006189 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006190 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006191 }
6192
6193 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006194 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006195 /* finished. */
6196 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006197 /* If the stack is empty, the function fails. */
6198 if (lua_gettop(stream->hlua->T) <= 0)
6199 return 0;
6200
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006201 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006202 hlua_lua2smp(stream->hlua->T, -1, smp);
6203 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006204 return 1;
6205
6206 /* yield. */
6207 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006208 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006209 return 0;
6210
6211 /* finished with error. */
6212 case HLUA_E_ERRMSG:
6213 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006214 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006215 fcn->name, lua_tostring(stream->hlua->T, -1));
6216 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006217 return 0;
6218
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006219 case HLUA_E_ETMOUT:
6220 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6221 return 0;
6222
6223 case HLUA_E_NOMEM:
6224 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6225 return 0;
6226
6227 case HLUA_E_YIELD:
6228 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6229 return 0;
6230
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006231 case HLUA_E_ERR:
6232 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006233 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006234
6235 default:
6236 return 0;
6237 }
6238}
6239
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006240/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6241 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006242 * resume sample-fetches. This function will be called by the sample
6243 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006244 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006245static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6246 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006247{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006248 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006249 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006250 const char *error;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006251 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006252
Willy Tarreaube508f12016-03-10 11:47:01 +01006253 if (!stream)
6254 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006255
Willy Tarreau87b09662015-04-03 00:22:06 +02006256 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006257 * Lua context can be not initialized. This behavior
6258 * permits to save performances because a systematic
6259 * Lua initialization cause 5% performances loss.
6260 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006261 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006262 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006263 if (!stream->hlua) {
6264 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6265 return 0;
6266 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006267 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006268 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6269 return 0;
6270 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006271 }
6272
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006273 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006274 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006275
6276 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006277 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6278 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6279 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006280 else
6281 error = "critical error";
6282 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006283 return 0;
6284 }
6285
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006286 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006287 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006288 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006289 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006290 return 0;
6291 }
6292
6293 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006294 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006295
6296 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006297 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006298 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006299 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006300 return 0;
6301 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006302 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006303
6304 /* push keywords in the stack. */
6305 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6306 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006307 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006308 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006309 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006310 return 0;
6311 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006312 hlua_arg2lua(stream->hlua->T, arg_p);
6313 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006314 }
6315
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006316 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006317 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006318
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006319 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006320 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006321 }
6322
6323 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006324 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006325 /* finished. */
6326 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006327 /* If the stack is empty, the function fails. */
6328 if (lua_gettop(stream->hlua->T) <= 0)
6329 return 0;
6330
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006331 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006332 hlua_lua2smp(stream->hlua->T, -1, smp);
6333 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006334
6335 /* Set the end of execution flag. */
6336 smp->flags &= ~SMP_F_MAY_CHANGE;
6337 return 1;
6338
6339 /* yield. */
6340 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006341 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006342 return 0;
6343
6344 /* finished with error. */
6345 case HLUA_E_ERRMSG:
6346 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006347 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006348 fcn->name, lua_tostring(stream->hlua->T, -1));
6349 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006350 return 0;
6351
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006352 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006353 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6354 return 0;
6355
6356 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006357 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6358 return 0;
6359
6360 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006361 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6362 return 0;
6363
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006364 case HLUA_E_ERR:
6365 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006366 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006367
6368 default:
6369 return 0;
6370 }
6371}
6372
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006373/* This function is an LUA binding used for registering
6374 * "sample-conv" functions. It expects a converter name used
6375 * in the haproxy configuration file, and an LUA function.
6376 */
6377__LJMP static int hlua_register_converters(lua_State *L)
6378{
6379 struct sample_conv_kw_list *sck;
6380 const char *name;
6381 int ref;
6382 int len;
6383 struct hlua_function *fcn;
6384
6385 MAY_LJMP(check_args(L, 2, "register_converters"));
6386
6387 /* First argument : converter name. */
6388 name = MAY_LJMP(luaL_checkstring(L, 1));
6389
6390 /* Second argument : lua function. */
6391 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6392
6393 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006394 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006395 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006396 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006397 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006398 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006399 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006400
6401 /* Fill fcn. */
6402 fcn->name = strdup(name);
6403 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006404 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006405 fcn->function_ref = ref;
6406
6407 /* List head */
6408 sck->list.n = sck->list.p = NULL;
6409
6410 /* converter keyword. */
6411 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006412 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006413 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006414 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006415
6416 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6417 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006418 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 +01006419 sck->kw[0].val_args = NULL;
6420 sck->kw[0].in_type = SMP_T_STR;
6421 sck->kw[0].out_type = SMP_T_STR;
6422 sck->kw[0].private = fcn;
6423
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006424 /* Register this new converter */
6425 sample_register_convs(sck);
6426
6427 return 0;
6428}
6429
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006430/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006431 * "sample-fetch" functions. It expects a converter name used
6432 * in the haproxy configuration file, and an LUA function.
6433 */
6434__LJMP static int hlua_register_fetches(lua_State *L)
6435{
6436 const char *name;
6437 int ref;
6438 int len;
6439 struct sample_fetch_kw_list *sfk;
6440 struct hlua_function *fcn;
6441
6442 MAY_LJMP(check_args(L, 2, "register_fetches"));
6443
6444 /* First argument : sample-fetch name. */
6445 name = MAY_LJMP(luaL_checkstring(L, 1));
6446
6447 /* Second argument : lua function. */
6448 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6449
6450 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006451 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006452 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006453 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006454 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006455 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006456 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006457
6458 /* Fill fcn. */
6459 fcn->name = strdup(name);
6460 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006461 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006462 fcn->function_ref = ref;
6463
6464 /* List head */
6465 sfk->list.n = sfk->list.p = NULL;
6466
6467 /* sample-fetch keyword. */
6468 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006469 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006470 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006471 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006472
6473 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6474 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006475 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 +01006476 sfk->kw[0].val_args = NULL;
6477 sfk->kw[0].out_type = SMP_T_STR;
6478 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6479 sfk->kw[0].val = 0;
6480 sfk->kw[0].private = fcn;
6481
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006482 /* Register this new fetch. */
6483 sample_register_fetches(sfk);
6484
6485 return 0;
6486}
6487
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006488/* This function is a lua binding to set the wake_time from an action. It is
6489 * only used if the action return ACT_RET_YIELD.
6490 */
6491__LJMP static int hlua_action_wake_time(lua_State *L)
6492{
6493 struct hlua *hlua = hlua_gethlua(L);
6494 unsigned int delay;
6495 unsigned int wakeup_ms;
6496
6497 MAY_LJMP(check_args(L, 1, "wake_time"));
6498
6499 delay = MAY_LJMP(luaL_checkinteger(L, 1));
6500 wakeup_ms = tick_add(now_ms, delay);
6501 hlua->wake_time = wakeup_ms;
6502 return 0;
6503}
6504
6505
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006506/* This function is a wrapper to execute each LUA function declared as an action
6507 * wrapper during the initialisation period. This function may return any
6508 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
6509 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
6510 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006511 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006512static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006513 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006514{
6515 char **arg;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006516 unsigned int hflags = 0;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006517 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006518 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006519
6520 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006521 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
6522 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
6523 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
6524 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006525 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006526 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006527 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006528 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006529
Willy Tarreau87b09662015-04-03 00:22:06 +02006530 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006531 * Lua context can be not initialized. This behavior
6532 * permits to save performances because a systematic
6533 * Lua initialization cause 5% performances loss.
6534 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006535 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006536 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006537 if (!s->hlua) {
6538 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6539 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006540 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006541 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006542 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006543 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6544 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006545 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006546 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006547 }
6548
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006549 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006550 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006551
6552 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006553 if (!SET_SAFE_LJMP(s->hlua->T)) {
6554 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6555 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006556 else
6557 error = "critical error";
6558 SEND_ERR(px, "Lua function '%s': %s.\n",
6559 rule->arg.hlua_rule->fcn.name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006560 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006561 }
6562
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006563 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006564 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006565 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006566 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006567 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006568 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006569 }
6570
6571 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006572 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006573
Willy Tarreau87b09662015-04-03 00:22:06 +02006574 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006575 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006576 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006577 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006578 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006579 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006580 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006581 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006582
6583 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006584 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006585 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006586 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006587 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006588 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006589 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006590 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006591 lua_pushstring(s->hlua->T, *arg);
6592 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006593 }
6594
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006595 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006596 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006597
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006598 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006599 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006600 }
6601
6602 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01006603 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006604 /* finished. */
6605 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006606 /* Catch the return value */
6607 if (lua_gettop(s->hlua->T) > 0)
6608 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006609
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006610 /* Set timeout in the required channel. */
6611 if (act_ret == ACT_RET_YIELD && s->hlua->wake_time != TICK_ETERNITY) {
6612 if (dir == SMP_OPT_DIR_REQ)
6613 s->req.analyse_exp = s->hlua->wake_time;
6614 else
6615 s->res.analyse_exp = s->hlua->wake_time;
6616 }
6617 goto end;
6618
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006619 /* yield. */
6620 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006621 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006622 if (s->hlua->wake_time != TICK_ETERNITY) {
Christopher Faulet81921b12019-08-14 23:19:45 +02006623 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006624 s->req.analyse_exp = s->hlua->wake_time;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006625 else
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006626 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006627 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006628 /* Some actions can be wake up when a "write" event
6629 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006630 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006631 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02006632 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006633 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006634 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006635 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006636 act_ret = ACT_RET_YIELD;
6637 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006638
6639 /* finished with error. */
6640 case HLUA_E_ERRMSG:
6641 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006642 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006643 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6644 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006645 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006646
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006647 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006648 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006649 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006650
6651 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006652 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006653 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006654
6655 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006656 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6657 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006658 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006659
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006660 case HLUA_E_ERR:
6661 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006662 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006663 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006664
6665 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006666 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006667 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006668
6669 end:
6670 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006671}
6672
Olivier Houchard9f6af332018-05-25 14:04:04 +02006673struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006674{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006675 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006676
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006677 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006678 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006679 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006680}
6681
6682static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6683{
6684 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006685 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006686 struct task *task;
6687 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006688 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006689
Willy Tarreaubafbe012017-11-24 17:34:44 +01006690 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006691 if (!hlua) {
6692 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6693 ctx->rule->arg.hlua_rule->fcn.name);
6694 return 0;
6695 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006696 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006697 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006698 ctx->ctx.hlua_apptcp.flags = 0;
6699
6700 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006701 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006702 if (!task) {
6703 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6704 ctx->rule->arg.hlua_rule->fcn.name);
6705 return 0;
6706 }
6707 task->nice = 0;
6708 task->context = ctx;
6709 task->process = hlua_applet_wakeup;
6710 ctx->ctx.hlua_apptcp.task = task;
6711
6712 /* In the execution wrappers linked with a stream, the
6713 * Lua context can be not initialized. This behavior
6714 * permits to save performances because a systematic
6715 * Lua initialization cause 5% performances loss.
6716 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006717 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006718 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6719 ctx->rule->arg.hlua_rule->fcn.name);
6720 return 0;
6721 }
6722
6723 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006724 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006725
6726 /* The following Lua calls can fail. */
6727 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006728 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6729 error = lua_tostring(hlua->T, -1);
6730 else
6731 error = "critical error";
6732 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6733 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006734 return 0;
6735 }
6736
6737 /* Check stack available size. */
6738 if (!lua_checkstack(hlua->T, 1)) {
6739 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6740 ctx->rule->arg.hlua_rule->fcn.name);
6741 RESET_SAFE_LJMP(hlua->T);
6742 return 0;
6743 }
6744
6745 /* Restore the function in the stack. */
6746 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6747
6748 /* Create and and push object stream in the stack. */
6749 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6750 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6751 ctx->rule->arg.hlua_rule->fcn.name);
6752 RESET_SAFE_LJMP(hlua->T);
6753 return 0;
6754 }
6755 hlua->nargs = 1;
6756
6757 /* push keywords in the stack. */
6758 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6759 if (!lua_checkstack(hlua->T, 1)) {
6760 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6761 ctx->rule->arg.hlua_rule->fcn.name);
6762 RESET_SAFE_LJMP(hlua->T);
6763 return 0;
6764 }
6765 lua_pushstring(hlua->T, *arg);
6766 hlua->nargs++;
6767 }
6768
6769 RESET_SAFE_LJMP(hlua->T);
6770
6771 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006772 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01006773 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006774
6775 return 1;
6776}
6777
Willy Tarreau60409db2019-08-21 14:14:50 +02006778void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006779{
6780 struct stream_interface *si = ctx->owner;
6781 struct stream *strm = si_strm(si);
6782 struct channel *res = si_ic(si);
6783 struct act_rule *rule = ctx->rule;
6784 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006785 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006786
6787 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02006788 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
6789 /* eat the whole request */
6790 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006791 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02006792 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006793
6794 /* If the stream is disconnect or closed, ldo nothing. */
6795 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6796 return;
6797
6798 /* Execute the function. */
6799 switch (hlua_ctx_resume(hlua, 1)) {
6800 /* finished. */
6801 case HLUA_E_OK:
6802 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6803
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006804 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006805 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006806 res->flags |= CF_READ_NULL;
6807 si_shutr(si);
6808 return;
6809
6810 /* yield. */
6811 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006812 if (hlua->wake_time != TICK_ETERNITY)
6813 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006814 return;
6815
6816 /* finished with error. */
6817 case HLUA_E_ERRMSG:
6818 /* Display log. */
6819 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6820 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6821 lua_pop(hlua->T, 1);
6822 goto error;
6823
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006824 case HLUA_E_ETMOUT:
6825 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6826 rule->arg.hlua_rule->fcn.name);
6827 goto error;
6828
6829 case HLUA_E_NOMEM:
6830 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6831 rule->arg.hlua_rule->fcn.name);
6832 goto error;
6833
6834 case HLUA_E_YIELD: /* unexpected */
6835 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6836 rule->arg.hlua_rule->fcn.name);
6837 goto error;
6838
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006839 case HLUA_E_ERR:
6840 /* Display log. */
6841 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6842 rule->arg.hlua_rule->fcn.name);
6843 goto error;
6844
6845 default:
6846 goto error;
6847 }
6848
6849error:
6850
6851 /* For all other cases, just close the stream. */
6852 si_shutw(si);
6853 si_shutr(si);
6854 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6855}
6856
6857static void hlua_applet_tcp_release(struct appctx *ctx)
6858{
Olivier Houchard3f795f72019-04-17 22:51:06 +02006859 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006860 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006861 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006862 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006863}
6864
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006865/* The function returns 1 if the initialisation is complete, 0 if
6866 * an errors occurs and -1 if more data are required for initializing
6867 * the applet.
6868 */
6869static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6870{
6871 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006872 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006873 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006874 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006875 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006876 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006877
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006878 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01006879 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006880 if (!hlua) {
6881 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6882 ctx->rule->arg.hlua_rule->fcn.name);
6883 return 0;
6884 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006885 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006886 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006887 ctx->ctx.hlua_apphttp.left_bytes = -1;
6888 ctx->ctx.hlua_apphttp.flags = 0;
6889
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006890 if (txn->req.flags & HTTP_MSGF_VER_11)
6891 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6892
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006893 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006894 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006895 if (!task) {
6896 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6897 ctx->rule->arg.hlua_rule->fcn.name);
6898 return 0;
6899 }
6900 task->nice = 0;
6901 task->context = ctx;
6902 task->process = hlua_applet_wakeup;
6903 ctx->ctx.hlua_apphttp.task = task;
6904
6905 /* In the execution wrappers linked with a stream, the
6906 * Lua context can be not initialized. This behavior
6907 * permits to save performances because a systematic
6908 * Lua initialization cause 5% performances loss.
6909 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006910 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006911 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6912 ctx->rule->arg.hlua_rule->fcn.name);
6913 return 0;
6914 }
6915
6916 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006917 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006918
6919 /* The following Lua calls can fail. */
6920 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006921 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6922 error = lua_tostring(hlua->T, -1);
6923 else
6924 error = "critical error";
6925 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6926 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006927 return 0;
6928 }
6929
6930 /* Check stack available size. */
6931 if (!lua_checkstack(hlua->T, 1)) {
6932 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6933 ctx->rule->arg.hlua_rule->fcn.name);
6934 RESET_SAFE_LJMP(hlua->T);
6935 return 0;
6936 }
6937
6938 /* Restore the function in the stack. */
6939 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6940
6941 /* Create and and push object stream in the stack. */
6942 if (!hlua_applet_http_new(hlua->T, ctx)) {
6943 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6944 ctx->rule->arg.hlua_rule->fcn.name);
6945 RESET_SAFE_LJMP(hlua->T);
6946 return 0;
6947 }
6948 hlua->nargs = 1;
6949
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006950 /* push keywords in the stack. */
6951 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6952 if (!lua_checkstack(hlua->T, 1)) {
6953 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6954 ctx->rule->arg.hlua_rule->fcn.name);
6955 RESET_SAFE_LJMP(hlua->T);
6956 return 0;
6957 }
6958 lua_pushstring(hlua->T, *arg);
6959 hlua->nargs++;
6960 }
6961
6962 RESET_SAFE_LJMP(hlua->T);
6963
6964 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006965 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006966
6967 return 1;
6968}
6969
Willy Tarreau60409db2019-08-21 14:14:50 +02006970void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006971{
6972 struct stream_interface *si = ctx->owner;
6973 struct stream *strm = si_strm(si);
6974 struct channel *req = si_oc(si);
6975 struct channel *res = si_ic(si);
6976 struct act_rule *rule = ctx->rule;
6977 struct proxy *px = strm->be;
6978 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
6979 struct htx *req_htx, *res_htx;
6980
6981 res_htx = htx_from_buf(&res->buf);
6982
6983 /* If the stream is disconnect or closed, ldo nothing. */
6984 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6985 goto out;
6986
6987 /* Check if the input buffer is avalaible. */
6988 if (!b_size(&res->buf)) {
6989 si_rx_room_blk(si);
6990 goto out;
6991 }
6992 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01006993 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006994 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6995
6996 /* Set the currently running flag. */
6997 if (!HLUA_IS_RUNNING(hlua) &&
6998 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6999 struct htx_blk *blk;
7000 size_t count = co_data(req);
7001
7002 if (!count) {
7003 si_cant_get(si);
7004 goto out;
7005 }
7006
7007 /* We need to flush the request header. This left the body for
7008 * the Lua.
7009 */
7010 req_htx = htx_from_buf(&req->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02007011 blk = htx_get_first_blk(req_htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007012 while (count && blk) {
7013 enum htx_blk_type type = htx_get_blk_type(blk);
7014 uint32_t sz = htx_get_blksz(blk);
7015
7016 if (sz > count) {
7017 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007018 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007019 goto out;
7020 }
7021
7022 count -= sz;
7023 co_set_data(req, co_data(req) - sz);
7024 blk = htx_remove_blk(req_htx, blk);
7025
7026 if (type == HTX_BLK_EOH)
7027 break;
7028 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007029 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007030 }
7031
7032 /* Executes The applet if it is not done. */
7033 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7034
7035 /* Execute the function. */
7036 switch (hlua_ctx_resume(hlua, 1)) {
7037 /* finished. */
7038 case HLUA_E_OK:
7039 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7040 break;
7041
7042 /* yield. */
7043 case HLUA_E_AGAIN:
7044 if (hlua->wake_time != TICK_ETERNITY)
7045 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007046 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007047
7048 /* finished with error. */
7049 case HLUA_E_ERRMSG:
7050 /* Display log. */
7051 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7052 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7053 lua_pop(hlua->T, 1);
7054 goto error;
7055
7056 case HLUA_E_ETMOUT:
7057 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7058 rule->arg.hlua_rule->fcn.name);
7059 goto error;
7060
7061 case HLUA_E_NOMEM:
7062 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7063 rule->arg.hlua_rule->fcn.name);
7064 goto error;
7065
7066 case HLUA_E_YIELD: /* unexpected */
7067 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7068 rule->arg.hlua_rule->fcn.name);
7069 goto error;
7070
7071 case HLUA_E_ERR:
7072 /* Display log. */
7073 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7074 rule->arg.hlua_rule->fcn.name);
7075 goto error;
7076
7077 default:
7078 goto error;
7079 }
7080 }
7081
7082 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007083 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7084 goto done;
7085
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007086 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7087 goto error;
7088
Christopher Faulet54b5e212019-06-04 10:08:28 +02007089 /* Don't add TLR because mux-h1 will take care of it */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007090 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7091 si_rx_room_blk(si);
7092 goto out;
7093 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007094 channel_add_input(res, 1);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007095 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7096 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007097 }
7098
7099 done:
7100 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007101 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007102 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007103 si_shutr(si);
7104 }
7105
7106 /* eat the whole request */
7107 if (co_data(req)) {
7108 req_htx = htx_from_buf(&req->buf);
7109 co_htx_skip(req, req_htx, co_data(req));
7110 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007111 }
7112 }
7113
7114 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007115 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007116 return;
7117
7118 error:
7119
7120 /* If we are in HTTP mode, and we are not send any
7121 * data, return a 500 server error in best effort:
7122 * if there is no room available in the buffer,
7123 * just close the connection.
7124 */
7125 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02007126 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007127
7128 channel_erase(res);
7129 res->buf.data = b_data(err);
7130 memcpy(res->buf.area, b_head(err), b_data(err));
7131 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007132 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007133 }
7134 if (!(strm->flags & SF_ERR_MASK))
7135 strm->flags |= SF_ERR_RESOURCE;
7136 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7137 goto done;
7138}
7139
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007140static void hlua_applet_http_release(struct appctx *ctx)
7141{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007142 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007143 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007144 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007145 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007146}
7147
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007148/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7149 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007150 *
7151 * This function can fail with an abort() due to an Lua critical error.
7152 * We are in the configuration parsing process of HAProxy, this abort() is
7153 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007154 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007155static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7156 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007157{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007158 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007159 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007160
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007161 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007162 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007163 if (!rule->arg.hlua_rule) {
7164 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007165 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007166 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007167
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007168 /* Memory for arguments. */
7169 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7170 if (!rule->arg.hlua_rule->args) {
7171 memprintf(err, "out of memory error");
7172 return ACT_RET_PRS_ERR;
7173 }
7174
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007175 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007176 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007177
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007178 /* Expect some arguments */
7179 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007180 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007181 memprintf(err, "expect %d arguments", fcn->nargs);
7182 return ACT_RET_PRS_ERR;
7183 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007184 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007185 if (!rule->arg.hlua_rule->args[i]) {
7186 memprintf(err, "out of memory error");
7187 return ACT_RET_PRS_ERR;
7188 }
7189 (*cur_arg)++;
7190 }
7191 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007192
Thierry FOURNIER42148732015-09-02 17:17:33 +02007193 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007194 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007195 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007196}
7197
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007198static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7199 struct act_rule *rule, char **err)
7200{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007201 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007202
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007203 /* HTTP applets are forbidden in tcp-request rules.
7204 * HTTP applet request requires everything initilized by
7205 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7206 * The applet will be immediately initilized, but its before
7207 * the call of this analyzer.
7208 */
7209 if (rule->from != ACT_F_HTTP_REQ) {
7210 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7211 return ACT_RET_PRS_ERR;
7212 }
7213
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007214 /* Memory for the rule. */
7215 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7216 if (!rule->arg.hlua_rule) {
7217 memprintf(err, "out of memory error");
7218 return ACT_RET_PRS_ERR;
7219 }
7220
7221 /* Reference the Lua function and store the reference. */
7222 rule->arg.hlua_rule->fcn = *fcn;
7223
7224 /* TODO: later accept arguments. */
7225 rule->arg.hlua_rule->args = NULL;
7226
7227 /* Add applet pointer in the rule. */
7228 rule->applet.obj_type = OBJ_TYPE_APPLET;
7229 rule->applet.name = fcn->name;
7230 rule->applet.init = hlua_applet_http_init;
7231 rule->applet.fct = hlua_applet_http_fct;
7232 rule->applet.release = hlua_applet_http_release;
7233 rule->applet.timeout = hlua_timeout_applet;
7234
7235 return ACT_RET_PRS_OK;
7236}
7237
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007238/* This function is an LUA binding used for registering
7239 * "sample-conv" functions. It expects a converter name used
7240 * in the haproxy configuration file, and an LUA function.
7241 */
7242__LJMP static int hlua_register_action(lua_State *L)
7243{
7244 struct action_kw_list *akl;
7245 const char *name;
7246 int ref;
7247 int len;
7248 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007249 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007250
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007251 /* Initialise the number of expected arguments at 0. */
7252 nargs = 0;
7253
7254 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7255 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007256
7257 /* First argument : converter name. */
7258 name = MAY_LJMP(luaL_checkstring(L, 1));
7259
7260 /* Second argument : environment. */
7261 if (lua_type(L, 2) != LUA_TTABLE)
7262 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7263
7264 /* Third argument : lua function. */
7265 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7266
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007267 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007268 if (lua_gettop(L) >= 4)
7269 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7270
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007271 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007272 lua_pushnil(L);
7273 while (lua_next(L, 2) != 0) {
7274 if (lua_type(L, -1) != LUA_TSTRING)
7275 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7276
7277 /* Check required environment. Only accepted "http" or "tcp". */
7278 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007279 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007280 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007281 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007282 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007283 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007284 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007285
7286 /* Fill fcn. */
7287 fcn->name = strdup(name);
7288 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007289 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007290 fcn->function_ref = ref;
7291
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007292 /* Set the expected number od arguments. */
7293 fcn->nargs = nargs;
7294
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007295 /* List head */
7296 akl->list.n = akl->list.p = NULL;
7297
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007298 /* action keyword. */
7299 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007300 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007301 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007302 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007303
7304 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7305
7306 akl->kw[0].match_pfx = 0;
7307 akl->kw[0].private = fcn;
7308 akl->kw[0].parse = action_register_lua;
7309
7310 /* select the action registering point. */
7311 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7312 tcp_req_cont_keywords_register(akl);
7313 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7314 tcp_res_cont_keywords_register(akl);
7315 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7316 http_req_keywords_register(akl);
7317 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7318 http_res_keywords_register(akl);
7319 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007320 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007321 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7322 "are expected.", lua_tostring(L, -1)));
7323
7324 /* pop the environment string. */
7325 lua_pop(L, 1);
7326 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007327 return ACT_RET_PRS_OK;
7328}
7329
7330static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7331 struct act_rule *rule, char **err)
7332{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007333 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007334
Christopher Faulet280f85b2019-07-15 15:02:04 +02007335 if (px->mode == PR_MODE_HTTP) {
7336 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01007337 return ACT_RET_PRS_ERR;
7338 }
7339
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007340 /* Memory for the rule. */
7341 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7342 if (!rule->arg.hlua_rule) {
7343 memprintf(err, "out of memory error");
7344 return ACT_RET_PRS_ERR;
7345 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007346
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007347 /* Reference the Lua function and store the reference. */
7348 rule->arg.hlua_rule->fcn = *fcn;
7349
7350 /* TODO: later accept arguments. */
7351 rule->arg.hlua_rule->args = NULL;
7352
7353 /* Add applet pointer in the rule. */
7354 rule->applet.obj_type = OBJ_TYPE_APPLET;
7355 rule->applet.name = fcn->name;
7356 rule->applet.init = hlua_applet_tcp_init;
7357 rule->applet.fct = hlua_applet_tcp_fct;
7358 rule->applet.release = hlua_applet_tcp_release;
7359 rule->applet.timeout = hlua_timeout_applet;
7360
7361 return 0;
7362}
7363
7364/* This function is an LUA binding used for registering
7365 * "sample-conv" functions. It expects a converter name used
7366 * in the haproxy configuration file, and an LUA function.
7367 */
7368__LJMP static int hlua_register_service(lua_State *L)
7369{
7370 struct action_kw_list *akl;
7371 const char *name;
7372 const char *env;
7373 int ref;
7374 int len;
7375 struct hlua_function *fcn;
7376
7377 MAY_LJMP(check_args(L, 3, "register_service"));
7378
7379 /* First argument : converter name. */
7380 name = MAY_LJMP(luaL_checkstring(L, 1));
7381
7382 /* Second argument : environment. */
7383 env = MAY_LJMP(luaL_checkstring(L, 2));
7384
7385 /* Third argument : lua function. */
7386 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7387
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007388 /* Allocate and fill the sample fetch keyword struct. */
7389 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7390 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007391 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007392 fcn = calloc(1, sizeof(*fcn));
7393 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007394 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007395
7396 /* Fill fcn. */
7397 len = strlen("<lua.>") + strlen(name) + 1;
7398 fcn->name = calloc(1, len);
7399 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007400 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007401 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7402 fcn->function_ref = ref;
7403
7404 /* List head */
7405 akl->list.n = akl->list.p = NULL;
7406
7407 /* converter keyword. */
7408 len = strlen("lua.") + strlen(name) + 1;
7409 akl->kw[0].kw = calloc(1, len);
7410 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007411 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007412
7413 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7414
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007415 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007416 if (strcmp(env, "tcp") == 0)
7417 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007418 else if (strcmp(env, "http") == 0)
7419 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007420 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007421 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007422 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007423
7424 akl->kw[0].match_pfx = 0;
7425 akl->kw[0].private = fcn;
7426
7427 /* End of array. */
7428 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7429
7430 /* Register this new converter */
7431 service_keywords_register(akl);
7432
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007433 return 0;
7434}
7435
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007436/* This function initialises Lua cli handler. It copies the
7437 * arguments in the Lua stack and create channel IO objects.
7438 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007439static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007440{
7441 struct hlua *hlua;
7442 struct hlua_function *fcn;
7443 int i;
7444 const char *error;
7445
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007446 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007447 appctx->ctx.hlua_cli.fcn = private;
7448
Willy Tarreaubafbe012017-11-24 17:34:44 +01007449 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007450 if (!hlua) {
7451 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007452 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007453 }
7454 HLUA_INIT(hlua);
7455 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007456
7457 /* Create task used by signal to wakeup applets.
7458 * We use the same wakeup fonction than the Lua applet_tcp and
7459 * applet_http. It is absolutely compatible.
7460 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007461 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007462 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007463 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007464 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007465 }
7466 appctx->ctx.hlua_cli.task->nice = 0;
7467 appctx->ctx.hlua_cli.task->context = appctx;
7468 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7469
7470 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007471 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007472 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007473 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007474 }
7475
7476 /* The following Lua calls can fail. */
7477 if (!SET_SAFE_LJMP(hlua->T)) {
7478 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7479 error = lua_tostring(hlua->T, -1);
7480 else
7481 error = "critical error";
7482 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7483 goto error;
7484 }
7485
7486 /* Check stack available size. */
7487 if (!lua_checkstack(hlua->T, 2)) {
7488 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7489 goto error;
7490 }
7491
7492 /* Restore the function in the stack. */
7493 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7494
7495 /* Once the arguments parsed, the CLI is like an AppletTCP,
7496 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007497 */
7498 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7499 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7500 goto error;
7501 }
7502 hlua->nargs = 1;
7503
7504 /* push keywords in the stack. */
7505 for (i = 0; *args[i]; i++) {
7506 /* Check stack available size. */
7507 if (!lua_checkstack(hlua->T, 1)) {
7508 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7509 goto error;
7510 }
7511 lua_pushstring(hlua->T, args[i]);
7512 hlua->nargs++;
7513 }
7514
7515 /* We must initialize the execution timeouts. */
7516 hlua->max_time = hlua_timeout_session;
7517
7518 /* At this point the execution is safe. */
7519 RESET_SAFE_LJMP(hlua->T);
7520
7521 /* It's ok */
7522 return 0;
7523
7524 /* It's not ok. */
7525error:
7526 RESET_SAFE_LJMP(hlua->T);
7527 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007528 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007529 return 1;
7530}
7531
7532static int hlua_cli_io_handler_fct(struct appctx *appctx)
7533{
7534 struct hlua *hlua;
7535 struct stream_interface *si;
7536 struct hlua_function *fcn;
7537
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007538 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007539 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007540 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007541
7542 /* If the stream is disconnect or closed, ldo nothing. */
7543 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7544 return 1;
7545
7546 /* Execute the function. */
7547 switch (hlua_ctx_resume(hlua, 1)) {
7548
7549 /* finished. */
7550 case HLUA_E_OK:
7551 return 1;
7552
7553 /* yield. */
7554 case HLUA_E_AGAIN:
7555 /* We want write. */
7556 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01007557 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007558 /* Set the timeout. */
7559 if (hlua->wake_time != TICK_ETERNITY)
7560 task_schedule(hlua->task, hlua->wake_time);
7561 return 0;
7562
7563 /* finished with error. */
7564 case HLUA_E_ERRMSG:
7565 /* Display log. */
7566 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7567 fcn->name, lua_tostring(hlua->T, -1));
7568 lua_pop(hlua->T, 1);
7569 return 1;
7570
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007571 case HLUA_E_ETMOUT:
7572 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7573 fcn->name);
7574 return 1;
7575
7576 case HLUA_E_NOMEM:
7577 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7578 fcn->name);
7579 return 1;
7580
7581 case HLUA_E_YIELD: /* unexpected */
7582 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7583 fcn->name);
7584 return 1;
7585
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007586 case HLUA_E_ERR:
7587 /* Display log. */
7588 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7589 fcn->name);
7590 return 1;
7591
7592 default:
7593 return 1;
7594 }
7595
7596 return 1;
7597}
7598
7599static void hlua_cli_io_release_fct(struct appctx *appctx)
7600{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007601 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007602 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007603}
7604
7605/* This function is an LUA binding used for registering
7606 * new keywords in the cli. It expects a list of keywords
7607 * which are the "path". It is limited to 5 keywords. A
7608 * description of the command, a function to be executed
7609 * for the parsing and a function for io handlers.
7610 */
7611__LJMP static int hlua_register_cli(lua_State *L)
7612{
7613 struct cli_kw_list *cli_kws;
7614 const char *message;
7615 int ref_io;
7616 int len;
7617 struct hlua_function *fcn;
7618 int index;
7619 int i;
7620
7621 MAY_LJMP(check_args(L, 3, "register_cli"));
7622
7623 /* First argument : an array of maximum 5 keywords. */
7624 if (!lua_istable(L, 1))
7625 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7626
7627 /* Second argument : string with contextual message. */
7628 message = MAY_LJMP(luaL_checkstring(L, 2));
7629
7630 /* Third and fourth argument : lua function. */
7631 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7632
7633 /* Allocate and fill the sample fetch keyword struct. */
7634 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7635 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007636 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007637 fcn = calloc(1, sizeof(*fcn));
7638 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007639 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007640
7641 /* Fill path. */
7642 index = 0;
7643 lua_pushnil(L);
7644 while(lua_next(L, 1) != 0) {
7645 if (index >= 5)
7646 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7647 if (lua_type(L, -1) != LUA_TSTRING)
7648 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7649 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7650 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007651 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007652 index++;
7653 lua_pop(L, 1);
7654 }
7655
7656 /* Copy help message. */
7657 cli_kws->kw[0].usage = strdup(message);
7658 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007659 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007660
7661 /* Fill fcn io handler. */
7662 len = strlen("<lua.cli>") + 1;
7663 for (i = 0; i < index; i++)
7664 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7665 fcn->name = calloc(1, len);
7666 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007667 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007668 strncat((char *)fcn->name, "<lua.cli", len);
7669 for (i = 0; i < index; i++) {
7670 strncat((char *)fcn->name, ".", len);
7671 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7672 }
7673 strncat((char *)fcn->name, ">", len);
7674 fcn->function_ref = ref_io;
7675
7676 /* Fill last entries. */
7677 cli_kws->kw[0].private = fcn;
7678 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7679 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7680 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7681
7682 /* Register this new converter */
7683 cli_register_kw(cli_kws);
7684
7685 return 0;
7686}
7687
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007688static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7689 struct proxy *defpx, const char *file, int line,
7690 char **err, unsigned int *timeout)
7691{
7692 const char *error;
7693
7694 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02007695 if (error == PARSE_TIME_OVER) {
7696 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
7697 args[1], args[0]);
7698 return -1;
7699 }
7700 else if (error == PARSE_TIME_UNDER) {
7701 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
7702 args[1], args[0]);
7703 return -1;
7704 }
7705 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007706 memprintf(err, "%s: invalid timeout", args[0]);
7707 return -1;
7708 }
7709 return 0;
7710}
7711
7712static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7713 struct proxy *defpx, const char *file, int line,
7714 char **err)
7715{
7716 return hlua_read_timeout(args, section_type, curpx, defpx,
7717 file, line, err, &hlua_timeout_session);
7718}
7719
7720static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7721 struct proxy *defpx, const char *file, int line,
7722 char **err)
7723{
7724 return hlua_read_timeout(args, section_type, curpx, defpx,
7725 file, line, err, &hlua_timeout_task);
7726}
7727
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007728static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7729 struct proxy *defpx, const char *file, int line,
7730 char **err)
7731{
7732 return hlua_read_timeout(args, section_type, curpx, defpx,
7733 file, line, err, &hlua_timeout_applet);
7734}
7735
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007736static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7737 struct proxy *defpx, const char *file, int line,
7738 char **err)
7739{
7740 char *error;
7741
7742 hlua_nb_instruction = strtoll(args[1], &error, 10);
7743 if (*error != '\0') {
7744 memprintf(err, "%s: invalid number", args[0]);
7745 return -1;
7746 }
7747 return 0;
7748}
7749
Willy Tarreau32f61e22015-03-18 17:54:59 +01007750static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7751 struct proxy *defpx, const char *file, int line,
7752 char **err)
7753{
7754 char *error;
7755
7756 if (*(args[1]) == 0) {
7757 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7758 return -1;
7759 }
7760 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7761 if (*error != '\0') {
7762 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7763 return -1;
7764 }
7765 return 0;
7766}
7767
7768
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007769/* This function is called by the main configuration key "lua-load". It loads and
7770 * execute an lua file during the parsing of the HAProxy configuration file. It is
7771 * the main lua entry point.
7772 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007773 * This function runs with the HAProxy keywords API. It returns -1 if an error
7774 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007775 *
7776 * In some error case, LUA set an error message in top of the stack. This function
7777 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007778 *
7779 * This function can fail with an abort() due to an Lua critical error.
7780 * We are in the configuration parsing process of HAProxy, this abort() is
7781 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007782 */
7783static int hlua_load(char **args, int section_type, struct proxy *curpx,
7784 struct proxy *defpx, const char *file, int line,
7785 char **err)
7786{
7787 int error;
7788
7789 /* Just load and compile the file. */
7790 error = luaL_loadfile(gL.T, args[1]);
7791 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007792 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007793 lua_pop(gL.T, 1);
7794 return -1;
7795 }
7796
7797 /* If no syntax error where detected, execute the code. */
7798 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7799 switch (error) {
7800 case LUA_OK:
7801 break;
7802 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007803 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007804 lua_pop(gL.T, 1);
7805 return -1;
7806 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007807 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007808 return -1;
7809 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007810 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007811 lua_pop(gL.T, 1);
7812 return -1;
7813 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007814 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007815 lua_pop(gL.T, 1);
7816 return -1;
7817 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007818 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007819 lua_pop(gL.T, 1);
7820 return -1;
7821 }
7822
7823 return 0;
7824}
7825
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01007826/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
7827 * in the given <ctx>.
7828 */
7829static int hlua_prepend_path(struct hlua ctx, char *type, char *path)
7830{
7831 lua_getglobal(ctx.T, "package"); /* push package variable */
7832 lua_pushstring(ctx.T, path); /* push given path */
7833 lua_pushstring(ctx.T, ";"); /* push semicolon */
7834 lua_getfield(ctx.T, -3, type); /* push old path */
7835 lua_concat(ctx.T, 3); /* concatenate to new path */
7836 lua_setfield(ctx.T, -2, type); /* store new path */
7837 lua_pop(ctx.T, 1); /* pop package variable */
7838
7839 return 0;
7840}
7841
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01007842static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
7843 struct proxy *defpx, const char *file, int line,
7844 char **err)
7845{
7846 char *path;
7847 char *type = "path";
7848 if (too_many_args(2, args, err, NULL)) {
7849 return -1;
7850 }
7851
7852 if (!(*args[1])) {
7853 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
7854 return -1;
7855 }
7856 path = args[1];
7857
7858 if (*args[2]) {
7859 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
7860 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
7861 return -1;
7862 }
7863 type = args[2];
7864 }
7865
7866 return hlua_prepend_path(gL, type, path);
7867}
7868
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007869/* configuration keywords declaration */
7870static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01007871 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007872 { CFG_GLOBAL, "lua-load", hlua_load },
7873 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7874 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007875 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007876 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007877 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007878 { 0, NULL, NULL },
7879}};
7880
Willy Tarreau0108d902018-11-25 19:14:37 +01007881INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
7882
Christopher Fauletafd8f102018-11-08 11:34:21 +01007883
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007884/* This function can fail with an abort() due to an Lua critical error.
7885 * We are in the initialisation process of HAProxy, this abort() is
7886 * tolerated.
7887 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007888int hlua_post_init()
7889{
7890 struct hlua_init_function *init;
7891 const char *msg;
7892 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007893 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007894
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007895 /* Call post initialisation function in safe environement. */
7896 if (!SET_SAFE_LJMP(gL.T)) {
7897 if (lua_type(gL.T, -1) == LUA_TSTRING)
7898 error = lua_tostring(gL.T, -1);
7899 else
7900 error = "critical error";
7901 fprintf(stderr, "Lua post-init: %s.\n", error);
7902 exit(1);
7903 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02007904
7905#if USE_OPENSSL
7906 /* Initialize SSL server. */
7907 if (socket_ssl.xprt->prepare_srv) {
7908 int saved_used_backed = global.ssl_used_backend;
7909 // don't affect maxconn automatic computation
7910 socket_ssl.xprt->prepare_srv(&socket_ssl);
7911 global.ssl_used_backend = saved_used_backed;
7912 }
7913#endif
7914
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007915 hlua_fcn_post_init(gL.T);
7916 RESET_SAFE_LJMP(gL.T);
7917
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007918 list_for_each_entry(init, &hlua_init_functions, l) {
7919 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7920 ret = hlua_ctx_resume(&gL, 0);
7921 switch (ret) {
7922 case HLUA_E_OK:
7923 lua_pop(gL.T, -1);
7924 return 1;
7925 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007926 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007927 return 0;
7928 case HLUA_E_ERRMSG:
7929 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007930 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007931 return 0;
7932 case HLUA_E_ERR:
7933 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007934 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007935 return 0;
7936 }
7937 }
7938 return 1;
7939}
7940
Willy Tarreau32f61e22015-03-18 17:54:59 +01007941/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7942 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7943 * is the previously allocated size or the kind of object in case of a new
7944 * allocation. <nsize> is the requested new size.
7945 */
7946static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7947{
7948 struct hlua_mem_allocator *zone = ud;
7949
7950 if (nsize == 0) {
7951 /* it's a free */
7952 if (ptr)
7953 zone->allocated -= osize;
7954 free(ptr);
7955 return NULL;
7956 }
7957
7958 if (!ptr) {
7959 /* it's a new allocation */
7960 if (zone->limit && zone->allocated + nsize > zone->limit)
7961 return NULL;
7962
7963 ptr = malloc(nsize);
7964 if (ptr)
7965 zone->allocated += nsize;
7966 return ptr;
7967 }
7968
7969 /* it's a realloc */
7970 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7971 return NULL;
7972
7973 ptr = realloc(ptr, nsize);
7974 if (ptr)
7975 zone->allocated += nsize - osize;
7976 return ptr;
7977}
7978
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007979/* Ithis function can fail with an abort() due to an Lua critical error.
7980 * We are in the initialisation process of HAProxy, this abort() is
7981 * tolerated.
7982 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007983void hlua_init(void)
7984{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007985 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007986 int idx;
7987 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007988 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007989 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007990 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007991#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007992 struct srv_kw *kw;
7993 int tmp_error;
7994 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007995 char *args[] = { /* SSL client configuration. */
7996 "ssl",
7997 "verify",
7998 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007999 NULL
8000 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008001#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008002
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008003 /* Init main lua stack. */
8004 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008005 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008006 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008007 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008008 hlua_sethlua(&gL);
8009 gL.Tref = LUA_REFNIL;
8010 gL.task = NULL;
8011
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008012 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008013 * the Lua function can fail with an abort. We are in the initialisation
8014 * process of HAProxy, this abort() is tolerated.
8015 */
8016
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008017 /* Initialise lua. */
8018 luaL_openlibs(gL.T);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01008019#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
8020#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
8021#ifdef HLUA_PREPEND_PATH
8022 hlua_prepend_path(gL, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
8023#endif
8024#ifdef HLUA_PREPEND_CPATH
8025 hlua_prepend_path(gL, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
8026#endif
8027#undef HLUA_PREPEND_PATH_TOSTRING
8028#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008029
Thierry Fournier75933d42016-01-21 09:30:18 +01008030 /* Set safe environment for the initialisation. */
8031 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008032 if (lua_type(gL.T, -1) == LUA_TSTRING)
8033 error_msg = lua_tostring(gL.T, -1);
8034 else
8035 error_msg = "critical error";
8036 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008037 exit(1);
8038 }
8039
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008040 /*
8041 *
8042 * Create "core" object.
8043 *
8044 */
8045
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008046 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008047 lua_newtable(gL.T);
8048
8049 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008050 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008051 hlua_class_const_int(gL.T, log_levels[i], i);
8052
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008053 /* Register special functions. */
8054 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008055 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008056 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008057 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008058 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008059 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008060 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008061 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008062 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008063 hlua_class_function(gL.T, "sleep", hlua_sleep);
8064 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008065 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8066 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8067 hlua_class_function(gL.T, "set_map", hlua_set_map);
8068 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008069 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008070 hlua_class_function(gL.T, "log", hlua_log);
8071 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8072 hlua_class_function(gL.T, "Info", hlua_log_info);
8073 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8074 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008075 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008076 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008077
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008078 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008079
8080 /*
8081 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008082 * Create "act" object.
8083 *
8084 */
8085
8086 /* This table entry is the object "act" base. */
8087 lua_newtable(gL.T);
8088
8089 /* push action return constants */
8090 hlua_class_const_int(gL.T, "CONTINUE", ACT_RET_CONT);
8091 hlua_class_const_int(gL.T, "STOP", ACT_RET_STOP);
8092 hlua_class_const_int(gL.T, "YIELD", ACT_RET_YIELD);
8093 hlua_class_const_int(gL.T, "ERROR", ACT_RET_ERR);
8094 hlua_class_const_int(gL.T, "DONE", ACT_RET_DONE);
8095 hlua_class_const_int(gL.T, "DENY", ACT_RET_DENY);
8096 hlua_class_const_int(gL.T, "ABORT", ACT_RET_ABRT);
8097 hlua_class_const_int(gL.T, "INVALID", ACT_RET_INV);
8098
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008099 hlua_class_function(gL.T, "wake_time", hlua_action_wake_time);
8100
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008101 lua_setglobal(gL.T, "act");
8102
8103 /*
8104 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008105 * Register class Map
8106 *
8107 */
8108
8109 /* This table entry is the object "Map" base. */
8110 lua_newtable(gL.T);
8111
8112 /* register pattern types. */
8113 for (i=0; i<PAT_MATCH_NUM; i++)
8114 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008115 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008116 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8117 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008118 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008119
8120 /* register constructor. */
8121 hlua_class_function(gL.T, "new", hlua_map_new);
8122
8123 /* Create and fill the metatable. */
8124 lua_newtable(gL.T);
8125
8126 /* Create and fille the __index entry. */
8127 lua_pushstring(gL.T, "__index");
8128 lua_newtable(gL.T);
8129
8130 /* Register . */
8131 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8132 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8133
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008134 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008135
Thierry Fournier45e78d72016-02-19 18:34:46 +01008136 /* Register previous table in the registry with reference and named entry.
8137 * The function hlua_register_metatable() pops the stack, so we
8138 * previously create a copy of the table.
8139 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008140 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008141 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008142
8143 /* Assign the metatable to the mai Map object. */
8144 lua_setmetatable(gL.T, -2);
8145
8146 /* Set a name to the table. */
8147 lua_setglobal(gL.T, "Map");
8148
8149 /*
8150 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008151 * Register class Channel
8152 *
8153 */
8154
8155 /* Create and fill the metatable. */
8156 lua_newtable(gL.T);
8157
8158 /* Create and fille the __index entry. */
8159 lua_pushstring(gL.T, "__index");
8160 lua_newtable(gL.T);
8161
8162 /* Register . */
8163 hlua_class_function(gL.T, "get", hlua_channel_get);
8164 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8165 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8166 hlua_class_function(gL.T, "set", hlua_channel_set);
8167 hlua_class_function(gL.T, "append", hlua_channel_append);
8168 hlua_class_function(gL.T, "send", hlua_channel_send);
8169 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8170 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8171 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008172 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01008173 hlua_class_function(gL.T, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008174
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008175 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008176
8177 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008178 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008179
8180 /*
8181 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008182 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008183 *
8184 */
8185
8186 /* Create and fill the metatable. */
8187 lua_newtable(gL.T);
8188
8189 /* Create and fille the __index entry. */
8190 lua_pushstring(gL.T, "__index");
8191 lua_newtable(gL.T);
8192
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008193 /* Browse existing fetches and create the associated
8194 * object method.
8195 */
8196 sf = NULL;
8197 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8198
8199 /* Dont register the keywork if the arguments check function are
8200 * not safe during the runtime.
8201 */
8202 if ((sf->val_args != NULL) &&
8203 (sf->val_args != val_payload_lv) &&
8204 (sf->val_args != val_hdr))
8205 continue;
8206
8207 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8208 * by an underscore.
8209 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008210 strncpy(trash.area, sf->kw, trash.size);
8211 trash.area[trash.size - 1] = '\0';
8212 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008213 if (*p == '.' || *p == '-' || *p == '+')
8214 *p = '_';
8215
8216 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008217 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008218 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008219 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008220 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008221 }
8222
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008223 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008224
8225 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008226 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008227
8228 /*
8229 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008230 * Register class Converters
8231 *
8232 */
8233
8234 /* Create and fill the metatable. */
8235 lua_newtable(gL.T);
8236
8237 /* Create and fill the __index entry. */
8238 lua_pushstring(gL.T, "__index");
8239 lua_newtable(gL.T);
8240
8241 /* Browse existing converters and create the associated
8242 * object method.
8243 */
8244 sc = NULL;
8245 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8246 /* Dont register the keywork if the arguments check function are
8247 * not safe during the runtime.
8248 */
8249 if (sc->val_args != NULL)
8250 continue;
8251
8252 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8253 * by an underscore.
8254 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008255 strncpy(trash.area, sc->kw, trash.size);
8256 trash.area[trash.size - 1] = '\0';
8257 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008258 if (*p == '.' || *p == '-' || *p == '+')
8259 *p = '_';
8260
8261 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008262 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008263 lua_pushlightuserdata(gL.T, sc);
8264 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008265 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008266 }
8267
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008268 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008269
8270 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008271 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008272
8273 /*
8274 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008275 * Register class HTTP
8276 *
8277 */
8278
8279 /* Create and fill the metatable. */
8280 lua_newtable(gL.T);
8281
8282 /* Create and fille the __index entry. */
8283 lua_pushstring(gL.T, "__index");
8284 lua_newtable(gL.T);
8285
8286 /* Register Lua functions. */
8287 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8288 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8289 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8290 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8291 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8292 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8293 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8294 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8295 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8296 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8297
8298 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8299 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8300 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8301 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8302 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8303 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008304 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008305
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008306 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008307
8308 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008309 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008310
8311 /*
8312 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008313 * Register class AppletTCP
8314 *
8315 */
8316
8317 /* Create and fill the metatable. */
8318 lua_newtable(gL.T);
8319
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008320 /* Create and fille the __index entry. */
8321 lua_pushstring(gL.T, "__index");
8322 lua_newtable(gL.T);
8323
8324 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008325 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8326 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8327 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8328 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8329 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008330 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8331 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8332 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008333
8334 lua_settable(gL.T, -3);
8335
8336 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008337 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008338
8339 /*
8340 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008341 * Register class AppletHTTP
8342 *
8343 */
8344
8345 /* Create and fill the metatable. */
8346 lua_newtable(gL.T);
8347
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008348 /* Create and fille the __index entry. */
8349 lua_pushstring(gL.T, "__index");
8350 lua_newtable(gL.T);
8351
8352 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008353 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8354 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008355 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8356 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8357 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008358 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8359 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8360 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8361 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8362 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8363 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8364
8365 lua_settable(gL.T, -3);
8366
8367 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008368 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008369
8370 /*
8371 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008372 * Register class TXN
8373 *
8374 */
8375
8376 /* Create and fill the metatable. */
8377 lua_newtable(gL.T);
8378
8379 /* Create and fille the __index entry. */
8380 lua_pushstring(gL.T, "__index");
8381 lua_newtable(gL.T);
8382
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008383 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008384 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8385 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8386 hlua_class_function(gL.T, "set_var", hlua_set_var);
8387 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8388 hlua_class_function(gL.T, "get_var", hlua_get_var);
8389 hlua_class_function(gL.T, "done", hlua_txn_done);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008390 hlua_class_function(gL.T, "reply", hlua_txn_reply_new);
Patrick Hemmer268a7072018-05-11 12:52:31 -04008391 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8392 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8393 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8394 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8395 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8396 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8397 hlua_class_function(gL.T, "log", hlua_txn_log);
8398 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8399 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8400 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8401 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008402
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008403 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008404
8405 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008406 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008407
8408 /*
8409 *
Christopher Faulet700d9e82020-01-31 12:21:52 +01008410 * Register class reply
8411 *
8412 */
8413 lua_newtable(gL.T);
8414 lua_pushstring(gL.T, "__index");
8415 lua_newtable(gL.T);
8416 hlua_class_function(gL.T, "set_status", hlua_txn_reply_set_status);
8417 hlua_class_function(gL.T, "add_header", hlua_txn_reply_add_header);
8418 hlua_class_function(gL.T, "del_header", hlua_txn_reply_del_header);
8419 hlua_class_function(gL.T, "set_body", hlua_txn_reply_set_body);
8420 lua_settable(gL.T, -3); /* Sets the __index entry. */
8421 class_txn_reply_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
8422
8423
8424 /*
8425 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008426 * Register class Socket
8427 *
8428 */
8429
8430 /* Create and fill the metatable. */
8431 lua_newtable(gL.T);
8432
8433 /* Create and fille the __index entry. */
8434 lua_pushstring(gL.T, "__index");
8435 lua_newtable(gL.T);
8436
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008437#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008438 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008439#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008440 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8441 hlua_class_function(gL.T, "send", hlua_socket_send);
8442 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8443 hlua_class_function(gL.T, "close", hlua_socket_close);
8444 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8445 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8446 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8447 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8448
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008449 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008450
8451 /* Register the garbage collector entry. */
8452 lua_pushstring(gL.T, "__gc");
8453 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008454 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008455
8456 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008457 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008458
8459 /* Proxy and server configuration initialisation. */
8460 memset(&socket_proxy, 0, sizeof(socket_proxy));
8461 init_new_proxy(&socket_proxy);
8462 socket_proxy.parent = NULL;
8463 socket_proxy.last_change = now.tv_sec;
8464 socket_proxy.id = "LUA-SOCKET";
8465 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8466 socket_proxy.maxconn = 0;
8467 socket_proxy.accept = NULL;
8468 socket_proxy.options2 |= PR_O2_INDEPSTR;
8469 socket_proxy.srv = NULL;
8470 socket_proxy.conn_retries = 0;
8471 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8472
8473 /* Init TCP server: unchanged parameters */
8474 memset(&socket_tcp, 0, sizeof(socket_tcp));
8475 socket_tcp.next = NULL;
8476 socket_tcp.proxy = &socket_proxy;
8477 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8478 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008479 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008480 socket_tcp.priv_conns = NULL;
8481 socket_tcp.idle_conns = NULL;
8482 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008483 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008484 socket_tcp.last_change = 0;
8485 socket_tcp.id = "LUA-TCP-CONN";
8486 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8487 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8488 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8489
8490 /* XXX: Copy default parameter from default server,
8491 * but the default server is not initialized.
8492 */
8493 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8494 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8495 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8496 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8497 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8498 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8499 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8500 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8501 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8502 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8503
8504 socket_tcp.check.status = HCHK_STATUS_INI;
8505 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8506 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8507 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8508 socket_tcp.check.server = &socket_tcp;
8509
8510 socket_tcp.agent.status = HCHK_STATUS_INI;
8511 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8512 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8513 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8514 socket_tcp.agent.server = &socket_tcp;
8515
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008516 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008517
8518#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008519 /* Init TCP server: unchanged parameters */
8520 memset(&socket_ssl, 0, sizeof(socket_ssl));
8521 socket_ssl.next = NULL;
8522 socket_ssl.proxy = &socket_proxy;
8523 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8524 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008525 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01008526 socket_ssl.priv_conns = NULL;
8527 socket_ssl.idle_conns = NULL;
8528 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008529 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008530 socket_ssl.last_change = 0;
8531 socket_ssl.id = "LUA-SSL-CONN";
8532 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8533 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8534 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8535
8536 /* XXX: Copy default parameter from default server,
8537 * but the default server is not initialized.
8538 */
8539 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8540 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8541 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8542 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8543 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8544 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8545 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8546 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8547 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8548 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8549
8550 socket_ssl.check.status = HCHK_STATUS_INI;
8551 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8552 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8553 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8554 socket_ssl.check.server = &socket_ssl;
8555
8556 socket_ssl.agent.status = HCHK_STATUS_INI;
8557 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8558 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8559 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8560 socket_ssl.agent.server = &socket_ssl;
8561
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008562 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008563 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008564
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008565 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008566 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8567 /*
8568 *
8569 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008570 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008571 * features like client certificates and ssl_verify.
8572 *
8573 */
8574 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8575 if (tmp_error != 0) {
8576 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8577 abort(); /* This must be never arrives because the command line
8578 not editable by the user. */
8579 }
8580 idx += kw->skip;
8581 }
8582 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008583#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008584
8585 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008586}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008587
Willy Tarreau80713382018-11-26 10:19:54 +01008588static void hlua_register_build_options(void)
8589{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008590 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008591
Willy Tarreaubb57d942016-12-21 19:04:56 +01008592 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8593 hap_register_build_opts(ptr, 1);
8594}
Willy Tarreau80713382018-11-26 10:19:54 +01008595
8596INITCALL0(STG_REGISTER, hlua_register_build_options);